stl标准算法find可以用在map上吗
map有自己的find算法没错,但是现在有一个需求,要在map的某一些键的范围上查找second信息、我用stl标准find,在map上编译不过去。
请问,标准算法可以用在map上吗,可否给几行例子? 贴出错误信息。 看参考资料,应该用类提供的find方法,效率更好。
Special Search Operations
Like sets and multisets, maps and multimaps provide special search member functions that perform better because of their internal tree structure (Table 6.28).
The find() member function searches for the first element that has the appropriate key and returns its iterator position. If no such element is found, find() returns end() of the container. You can't use the find() member function to search for an element that has a certain value. Instead, you have to use a general algorithm such as the find_if() algorithm, or program an explicit loop. Here is an example of a simple loop that does something with each element that has a certain value:
std::multimap<std::string,float> coll;
...
//do something with all elements having a certain value
std::multimap<std::string,float>::iterator pos;
for (pos = coll.begin(); pos != coll.end(); ++pos) {
if (pos->second == value) {
do_something();
}
}
Table 6.28. Special Search Operations of Maps and Multimaps OperationEffect
count(key)Returns the number of elements with key key
find(key)Returns the position of the first element with key key or end()
lower_bound(key)Returns the first position where an element with key key would get inserted (the first element with key >= key)
upper_bound(key)Returns the last position where an element with key key would get inserted (the first element with key > key)
equal_range(key)Returns the first and last positions where elements with key key would get inserted (the range of elements with key == key)
Be careful when you want to use such a loop to remove elements. It might happen that you saw off the branch on which you are sitting. See page 204 for details about this issue.
Using the find_if() algorithm to search for an element that has a certain value is even more complicated than writing a loop because you have to provide a function object that compares the value of an element with a certain value. See page 211 for an example.
The lower_bound(), upper_bound(), and equal_range() functions behave as they do for sets (see page 180), except that the elements are key/value pairs. typedef std::map< std::string, int > mydef;
struct _select_second
{
int value;
_select_second( int v ) : value(v) {}
bool operator ()( mydef::value_type ele )
{
return ele.second == value;
}
};
mydef vMap;
vMap["hello"] = 20;
mydef::iterator iter = std::find_if( vMap.begin(), vMap.end(), _select_second(20) ); 你说的find是algorithsm里面的find,不是map内部的find吧。
页:
[1]