打印向量元素错误消息

printing vector elements error message

本文关键字:消息 错误 元素 向量 打印      更新时间:2023-10-16

我是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;
    }

选择了两个迭代器,即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);

要退出循环,请输入'-1'

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

'完成工作计划:

#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;
}