c++ - 在 std::map 中设置所有值

标签 c++ stl

如何将 std::map 中的所有值设置为相同的值,而不使用循环遍历每个值?

最佳答案

使用循环迄今为止最简单的方法。事实上,它是一行代码:[C++17]

for (auto& [_, v] : mymap) v = value;

不幸的是,C++20 之前的 C++ 算法对关联容器的支持不是很好。因此,我们不能直接使用 std::fill

无论如何要使用它们(C++20 之前),我们需要编写适配器——在 std::fill 的情况下,一个迭代器适配器。这是一个最低限度可行的(但不是真正符合要求的)实现来说明这是多少工作量。我建议按原样使用它。使用库(例如 Boost.Iterator )进行更通用的生产强度实现。

template <typename M>
struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> {
    using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>;
    using underlying = typename M::iterator;
    using typename base_type::value_type;
    using typename base_type::reference;

    value_iter(underlying i) : i(i) {}

    value_iter& operator++() {
        ++i;
        return *this;
    }

    value_iter operator++(int) {
        auto copy = *this;
        i++;
        return copy;
    }

    reference operator*() { return i->second; }

    bool operator ==(value_iter other) const { return i == other.i; }
    bool operator !=(value_iter other) const { return i != other.i; }

private:
    underlying i;
};

template <typename M>
auto value_begin(M& map) { return value_iter<M>(map.begin()); }

template <typename M>
auto value_end(M& map) { return value_iter<M>(map.end()); }

有了这个,我们可以使用std::fill:

std::fill(value_begin(mymap), value_end(mymap), value);

关于c++ - 在 std::map 中设置所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/139325/

相关文章:

c++ - VC++编译器升级2010->2015重新定义; 'constexpr' 说明符不匹配

c++ - 可能 STL 迭代器方法抛出异常

c++ - VS 2010 和 VS 2010 SP1 C++ 二进制文件之间的二进制兼容性

c++ - 通过 glUniform 将 GLM 的 vector 类型传递给 OpenGL

c++ - 在模板特化的情况下,是否允许编译器忽略内联?

java - 如果调用 JNI DeleteGlobalRef(),相应的 java 对象是否会被垃圾回收?

algorithm - 为工作选择合适的 STL 容器的标准?

c++ - vector 和使用STL

c++ - std::next_permutation() 来自 vector 的一部分

c++ - 非限定查找和(可能)依赖的基类