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