|
发表于 2009-8-13 18:34:12
|
显示全部楼层
看参考资料,应该用类提供的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 Operation Effect
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. |
|