当我尝试运行此程序时,出现一个错误,该错误使程序停止并说"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"

本文关键字:错误 程序 out Vector of range subscript 试运行 一个      更新时间:2023-10-16
#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 个元素,因此它们的索引从 09 .


你可以通过以下方式修复它:

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]<<",";
}