How to retrieve all keys (or values) from a std::map and put them into a vector?(如何从 std::map 检索所有键(或值)并将它们放入向量中?)
问题描述
这是我出来的可能方式之一:
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, "
"));
当然,我们也可以通过定义另一个函子RetrieveValues来从地图中检索所有值.
Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.
有没有其他方法可以轻松实现这一目标?(我一直想知道为什么 std::map 不包含一个成员函数让我们这样做.)
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.)
推荐答案
虽然您的解决方案应该有效,但可能难以阅读,这取决于您的程序员同事的技能水平.此外,它将功能从呼叫站点移开.这会使维护变得更加困难.
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.
我不确定您的目标是将密钥放入向量中还是将它们打印出来进行 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.
这篇关于如何从 std::map 检索所有键(或值)并将它们放入向量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 std::map 检索所有键(或值)并将它们放入向
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
