为什么这个矢量不打印?

时间:2013-01-30 23:04:28

标签: c++ vector c++11 iterator auto

编译错误说it未在此范围内声明,它没有命名类型,预期;

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> vec;

    vec.push_back(1);
    vec.push_back(3);
    vec.push_back(5);

    for (auto it = vec.begin(); it != vec.end(); ++it) {
         cout << *it << endl;
    }

    cout << "size: " << vec.size() << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:2)

如评论所述,您需要在编译时指定-std=c++11标志。

只需提及迭代的替代语法range-for statement

for (auto& i: vec)
{
    std::cout << i << std::endl;
}

并使用uniform initialization填充vector初始值:

std::vector<int> vec {1, 3, 5};

另见Why is "using namespace std" considered bad practice?