C++ vector 下标超出范围错误 1221

标签 c++ vector

我正在尝试制作一个程序,从用户那里接收数字,然后将数字从小到大重新排列。我正在使用 vector (我刚刚了解到),它给了我一个下标超出范围的错误。我找不到代码的哪一部分给我这个错误,所以希望对 vector 和 c++ 有更多了解的人可以找到它:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void order(int a, int b);
void orderRev(int a, int b);

int main() {

vector<int> num;
bool going = true;

do {
    cout << "\nEnter a number or type 'x' to order:" << endl;
    string reply;
    getline(cin, reply);
    if (reply != "x") {
        int a = atoi(reply.c_str());
        num.push_back(a);
        cout << "\nYou currently have " << num.size() << " numbers added." << endl;
    }
    else {
        going = false;
    }
} while (going);

for (int i = 0; i < num.size(); i++) {
        order(num[i], num[i + 1]);
    }

for (int i = num.size() - 1; i >= 0; i--) {
    orderRev(num[i + 1], num[i]);
}

cout << "\nThe number you entered in order from least to greatest are: " << endl;
for (int i = 0; i < num.size(); i++) {
    cout << num[i] << " ";
}


void order(int a, int b) {
    if (a > b) {
        int c = b;
        b = a;
        a = c;
    }
}

void orderRev(int a, int b) {
    if (a < b) {
        int c = b;
        b = a;
        a = c;
    }
}

最佳答案

将这些行修改为:

// added the -1 as this will now go up to the 2nd to last element
// for `n`, and the last element for `n+1`
for (int i = 0; i < num.size() - 1; i++) {
    order(num[i], num[i + 1]);
}

// changed the starting number to size -2 (for the same reasoning)
for (int i = num.size() - 2; i >= 0; i--) {
    orderRev(num[i + 1], num[i]);
}

为什么要这样?想想 C++ 中的索引是如何工作的。它们是零索引的!这意味着如果您既想要元素又想要它前面的元素,则必须达到 vector 的大小减 1。因此,对于包含 10 个项目(大小 10)的 vector ,在 i == 9 处您的代码将像这样工作:

for (int i = 0; i < num.size(); i++) {
  // i = 9
  order(num[9], num[9+1]);// index 10 does not exist! Hence, you really need to go up to num.size() - 1!
}

关于C++ vector 下标超出范围错误 1221,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136674/

相关文章:

c++ - 转换 cpp 函数以在 r 中使用

c++ - 在循环中动态创建对象

c++ - v <int> pos(MAX)v <int> tmp是非类类型 ‘__gnu_cxx::__alloc_traits<std::allocator<int>>::value_type {aka int}’ pos [i] .push_back(tmp);

c++ - 如果另一个线程将元素推送到 vector 的末尾, vector 上的迭代器会失效吗?

c++ - 将指向成员的指针强制转换为大多数派生类型

c++ - 来自 C++11 中 C99 的 fenv.h

python - 将字典映射到向量以获得一组索引向量

c++ - 我得到 "void value not ignored as it ought to be"我该怎么办?

c++ - c++读取文本文件并将数字输入2D数组中

C++ vector 初始化