c++ - boost::range 如何使用管道输入在 map 中插入元素

标签 c++ boost stl

我想使用 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/

相关文章:

C++ 正则表达式库

c++ - bazel alwayslink = true 是什么意思?

c++ - 将交换与对象自杀一起使用

std::map::at() 的 C++98 包装器

android - Android下如何指定STL库?

c++ - 模板化的 Pointer 类可以有一个虚拟析构函数吗?

c++ - 递归算法对数组中每个值小于 x 的元素求和

c++ - emscripten 和 boost 库 : how to compile existing project for webassembly?

c++ - 链接错误 : Boost Library on Windows using MinGW

c++ - std::mem_fn(&method_defined_with_forceinline)(*this) 未内联