c++ - 尝试使用 for 循环创建和填充 vector 时出现超出范围的错误 (C++)

标签 c++ vector outofrangeexception

我正在尝试创建一个 vector ,其中每个元素都是 1000 以下的 3 的倍数。我尝试了两种方法,但只有一种有效。无效的方式是:

int main() {
    vector<int> multiples_of_three;
    for (int i = 0; i <= 1000/3; ++i)
        multiples_of_three[i] = 3*i;
        cout << multiples_of_three[i] << "\n";
}

这特别针对 multiples_of_three[i] 给出了超出范围的错误。下一段代码有效:

int main() {
    vector<int> multiples_of_three(334);
    for (int i = 0; i <  multiples_of_three.size(); ++i) {
        multiples_of_three[i] = 3*i;
        cout <<  multiples_of_three[i];
}

因此,如果我定义了 vector 的大小,我就可以将其保持在限制范围内。为什么如果我尝试让 for 循环指定元素的数量,我会收到超出范围的错误?

谢谢!

最佳答案

这工作得很好:

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

//this one is the edited version

int main() {
    vector<int> multiples_of_three(334);      //notice the change: I declared the size
    for (int i = 0; i <= 1000 / 3; ++i){
        multiples_of_three[i] = 3 * i;
        cout << multiples_of_three[i] << "\n";
    }
    system("pause");
}


Consider these two examples below:

//=========================the following example has errors =====================
int main() {

    vector<int> multiples_of_three;
    multiples_of_three[0] = 0;  // error
    multiples_of_three[1] = 3;  // error

    cout << "Here they are: " << multiples_of_three[0]; cout << endl;
    cout << "Here they are: " << multiples_of_three[1]; cout << endl;

    cout << endl;
    system("pause");

return 0;
}
//============================the following example works==========================

int main() {
    vector<int> multiples_of_three;
    multiples_of_three.push_back(0);
    multiples_of_three.push_back(3);

    cout << "Here they are: " << multiples_of_three[0]; cout << endl;
    cout << "Here they are: " << multiples_of_three[1]; cout << endl;

    cout << endl;
    system("pause");
return 0;
}

因此,除非您已经声明了大小,否则永远不要直接使用索引来分配值(如第一个示例中所示)。但是,如果已经分配了值,则可以使用索引来检索值(如第二个示例中所示)。如果您想使用索引来赋值,请首先声明数组的大小(如编辑后的版本)!

关于c++ - 尝试使用 for 循环创建和填充 vector 时出现超出范围的错误 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009472/

相关文章:

C++模板指向成员

c++ - 获取 std::set 元素地址时从 ‘const int*’ 到 ‘int*’ 的无效转换

c++ - 将 vector 中的元素与数组中的元素进行比较

c++在 vector 末尾插入元素

C++ vector::_M_range_check 错误?

c++ - CRC32 计算不对

c++ - CMake 为 FIND_PACKAGE 设置起始路径?

c++ - vector 中的方括号

c++ - 使用 C++,为什么我会收到错误消息 "string subscript out of range"而我知道它不是?或者至少看起来是这样

允许有空格的 Java 列表