問題描述
這是我出來的可能方式之一:
This is one of the possible ways I come out:
struct RetrieveKey
{
template <typename T>
typename T::first_type operator()(T keyValuePair) const
{
return keyValuePair.first;
}
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());
// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "
"));
當(dāng)然,我們也可以通過定義另一個函子RetrieveValues來從地圖中檢索所有值.
Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.
有沒有其他方法可以輕松實現(xiàn)這一目標(biāo)?(我一直想知道為什么 std::map 不包含一個成員函數(shù)讓我們這樣做.)
Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.)
推薦答案
雖然您的解決方案應(yīng)該有效,但可能難以閱讀,這取決于您的程序員同事的技能水平.此外,它將功能從呼叫站點移開.這會使維護(hù)變得更加困難.
While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.
我不確定您的目標(biāo)是將密鑰放入向量中還是將它們打印出來進(jìn)行 cout,所以我兩者都在做.你可以試試這樣的:
I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:
std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
key.push_back(it->first);
value.push_back(it->second);
std::cout << "Key: " << it->first << std::endl();
std::cout << "Value: " << it->second << std::endl();
}
或者更簡單,如果您使用的是 Boost:
Or even simpler, if you are using Boost:
map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
v.push_back(me.first);
cout << me.first << "
";
}
就我個人而言,我喜歡 BOOST_FOREACH 版本,因為輸入較少,而且它的作用非常明確.
Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.
這篇關(guān)于如何從 std::map 檢索所有鍵(或值)并將它們放入向量中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!