c++ - std::map 通过变换替换现有元素

标签 c++ c++11

我有一个代码:

std::vector<int> vector = {1, 3, 5, 7, 9};
using my_type = std::pair<int, int>;
std::map<int, boost::optional<my_type>> map;
for (const auto &i : vector) {
    map[i] = boost::none;
}
const my_type val = {1, 5};
std::transform(vector.cbegin(),
               vector.cend(),
               std::inserter(map, map.end()),
               [&val](const int &i) {
                   return std::make_pair(i, boost::optional<my_type>(val));
});

一切正常,但 std::transform 不会通过用现有键替换值来更改映射,所以我有这个:

{ 
    {1, boost::none},
    {3, boost::none},
    {5, boost::none},
    {7, boost::none},
    {9, boost::none},
}

是否可以按照简单的基于范围的方式使其工作?

for (const auto &i : vector) {
    map[i] = boost::optional<my_type>(val));
}

附言我知道 std::inserterstd::map::insert 是如何工作的,只是好奇如何更改转换以更改值。

最佳答案

不适用于 inserter,因为 insert 仅在 map 中没有元素时才插入元素。 会有insert_or_assign在 C++17 中。

template<typename Map>
struct map_insert_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
   map_insert_iterator(Map& m) : map(m)
   {
   }
   map_insert_iterator<Map>& operator = (const typename Map::value_type& value)
   {
      map.insert_or_assign(value.first, value.second);
      return *this;
   }
   map_insert_iterator<Map>& operator * () { return *this; }
   map_insert_iterator<Map>& operator ++ () { return *this; }
   map_insert_iterator<Map>& operator ++ (int) { return *this; }
private:
   Map& map;
};

template<typename Map>
map_insert_iterator<Map> map_inserter(Map& m)
{
   return map_insert_iterator<Map>(m);
}

Live

关于c++ - std::map 通过变换替换现有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34784455/

相关文章:

c++ - 让 OpenAL 在 C++ 中工作

c++ - 在 Windows/Visual Studio 上用 C++ 在运行时编译函数的简单有效的方法是什么?

c++ - 获取错误 : 'mutex' in namespace 'std' does not name a type in MinGW mysys prompt

具有右值引用的 C++ 模板化方法消歧规则

c++ - 一行类定义?

c++ - 如何知道 std::thread 在 C++ 中何时完成?

c++ - cpp 主体线程的局部函数是否安全?如果是这样,从中调用静态函数呢?

C++11 使用带有自定义比较函数的 std::equal_range

c++ - 避免模​​棱两可的部分特化

c++ - std::bind2nd 的替代品