gpt4 book ai didi

c++ - 在 ref/cref 范围内同时迭代

转载 作者:行者123 更新时间:2023-11-30 00:46:58 24 4
gpt4 key购买 nike

我有一个接受两个整数 vector 的函数。第一个 vector 作为引用传递,第二个 vector 作为对常量的引用传递。我想同时遍历两个 vector ,并更新第一个 vector 。所以像下面这样:

#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/range/combine.hpp>

void foo(std::vector<int>& a, std::vector<int> const& b)
{
boost::tuple<int&, int const&> x;
BOOST_FOREACH(x, boost::combine(a,b)) {
int& v1 = x.get<0>();
int const& v2 = x.get<1>();
v1 = v1 + v2 + 5;
}

}

int main(int argc, char **argv)
{
std::vector<int> a(3,10);
std::vector<int> b(3,10);

foo(a,b);
for (int v : a) {
std::cout << v << std::endl;
}
return 0;
}

我遇到的问题是迭代两个范围,一个是 ref,另一个是 ref const。如何正确使用 boost:combine/for 循环?谢谢。

最佳答案

至少如果我正确阅读了 Boost 内容,您似乎想要类似于以下内容的内容:

std::transform(a.begin(), a.end(), 
b.begin(),
a.begin(),
[] (int x, int y) { return x + y + 5; });

就目前而言,它使用 C++11。如果你在没有 C++11 的情况下需要它,你无疑可以使用 Boost Lambda 来完成同样的事情,或者你可以自己编写一个函数对象:

struct combine { 
int operator()(int x, int y) { return x + y + 5; }
};

void foo(std::vector<int>& a, std::vector<int> const & b)
{
std::transform(a.begin(), a.end(),
b.begin(),
a.begin(),
combine());
}

另请注意 std::vector<int>& const b是不正确的。你几乎肯定想要:std::vector<int> const &b反而。随着const & 之后,它表示引用本身是 const .把它移到前面意味着引用所指的是const。 .前者没有意义(您不能将 const 应用于引用;就 const 引用的概念完全有意义而言,每个引用始终是 const)。

关于c++ - 在 ref/cref 范围内同时迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36487054/

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