gpt4 book ai didi

c++ 11用于多个项目的容器循环

转载 作者:太空狗 更新时间:2023-10-29 20:11:52 25 4
gpt4 key购买 nike

我想知道是否可以在 c++11 语法中对多个项目使用基于 for 循环的新容器,例如:

std::vector<double> x;
std::vector<double> y;

for (double& xp, yp : x, y)
{
std::cout << xp << yp << std::endl;
}

我找不到任何有关将此循环用于多个容器的信息。我将不胜感激。

经典 for 循环中的示例效果:

std::vector<double>::iterator itX = m_x.begin();
std::vector<double>::iterator itY = m_y.begin();

for (uint32_t i = 0; i < m_x.size(); i++, itX++, itY++)
{
// operations on the m_x and m_y vectors
}

最佳答案

语言工作组中有一个请求,要求支持一种非常相似的语法,以在多个容器上同时迭代:

Section: 6.5.4 [stmt.ranged] Status: Open Submitter: Gabriel Dos Reis

Opened: 2013-01-12 Last modified: 2015-05-22

Discussion:

The new-style 'for' syntax allows us to dispense with administrative iterator declarations when iterating over a single sequence. The burden and noise remain, however, when iterating over two or more sequences simultaneously. We should extend the syntax to allow that. E.g. one should be able to write:

for (auto& x : v; auto& y : w)
a = combine(v, w, a);

instead of the noisier

auto p1 = v.begin();
auto q1 = v.end();
auto p2 = w.begin();
auto q2 = w.end();
while (p1 < q1 and p2 < q2) {
a = combine(*p1, *p2, a);
++p1;
++p2;
}

参见 http://cplusplus.github.io/EWG/ewg-active.html#43

所以它可能会发生,但不会在不久的将来发生。

同时,最好的选择可能是经典的 for 循环。

关于c++ 11用于多个项目的容器循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com