c++ - 使用 for_each 或 transform 访问 map 的第二个元素

标签 c++ dictionary foreach copy deque

我想问你如何从

中复制所有第二个元素
map<string, string> myMap

deque<string> myDeq

在不创建仿函数的情况下使用 for_each 或 transform。我在 this question 中尝试过

transform(myMap.begin(), myMap.end(), back_inserter(myDeq), mem_fun_ref(&map<string, string>::value_type::second)); 

但它对我不起作用 - 我收到错误“非法使用此类型”。

最佳答案

你得到错误的原因是因为 map<string, string>::value_type::second不是成员函数。它只是 std::pair 模板结构的一个成员变量。

一种不使用仿函数的可能解决方案是使用 lambda。但这是 C++11 的特性,所以我不知道这是否是您想要的。

看看下面的例子

#include <iostream>
#include <map>
#include <deque>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    map<string,string> myMap;
    deque<string> myDeque;

    myMap["key1"]="value1";
    myMap["key2"]="value2";
    transform(myMap.begin(),myMap.end(),back_inserter(myDeque),[](map<string,string>::value_type p){return p.second;});

    copy(myDeque.begin(),myDeque.end(),ostream_iterator<string>(cout,"\n"));
}

关于c++ - 使用 for_each 或 transform 访问 map 的第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937218/

相关文章:

c++ - QT 队列触发连接

ios - 在 SWIFT 倒计时中使用的访问字典

c++ - 向 typedef 添加函数

php - 如何实时回显输出(在脚本完成之前)?

grails - 只有一个元素时遍历数组

c++ - 如何释放在 "get"函数中分配的动态内存?

C++:排序/字母排序方法

C++ std::unique_ptr 从函数返回并测试 null

c++ - C++ STL map 如何管理内存,以及如何绕过它

php - 如何使用主键从表中选择多个数据?