find() syntax with obj member data

S

solartimba

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);
 
M

Mike Wahler

solartimba said:
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::eek:stream& out(std::eek:stream& os) const
{
return os << id << ' ' << name;
}
};

std::eek:stream& operator<<(std::eek:stream& 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top