Wednesday, March 18, 2009

c++ stl - check if vector contains item

std::find is solution!

Whenever I want to check if vector contains satin item my preferred way is to use std::find.
//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>

class Person
{
public:
    Person();
    Person(int a, std::string n);
    Person(const Person& src);
    
    bool Person::operator==(const Person& src);

    int age;
    std::string name;
};

Person::Person()
: age(0)
, name("")
{};

Person::Person(int a, std::string n)
:age(a)
,name(n)
{};

Person::Person(const Person& src)
{
    age = src.age;
    name = src.name;
};

bool Person::operator==(const Person& src)
{
    if (name != src.name) return false;
    if (age != src.age) return false;
    return true;
}

int main(int count, char** args)
{
std::vector<Person> personVec;
Person p1(10, "Person1");
Person p2(12, "Person2");
Person p3(12, "Person3");

personVec.push_back(p1);
personVec.push_back(p2);
personVec.push_back(p3);

// use of find
Person f(12, "Person2"), f2(13, "Person1000");
std::vector<Person>::iterator it;

std::cout << "Find Person2" << std::endl;
it = std::find(personVec.begin(), personVec.end(), f);

if (it == personVec.end()){
    std::cout << " Person not found! " << std::endl;
}
std::cout << " Found person: " << it->name 
           << ":" << it->age 
           << " vector index: " << it - personVec.begin()
           << std::endl;

std::cout << "Find Person1000" << std::endl;
it = std::find(personVec.begin(), personVec.end(), f2);

if (it == personVec.end()){
    std::cout << " Person not found! " << std::endl;
}
std::cout << " Found person: " << it->name 
           << ":"<< it->age 
           << " vector index: " << it - personVec.begin()
           << std::endl;
 
}