【发布时间】:2016-05-06 03:44:16
【问题描述】:
我想迭代一个临时的 valarray,但它不起作用。这是我的(非工作)代码:
#include <iostream>
#include <valarray>
int main()
{
using namespace std;
valarray<int> numerators = {99, 26, 25};
valarray<int> denominators = {9, 2, 5};
for (int i : numerators / denominators) { cout << i << ","; }
// lots of errors
return 0;
}
下面是我想要实现的最小工作示例,除了我不想定义像 temp_array 这样的对象。
#include <iostream>
#include <valarray>
int main()
{
using namespace std;
valarray<int> numerators = {99, 26, 25};
valarray<int> denominators = {9, 2, 5};
valarray<int> && temp_array = numerators / denominators;
for (int i : temp_array) { cout << i << ","; }
// prints 11,13,5,
return 0;
}
我的编译器是 g++ 版本 4.8.5 (Red Hat 4.8.5-4)。 我正在使用 -std=c++0x 标志进行编译。
我尝试了其他语法,例如for (auto&& i : temp_array) 和for (int const & i : temp_array),但它不起作用。
【问题讨论】:
-
valarray的operator/被允许返回一个代理对象作为表达式模板。 -
显然,我已经离开 C++ 太久了。有人可以解释
for(int i : temp_array){}是如何有效的 for 循环语句吗?不应该是for(init;end_condition;increment)之类的吗? -
@user1717828 查看 C++11 的基于范围的 for 循环。
标签: c++ for-loop rvalue temporary-objects valarray