STL Vectors

Started by
10 comments, last by zackriggle 21 years, 1 month ago
Okay I guess that WASN''T my last question. The whole STL thing is getting on my nerves more than pointers . Anyways, here''s the question:

I understand that std::find() can find a certain element in a vector or other STL container... but, if I have a vector of an object, can I search through the vector for an object with a member that is a certain value?

Example

  class MyClass{public:   int a;};void main(){  std::vector<MyClass> MyVector;  MyClass mc;  mc.a = 15;  MyVector.push_back(mc);  mc.a = 7;  MyVector.push_back(mc);  mc.a = 15144;  MyVector.push_back(mc);  mc.a = 12457;  MyVector.push_back(mc);  std::vector<MyClass>::iterator i;  i = Search(MyVector,a,7); // <-- Searches for an element whose                            // member ''a'' is set to 7...  // And use A to do whatever is neccesary...};  
Advertisement
If you want to do this through generic programming (using STL algorithms and suchlike, you will want to look into std::find_if. Just make a predicate functor that checks member equality, and feed it in to find_if. This is the "right" STL way to do it. But if you're like me, or most others, you'll just iterate through the freakin' container. With few exceptions, the STL algorithms are not appreciably faster than manual iteration, and some have a habit of incurring a lot of calling overhead.

Oh, if you haven't found it yet: the best STL docs are at http://www.sgi.com/tech/stl/ (memorize this URL).

How appropriate. You fight like a cow.

[edited by - sneftel on March 17, 2003 2:04:35 AM]

This topic is closed to new replies.

Advertisement