在std :: map中设置所有值 [英] Setting all values in a std::map

查看:111
本文介绍了在std :: map中设置所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to set all the values in a std::map to the same value, without using a loop iterating over each value?

推荐答案

使用循环迄今为止最简单的方法.实际上,它是单线的: [C ++ 17]

Using a loop is by far the simplest method. In fact, it’s a one-liner:[C++17]

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

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

Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use std::fill.

要始终使用它们(C ++ 20之前的版本),我们需要编写适配器-在迭代器适配器 std :: fill 的情况下.这是一个最小可行的(但不是真正合规的)实施方式,以说明这需要付出多大的努力.我建议按原样使用它.使用一个库(例如 Boost.Iterator )以实现更通用的生产强度实施.

To use them anyway (pre-C++20), we need to write adapters — in the case of std::fill, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do not advise using it as-is. Use a library (such as Boost.Iterator) for a more general, production-strength implementation.

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 :

With this, we can use std::fill:

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

这篇关于在std :: map中设置所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆