c++ - 如何将函数应用于映射的每个值以创建排序序列?

标签 c++ stdstring stdmap stl-algorithm

在 C++ 中使用 STL,我如何将函数应用于 std::map 中的每个值来获取 std::string (打印表示值)并将 std::string 收集到一个按浮点键排序的集合中,该浮点键来自应用于映射中每个相应值的另一个函数?

换句话说,我想迭代映射中的键值对并创建一组新的键值对,其中新键和值是旧值的函数。

double getNewKey(origValue value);
std::string getNewValue(origValue value);
// Or is it better to map both at once in a pair?
std::pair<double, std::string> getNewPair(origValue value);

std::map<origKey, origValue> origMap;

// Perform some transformation on each value of origMap to get a new map:
std::map<double, std::string> transformedMap =
  /* What goes here to use getNewKey() and getNewValue() or use getNewPair()? */
  ;

但是,请不要使用 C++11。

最佳答案

std::transform 是您所需要的:

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

// using a few C++11 features to make life easier
int main(){
  std::map<int, int> src, dst; // example KV pair
  for(unsigned i=0; i < 10; ++i)
    src[i] = i;
  typedef std::map<int, int>::value_type kv_pair;
  std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()),
      [](kv_pair const& p){
        return kv_pair(p.first, p.second * 2);
      });
  for(auto& p : dst)
    std::cout << p.first << " : " << p.second << "\n";
}

Live example.

关于c++ - 如何将函数应用于映射的每个值以创建排序序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801568/

相关文章:

运行我的随机 ID 生成时出现 C++ 段错误

c++ - 在 C++ 范围内快速设置 map 中的值

C++ std::function 运算符=

c++ - 如何从集合中初始化 map

c++ - 消除标点符号和空格

c++ - 大数组大小的段错误

c++ - std::endl 和 '\n' 有什么区别

c++ - C++ 中的线程安全单例实现

c++ - 用于排序的比较器

c++ - 搜索不同于 "X"的第一个字符的字符串