如何将 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/