Skip to main content
GameDev.net gamedev.net
🔒 Locked

STL find

Started by MagTDK May 22, 2002 at 10:46 PM 3 replies 200+ views
Original Post
MagTDK
MagTDK
I found this example at http://www.sgi.com/tech/stl/find.html
      
list<int> L;
L.push_back(3);
L.push_back(1);
L.push_back(7);

list<int>::iterator result = find(L.begin(), L.end(), 7);
  
I understand this, but what if I have a list like so:
        
class CTest
{
  int idata;
  int idata2;
  float idata3;
};

list<int> mylist;

CTest myTest;

myTest.idata = 5;
myTest.idata2 = 10;
myTest.idata3 = 20.00f

mylist.push_back(myTest);

myTest.idata = 2;
myTest.idata2 = 4;
myTest.idata3 = 8.00f

mylist.push_back(myTest);

list<CTest>::iterator result = find(mylist.begin(), mylist.end(), ?);
  
How do I fill the last parameter of the find function? For example if I wanted to find if idata2 equals 4? [edited by - MagTDK on May 22, 2002 11:49:59 PM]
Shannon Barber
Shannon Barber
You have to write a functor, "Effective STL" by Scott Meyers helped me quite a bit on working with the STL


  
struct search_for_idata2
{
const int sought;
search_for_idata2(int seek) : sought(seek){}
bool operator()(const Test& test)
{
return test.idata == sought;
}
};


//This is what needs to happen

search_for_idata2 search_functor(4);
std::find_if(.begin(), .end(), search_functor);

//Typically it''s written like this:

std::find_if(.begin(), .end(), search_for_idata2(4) );
//This create a temporary instance of search_for_idata2, the

// ending () does that, and then the 4 is passed as the ctor arguement




There''s a couple of slicker ways to do it, but that''s the most straight forward.
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Oluseyi
Oluseyi
IIRC, std::list has its own find member method for specifically this reason. But for complex list elements, you''ll still need a search functor.
Stoffel
Stoffel
Containers that specialize find are map, set, multimap and multiset. This is because std::find is O(N), and indeed can be no better for list, deque or vector. But the ordered containers can implement find O(lgN), so they specialize it.

MagTDK
MagTDK

Thanks for your help.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.