0

I'm trying to use std::valarray setting some initial values. Printing the array values, I get something different from what I expect. I'm on Windows (10) with CodeBlocks (GCC 4.9.2, C++11 build option).

Here is the code:

#include <iostream>
#include <string>
#include <valarray>

void print(std::string aname, std::valarray<int> & va)
{
    std::cout << aname << "[ ";
    for(auto &i : va)
    {
        std::cout << va[i] << ' ';
    }
    cout << ']'<< endl;
}

int main()
{

    std::valarray<int> one { 1, 0, 0 };
    std::valarray<int> two  { 0, 1, 0 };
    std::valarray<int> three { 0, 0, 1 };
    std::cout << std::endl;
    print("one", one);
    print("two", two);
    print("three", three);

    return 0;
}

The output is:

one[ 0 1 1 ]
two[ 0 1 0 ]
three[ 0 0 0 ]
4

1 回答 1

2

当您使用这种 for 循环时:

for(auto &i : va)

i接收 va 的内容,因此,正确的显示方式是:

std::cout << i << ' ';   // not va[i]
于 2017-09-20T13:05:27.517 回答