c++ - vector <int> 输入和输出

标签 c++ stl vector cin

我被简单的 vector 输入和输出操作困住了。编译器返回错误提示“std::outof range”

这是代码

int main()
{
int size;
cout <<"Enter size of vector\n";
cin>>size;
cout<<"Now to input the vector of size "<<size<<endl;
vector <int> trial;
for (size_t i=0;i<size;++i){
    int x;
    cout<<"write at position"<<trial.at(i)<<'t';
    cin>>x;
    trial.push_back(x);
    cout<<endl;
}
ostream_iterator<int> output(cout,"");
copy(trial.begin(),trial.end(),output);
}

如果能简要解释问题的内部工作原理,我将不胜感激。

最佳答案

您在 trial.push_back(x) 之前调用 trial.at(i),访问一个尚不存在的元素。由于该元素(还)不存在,i 是无效索引,at() 将抛出 std::out_of_range 异常传递无效索引时。如果未捕获到异常,它将终止程序。据推测,您平台的运行时库显示了导致程序终止的异常。

我想你真正想要的是:

std::cout << "write at position " << i << '\t';

关于c++ - vector <int> 输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556295/

相关文章:

c++ - GDB加载so文件失败并报错No such file or directory

c++ - 反转 map<string, int> 到 vector<vector<string>> 的映射

c++ - 如何实现枚举类对象的二维 vector ?

haskell - FFI 中的可变数据和惰性

c# - 从 C# : Of structs, 字符串和 wchar_t 数组调用 C++ dll 函数

c++ - 如何在类构造函数中设置STL队列的大小

c++ - 模板类可以在 C++ 中具有静态成员吗

c++ - 将 STL 容器与包含其自身 key 的类一起使用

c++ - 在 g++ 中使用 std::variant

c++ - 在C++中访问 vector 内部的数组