当我尝试运行此程序时,出现一个错误,该错误使程序停止并说"Vector subscript out of range"
When I try to run this program I get an error that halts the program and says, "Vector subscript out of range"
#include <iostream>
#include <vector>
using namespace std;
vector<int> niz(10);
int main() {
int i;
for(i=0; i<10; i++){
cout<<"Unesi broj: ";
cin>>niz[i];
}
vector<int> obrnuto(10);
niz[i] = obrnuto[i];
for(i=10; i>0; i--){
cout<<obrnuto[i]<<",";
}
return 0;
}
它应该在第一个向量中向后写出数字,并将它们保存在第二个向量中......我不知道有什么问题,请帮忙
int i;
for(i=0;i<10;i++){
cout<<"Unesi broj: ";
cin>>niz[i];
}
vector<int> obrnuto(10);
niz[i]=obrnuto[i];
此时i == 10
,这意味着通过niz[i]
,您正在访问第 11 个元素,一个不存在的元素。与obrnuto[i]
相同的问题
请记住,大多数语言中的数组指示从 0 开始,即int arr[10]
具有来自 arr[0]
- arr[9]
的元素。
从你的描述中,我认为你想要的很简单
niz = obrnuto;
虽然我不确定你为什么需要第二个vector
。
另外,你想要
for(i=10; i>0; i--){
要成为
for(i=9; i>=0; i--){
代码中有两个主要错误。两者都与C++等语言中的索引有关。
您必须记住,在C++中,数组的索引以0
sizeOfArray-1
开头。
那是:
for(i=0;i<10;i++){
cout<<"Unesi broj: ";
cin>>niz[i];
}
vector<int> obrnuto(10);
niz[i]=obrnuto[i]; // First error
for(i=10;i>0;i--){ // Second error
cout<<obrnuto[i]<<",";
}
第一个错误:你在 for 循环之后,i=10
.所以你在这里有第一个越界错误。
错误:你在 10 开始第二个 for 循环,也就是说,当你这样做时obrnuto[i]
你又越界了。
在您的情况下,您的向量有 10 个元素,因此它们的索引从 0
到 9
.
你可以通过以下方式修复它:
for(i=0;i<10;i++){
cout<<"Unesi broj: ";
cin>>niz[i];
}
vector<int> obrnuto(10);
niz = obrnuto; // You just want to copy the members of the vector into the second one right ?
//^^^^^^^^^^^
for ( i = 9; i >= 0; i-- ) {
// ^ ^
cout<<obrnuto[i]<<",";
}
相关文章:
- 程序崩溃并显示"std::out_of_range"错误
- xmake总是报告:错误:无法获取cxx的程序,为什么
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 分段错误当我试图运行程序时出错
- 显示错误输出的简单数组排序程序
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 在气泡排序程序中未声明错误功能
- 我在c ++矩阵计算器程序中找不到错误
- 叮当格式化程序多行格式配置错误
- 全局向量导致 C++ 程序结束时出现段错误
- 运行时间错误:程序跳过提示,以获取第二名和第三个名称
- Glibc 2.7 配置错误程序太旧
- 运行时错误:程序已停止响应
- OpenCV for Android:在 PATH 中找不到错误程序"sh"
- C++中的 scanf 错误 - 程序没有响应
- c++语法错误:程序以非零状态退出
- 运行时错误C++程序:检测到glibc,munmap_chunk(),指针无效
- libxml2错误程序c++