"solartimba" <ka*****@hotmail.com> wrote in message
news:1a**************************@posting.google.c om...
If I have a class like:
class cExample
{
private:
string name;
int id;
}
and I have a vector of these objects vector<cExample> v.
How do I use find() to get a particular id? (I know maps are better at
this but I need to use a vector)
This wouldn't work, right? vIter=find(v.begin(),v.end(),4);
#include <algorithm>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
class cExample
{
std::string name;
int id;
public:
cExample(const std::string& s, int i) : name(s), id(i)
{ }
bool operator==(int i) const
{
return id == i;
}
std::ostream& out(std::ostream& os) const
{
return os << id << ' ' << name;
}
};
std::ostream& operator<<(std::ostream& os, const cExample& e)
{
return e.out(os);
}
std::vector<cExample>::const_iterator lookup
(const std::vector<cExample>& v, int id)
{
std::vector<cExample>::const_iterator it
(std::find(v.begin(), v.end(), id));
if(it != v.end())
std::cout << *it << '\n';
else
std::cout << id << " [not found]\n";
return it;
}
int main()
{
std::vector<cExample> v;
v.push_back(cExample("John", 2));
v.push_back(cExample("Paul", 4));
v.push_back(cExample("George", 6));
v.push_back(cExample("Ringo", 8));
for(int i = 0; i < 10; ++i)
lookup(v, i);
return 0;
}
-Mike