【问题标题】:Why doesn't this vector print? [closed]为什么这个矢量不打印? [关闭]
【发布时间】:2013-01-30 23:04:28
【问题描述】:

编译错误说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;
}

【问题讨论】:

  • 工作正常:ideone.com/qVFl6p。你指定了 -std=c++11 吗?
  • 是的,谢谢,我之前设置了它,但不能保存,但现在可以了!
  • 您想修正缩进吗?
  • 我是这样缩进的,因为我在发布代码时遇到了问题。

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


【解决方案1】:

如注释,编译时需要指定-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?

【讨论】:

  • 为什么是 auto& 而不仅仅是 auto?我是 C++ 新手。
  • @SalRosa 引用容器的元素。它真的应该是const auto&amp;,因为你没有修改循环内的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多