【问题标题】:Accessing second elements of the map with for_each or transform使用 for_each 或 transform 访问地图的第二个元素
【发布时间】:2012-12-05 21:50:20
【问题描述】:

我想问你如何从

复制所有第二个元素
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)); 

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

【问题讨论】:

    标签: c++ map foreach copy deque


    【解决方案1】:

    您收到错误的原因是因为map&lt;string, string&gt;::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"));
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 1970-01-01
      • 2021-05-17
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      相关资源
      最近更新 更多