打印矢量元素错误消息

时间:2016-06-22 23:49:26

标签: c++ vector

我是c ++的初学者。以下简单的程序将元素推送到向量中并在遍历时显示它们,但是无法正常工作。编译器说"表达式:矢量迭代器不可以生成。" 任何人都可以帮我解决这个问题吗?

    #include <iostream>
    #include<vector>
    int main()
    {
    int n;
    std::vector<int>x;
    std::vector<int>::iterator it;
    for (it = x.begin(); it != x.end(); ++it)
    {
        std::cout << "enter an element in the vector:" << "\n";
        std::cin >> n;
        x.push_back(n);
        std::cout << "vector:" << "\n";
        std::cout << *it;
    }

    return 0;
    }

1 个答案:

答案 0 :(得分:0)

选择两个迭代器,即it1和it2变量。 it1用于将输入存储到向量中。矢量的初始输入存储在此处。

std::vector<int>::iterator it1;
it1=x.begin();
std::cout << "enter an element in the vector: " << "\n";
std::cin >> n;
x.push_back(n);

要退出循环,请输入&#39; -1&#39;

while(n!=-1)
{
++it1;
std::cout << "enter an element in the vector: " << "\n";
std::cin >> n;
x.push_back(n);
} ;

it2用于显示向量的输出。

for(it2 = x.begin(); it2 != x.end(); ++it2)
  std::cout<<*it2<<" ";//no need of curly braces for single for statement

&#39; 完整的工作计划:

#include <iostream>
#include<vector>

int main()
{
  int n;
  std::vector<int> x;
  std::vector<int>::iterator it1;
  std::vector<int>::iterator it2;
  it1=x.begin();
  std::cout << "enter an element in the vector: " << "\n";
  std::cin >> n;
  x.push_back(n);

  while(n!=-1)
  {
    ++it1;
    std::cout << "enter an element in the vector: " << "\n";
    std::cin >> n;
    x.push_back(n);
  };

  std::cout<<"Vector : ";
  for(it2 = x.begin(); it2 != x.end(); ++it2)
    std::cout<<*it2<<" " ;

  return 0;
}