gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:25:27 26 4
gpt4 key购买 nike

我正在尝试创建一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com