Nav*_*K N 31 c++ iterator stdmap find
我知道find方法在std :: map中找到提供的键,并将迭代器返回给元素.反正有没有找到值并获得元素的迭代器?我需要做的是检查std :: map中是否存在指定的值.我通过循环地图中的所有项目并进行比较来完成此操作.但我想知道有没有更好的办法.
这是我写的
bool ContainsValue(Type_ value)
{
bool found = false;
Map_::iterator it = internalMap.begin(); // internalMap is std::map
while(it != internalMap.end())
{
found = (it->second == value);
if(found)
break;
++it;
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
编辑
如何在内部使用另一个存储值,键组合的地图.所以我可以打电话找到它吗?std :: map中的find()是否进行顺序搜索?
谢谢
Cod*_*ddy 16
如果您可以访问优秀的boost库,那么您应该使用boost :: multi_index来创建双向映射,正如Mark所说.与std :: map不同,它允许您通过键或值查找.
如果您只有STL,那么下面的代码就可以解决问题(模板化可以使用mapped_type支持operator ==的任何类型的map):
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
#include <cassert>
template<class T>
struct map_data_compare : public std::binary_function<typename T::value_type,
typename T::mapped_type,
bool>
{
public:
bool operator() (typename T::value_type &pair,
typename T::mapped_type i) const
{
return pair.second == i;
}
};
int main()
{
typedef std::map<std::string, int> mapType;
mapType map;
map["a"] = 1;
map["b"] = 2;
map["c"] = 3;
map["d"] = 4;
map["e"] = 5;
const int value = 3;
std::map<std::string, int>::iterator it = std::find_if( map.begin(), map.end(), std::bind2nd(map_data_compare<mapType>(), value) );
if ( it != map.end() )
{
assert( value == it->second);
std::cout << "Found index:" << it->first << " for value:" << it->second << std::endl;
}
else
{
std::cout << "Did not find index for value:" << value << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*isW 15
如何在内部使用另一个存储值,键组合的地图.所以我可以打电话找到它吗?
是:维护两个地图,一个地图使用一种类型的密钥,另一个地图使用另一种.
std :: map中的find()是否进行顺序搜索?
不,它是对已排序树的二进制搜索:其速度为O(log(n)).
查看boost的双向映射:http://www.boost.org/doc/libs/1_38_0/libs/bimap/doc/html/index.html
它让两个值都像一把钥匙.
否则,迭代是要走的路.
您所要求的正是std::find所做的(而不是成员函数)
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
69774 次 |
最近记录: |