创建 STL 恒等映射的最简单方法是什么?

发布于 2024-07-13 19:03:10 字数 168 浏览 4 评论 0原文

我想初始化一个地图 - 对象“id”,其身份从 0 到 n-1,即

 id[0] = 0
 id[1] = 1
 .
 .
 id[n-1] = n-1

是否有一种简单的方法 - 一个单行,地图对象内的一种方法,只是非常简单的东西 - 就可以做到这一点?

I'd like to initialize a map - object "id" with identities from 0 to n-1, i.e.

 id[0] = 0
 id[1] = 1
 .
 .
 id[n-1] = n-1

Is there a simple way - a one-liner, a method inside the map-object, simply something really simple - that does that?

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

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

发布评论

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

评论(4

别再吹冷风 2024-07-20 19:03:10

出什么问题了

for(unsigned int i = 0; i < n; ++i)
    id[i] = i;

What is wrong with

for(unsigned int i = 0; i < n; ++i)
    id[i] = i;
往日 2024-07-20 19:03:10

您可以使用

template <class InputIterator>
map(InputIterator f, InputIterator l,
    const key_compare& comp)

构造函数的形式,但您需要构建一个InputIterator,它在您想要的范围内充当生成器函数。 这比仅仅使用 for 循环要输入更多的内容。

You could use the

template <class InputIterator>
map(InputIterator f, InputIterator l,
    const key_compare& comp)

form of the constructor, but you'd need to build an InputIterator that worked as a generator function over the range you want. That'd be a whole lot more typing than just using a for loop.

凉薄对峙 2024-07-20 19:03:10

使用键为简单索引的映射似乎有点奇怪。 你确定不能使用向量吗? 这样做,您可以使用 boost:: counting_iterator 来填充向量:

std::vector<int> v(boost::counting_iterator<int>(0), 
                   boost::counting_iterator<int>(N-1));
// v is filled with integers from 0 to N-1

但是,我不确定这与简单的 for 循环相比是否是一个巨大的收益。

It seems a little weird to use a map with the key being a simple index. Are you sure you cannot use a vector? Doing so, you could use boost::counting_iterator to fill the vector:

std::vector<int> v(boost::counting_iterator<int>(0), 
                   boost::counting_iterator<int>(N-1));
// v is filled with integers from 0 to N-1

However, I'm not sure whether this is a huge gain compared to the simple for loop.

迷途知返 2024-07-20 19:03:10

留意 std::iota 作为数字库的一部分(C++0x 功能):

template <ForwardIterator Iter, HasPreincrement T>
requires OutputIterator<Iter, const T&>
void iota(Iter first, Iter last, T value);

Look out for std::iota as part of the numeric library (C++0x feature):

template <ForwardIterator Iter, HasPreincrement T>
requires OutputIterator<Iter, const T&>
void iota(Iter first, Iter last, T value);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文