eud*_*xos 6 c++ for-loop pass-by-reference c++11
我想在几个数组上执行相同的操作,如:
#include<vector>
#include<algorithm>
int main(void){
std::vector<double> a, b;
for(auto& ab:{a,b}) std::sort(ab.begin(),ab.end()); // error
}
Run Code Online (Sandbox Code Playgroud)
此代码失败,因为它auto&是一个const引用.周围有优雅的方式吗?
我认为问题在于它有点像将临时绑定绑定到非const引用.那里没有"具体"的集合,所以有点像临时的.
如果你有一个临时向量,它将绑定到const引用,但不是非const引用.
我也认为这不会对你正在做的事情起作用,但这应该有效:
#include<vector>
#include<algorithm>
int main(void)
{
std::vector<double> a, b;
for(std::vector<double>* ab:{&a,&b})
std::sort(ab->begin(),ab->end()); // or begin(*ab),end(*ab)
}
Run Code Online (Sandbox Code Playgroud)
和汽车也可以工作.