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

它应该在第一个向量中向后写出数字并将它们保存在第二个向量中......我不知道出了什么问题,请帮忙

4

2 回答 2

4
int i;
for(i=0;i<10;i++){
    cout<<"Unesi broj: ";
    cin>>niz[i];
}

vector<int> obrnuto(10);
niz[i]=obrnuto[i];

At this point i == 10, which means that by niz[i], you are accessing the 11th element, one that does not exist. Same issue with obrnuto[i]

Remember that array indicies in most languages start from 0. i.e int arr[10] has elements from arr[0] - arr[9].

From your description I think you want simply

niz = obrnuto;

Although I am not sure why you need the 2nd vector at all.

Also, you want

for(i=10; i>0; i--){ 

to be

for(i=9; i>=0; i--){
于 2013-08-26T07:44:28.843 回答
0

您的代码中有两个主要错误。两者都与 C++ 等语言中的索引有关。

您必须记住,在 C++ 中,数组的索引0sizeOfArray-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]<<",";
}
于 2013-08-26T07:54:12.960 回答