Re: adding search capability to a Vector
On 9 Feb., 09:55, Kei <k7m...@gmail.com> wrote:
I am trying to add a simple search behaviour to a STL Vector like the
following:
//---- declaration ---
typedef struct {
std::string name;
std::string favouriteFood;} TBuddy;
This struct isn't C compatible anyway so you might want to define it
the C++ way:
struct TBuddy {
//...
};
typedef TBuddy* PBuddy;
Why do you want to store pointers in the vector?
class TBuddies: public std::vector<PBuddy> {
public:
std::string favouriteFoodOf(const std::string& name) cons=
t;
};
Why public inheritance? Why making your own class?
Use std::find_if that is defined in <algorithm>
http://www.cplusplus.com/reference/algorithm/find_if.html
//---- implementation ---
std::string TBuddies::findValue(const std::string& name) const
{
for(TBuddies::iterator i= this->begin(); i!= this->en=
d(); ++i) {
PBuddy b = *i;
if(b->name ==s) return b->favouriteFo=
od;
}
return "";
}
Since the member function is declared const, 'this' points to a const
TBuddies object. The functions begin() and end() are "const
overloaded". Their const versions return instances of const_iterator.
Anyways, inside findValue you don't need access to any protected
fields. You better make it a free function that calles std::find_if.
Or better yet: use a std::map. It looks like std::map (instead of
std::vector) is what you are looking for.
Cheers!
SG