可能重複:
Checking value exist in a std::map - C++
How to traverse a stl map/vector/list/etc?搜索特定值的std ::地圖
你好,
是否有可能要搜索的性病特定值: :地圖,不知道密鑰?我知道我可以迭代整個地圖,並比較值,但是可以使用std算法中的函數嗎?
可能重複:
Checking value exist in a std::map - C++
How to traverse a stl map/vector/list/etc?搜索特定值的std ::地圖
你好,
是否有可能要搜索的性病特定值: :地圖,不知道密鑰?我知道我可以迭代整個地圖,並比較值,但是可以使用std算法中的函數嗎?
這會有幫助嗎? STL find_if
您需要具有某種謂詞,或者是函數指針或者實現了operator()
的對象。所述謂詞應該只有一個參數。
如果您想對值和索引建立索引,則可以使用Boost.Bimap。沒有這個或類似的,這將不得不通過蠻力(=>手動掃描map
)。
Boost.Bimap是一個C++的雙向映射圖庫 。通過Boost.Bimap,您可以在 中創建關聯容器,這兩種類型都可以用作關鍵字。
+ 1。另外,如果不允許在代碼中使用Boost,則可以使用兩個相反的STL映射。 – Stas 2010-12-06 15:47:50
使用標準函數(例如,std::find_if
)有一些(尷尬的)方法來做到這一點,但是這些方法仍然涉及迭代整個地圖。 Boost.Bimap將在兩個方向上提供高效的索引,並且您可以使用Boost.Multi-Index更進一步。
嗯,你可以使用std::find_if
:
int main()
{
typedef std::map<int, std::string> my_map;
my_map m;
m.insert(std::make_pair(0, "zero"));
m.insert(std::make_pair(1, "one"));
m.insert(std::make_pair(2, "two"));
const std::string s("one");
const my_map::const_iterator it = std::find_if(
m.begin(), m.end(), boost::bind(&my_map::value_type::second, _1) == s
);
}
但是,這僅僅比手工製作的循環稍微好一點:它仍然O(n)
。
對於`std :: map`,你必須迭代。否則,使用`boost :: bimap` - http://stackoverflow.com/questions/535317/checking-value-exist-in-a-stdmap-c – birryree 2010-12-06 15:25:52
這個鏈接告訴你如何遍歷地圖^^^ – 2010-12-06 16:03:57