我想使用 boost:range 实用程序来转换 vector ,并将原始元素作为键,将转换后的元素作为值放在 std::map 中。我想出了类似下面的东西。很明显,我错过了我们可以在最后一步实际插入元素的方式。你能帮帮我吗?
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm/copy.hpp>
const std::vector<int> vec = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
void doSomething(int i)
{
// Do Something
}
/** Map integers to the alphabet: 0->a, 1->b, ... */
std::string alphabetize(int i)
{
return std::string(1, 'a' + i);
}
int main()
{
std::map<std::string, int > myMap;
boost::copy(vec | boost::adaptors::transformed(alphabetize), std::inserter(myMap, myMap.end()));
}
为了进一步扩展它,我如何使用 for_each 为所有元素调用一个函数,就像这样
boost::range::for_each(myMap | boost::adaptors::map_value, doSomething);
最佳答案
只是 make 函数,它返回对,而不是字符串。
std::pair<std::string, int> alphabetize(int i)
{
return std::make_pair(std::string(1, 'a' + i), i);
}
关于c++ - boost::range 如何使用管道输入在 map 中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251864/