设置 std::map 中的所有值

发布于 2024-07-06 09:13:53 字数 45 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫﹏色ふ单纯 2024-07-13 09:13:53

使用循环是迄今为止最简单的方法。 事实上,这是一句简单的话:[C++17]

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

不幸的是,C++ 算法对关联容器的支持在 C++20 之前并不是很好。 因此,我们不能直接使用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);

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

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

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

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()); }

With this, we can use std::fill:

std::fill(value_begin(mymap), value_end(mymap), value);
哆兒滾 2024-07-13 09:13:53

我遇到了同样的问题,但发现 boost::adaptors::values 返回的范围是可变的,因此它可以与 std::fill 等普通算法一起使用。

#include <boost/range/adaptor/map.hpp>
auto my_values = boost::adaptors::values(my_map);
std::fill(my_values.begin(), my_values.end(), 123);

I encountered the same problem but found that the range returned by boost::adaptors::values is mutable, so it can then be used with normal algorithms such as std::fill.

#include <boost/range/adaptor/map.hpp>
auto my_values = boost::adaptors::values(my_map);
std::fill(my_values.begin(), my_values.end(), 123);
余生一个溪 2024-07-13 09:13:53

boost::assign 库有各种巧妙的东西来帮助初始化容器的内容。 我认为这可以用来避免显式地迭代地图。 不幸的是,地图是难以初始化的奇怪野兽,因为键必须是唯一的。 最重要的是,简单的 for 循环可能是初始化映射的最佳方法。 它可能不是超级优雅,但它可以完成工作,并且任何熟悉 STL 的人都可以立即理解。

map <int,string> myMap;
for( int k=0;k<1000;k++)
  myMap.insert(pair<int,string>(k,string("")));

这篇文章的其余部分描述了我得出上述结论的过程。

boost::assign 使向映射分配少量值变得简单。

map<string,int> m; 
insert( m )( "Bar", 1 )( "Foo", 2 );

或者

 map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);

在您的情况下,您想用相同的值初始化整个地图,有实用程序重复和重复_fun。
像这样的东西应该适用于多重映射(未经测试的代码片段)

pair<int,string> init( 0,string(""));
multimap <int,string> myMap = repeat(1000,init);

正如 Konrad Rudolph 所指出的,您不能使用相同的精确值初始化映射,因为键必须是唯一的。

这让生活变得更加复杂(有趣?)。 也许是这样的:

map <int,string> myMap;

struct nextkey
{
   int start;
   nextkey( s ) : start( s ) {}
   pair<int,string> operator () ()
{
   return pair<int,string>(start++,string(""));
}
};

myMap = repeat_fun(1000,nextkey(0));

现在,这变得如此复杂,我现在认为简单的迭代是正确的方法

map <int,string> myMap;
for( int k=0;k<1000;k++)
  myMap.insert(pair<int,string>(k,string("")));

The boost::assign library has all sorts of neat stuff to help out initializing the contents of a container. My thought that this could be used to avoid explicitly iterating through the map. Unfortunately, maps are curious beasts difficult to initialize because the keys must be unique. The bottom line is that a simple for loop is probably the best way to initialize a map. It may not be super elegant, but it gets the job done and is immediatly comprehensible by anyone with any acquaintance with the STL.

map <int,string> myMap;
for( int k=0;k<1000;k++)
  myMap.insert(pair<int,string>(k,string("")));

The rest of this post describes the journey I took to reach the above conclusion.

The boost::assign makes it simple to assign a small number of values to a map.

map<string,int> m; 
insert( m )( "Bar", 1 )( "Foo", 2 );

or

 map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);

In your case, where you want to initialize the entire map with the same value, there are the utilities repeat and repeat_fun.
Something like this should work with a multimap ( untested code snippet )

pair<int,string> init( 0,string(""));
multimap <int,string> myMap = repeat(1000,init);

As Konrad Rudolph as pointed out, you cannot initialize a map with the same exact value, because the keys must be unique.

This makes life much more complex ( fun? ). Something like this, perhaps:

map <int,string> myMap;

struct nextkey
{
   int start;
   nextkey( s ) : start( s ) {}
   pair<int,string> operator () ()
{
   return pair<int,string>(start++,string(""));
}
};

myMap = repeat_fun(1000,nextkey(0));

Now, this is getting so complex, I now think a simple iteration IS the way to go

map <int,string> myMap;
for( int k=0;k<1000;k++)
  myMap.insert(pair<int,string>(k,string("")));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文