g ++错误:'vec'没有命名类型

时间:2014-04-14 18:19:00

标签: c++ vector stl

我正在尝试使用C ++ STL向量。这是我的计划:

# include <iostream> 
# include <vector>

using namespace std; 

vector<int> vec; 

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

vector<int>::iterator itr1 = vec.begin();
vector<int>::iterator itr2 = vec.end();

for(vector<int>::iterator itr = itr1; itr != itr2; itr++){
    cout << *itr  << endl;  
}

我在error: ‘vec’ does not name a type行上收到错误vec.push_back();。我无法看到我在这里做错了什么。

1 个答案:

答案 0 :(得分:7)

仅允许在函数内部使用vec.push_back(42);等语句。例如,

#include <iostream> 
#include <vector>

int main()
{
  using namespace std; 

  vector<int> vec; 

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

  vector<int>::iterator itr1 = vec.begin();
  vector<int>::iterator itr2 = vec.end();

  for(vector<int>::iterator itr = itr1; itr != itr2; itr++){
    cout << *itr  << endl;  
  }

}