Discussion:
STL List Searching (find)
(too old to reply)
Mike Copeland
2010-03-04 01:10:08 UTC
Permalink
I've declared the data structure below and have loaded it with data.
Now, I need to find the appropriate "stateCode" for selected
"stateName" values. I tried to develop an operator to use with a
"find" call, but I get a C2678 error (MS VS6.0) on the "find" statement.
What am I doing wrong? TIA

struct StateData
{
string stateName;
string stateCode;
bool operator==(const StateData &rhs) const
{
return stateName == rhs.stateName;
}
} stateWork;
typedef list<StateData> StateData;
StateData stateList;
list<StateData>::iterator stIter;

stIter = find(stateList.begin(), stateList.end(), "Colorado"); // C2678
error
Ulrich Eckhardt
2010-03-04 08:12:36 UTC
Permalink
Post by Mike Copeland
Now, I need to find the appropriate "stateCode" for selected
"stateName" values.
Have you considered std::map?
Post by Mike Copeland
I tried to develop an operator to use with a "find" call, but I get
a C2678 error (MS VS6.0) on the "find" statement.
Two things:
1. It's VS98 or VC6 which you probably mean. In any case, it is by more than
ten years outdated and even predates the C++ standard. That means that even
legit code could fail to compile. Upgrade.
2. I don't know what C2678 is, you could give the error message, too.
Anyway, I see the problem already...
Post by Mike Copeland
struct StateData
{
string stateName;
string stateCode;
bool operator==(const StateData &rhs) const
{
return stateName == rhs.stateName;
}
} stateWork;
^^^^^^^^^ Why?

Note here: While not technically wrong, your equality operator sucks,
because it only checks for equality in the state name.
Post by Mike Copeland
typedef list<StateData> StateData;
StateData stateList;
list<StateData>::iterator stIter;
Use the typedef:

StateData::iterator stIter;
Post by Mike Copeland
stIter = find(stateList.begin(), stateList.end(), "Colorado");
The string literal is not a StateData object nor is it convertible to one.
What you need to do there is this:

StateData tmp;
tmp.stateName = "Colorado";
it = find(stateList.begin(), stateList.end(),
tmp);

But, that's still not what you really want. Instead, you want to use a
search with a predicate:

it = find_if(stateList.begin(), stateList.end(),
predicate_name("Colorado"));

Where "predicate_name" is a functor that is defined like this:

struct predicate_name
{
explicit predicate_name(std::string const& n):
name(n)
{}
bool operator()(StateData const& s) const
{
return name == s.stateName;
}
std::string name;
};

You can then drop the equality operator.

Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite

Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
Continue reading on narkive:
Loading...