Re: STL List Searching (find)
Mike Copeland wrote:
Now, I need to find the appropriate "stateCode" for selected
"stateName" values.
Have you considered std::map?
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...
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.
typedef list<StateData> StateData;
StateData stateList;
list<StateData>::iterator stIter;
Use the typedef:
StateData::iterator stIter;
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