[英]Getting out-of-range error when trying to create and populate a vector using a for loop (C++)
我正在尝试创建一个向量,其中每个元素是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];
}
因此,如果我定义了矢量的大小,我可以将其保持在它的约束范围内。 为什么如果我尝试让for循环决定元素的数量,我得到一个超出范围的错误?
谢谢!
默认构造函数(在此处调用: vector<int> multiples_of_three;
)创建一个空向量。 你可以用push_back
或更好的方法填充它们,如果你知道你必须添加的对象的数量,将该数字传递给构造函数,这样它就会立即保留所需的内存量而不是不断增长(这意味着分配内存并复制旧的menory into the new)向量。
另一种方法是从空的默认构造向量调用reserve
,并使用push_back
来填充它。 reserve
保留足够的内存以保持所需的对象数量但不改变向量的大小。 reserve
优点是不会为每个对象调用默认构造函数(因为它将使用resize
或参数化构造函数),因为在创建向量之后立即覆盖初始化循环中的对象,所以不需要这样做。
这非常好用:
#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;
}
因此,除非您已声明大小,否则不要直接使用索引来分配值(如第一个示例中所示)。 但是,如果已经分配了值,则可以使用索引来检索值(如第二个示例中所示)。 如果你想使用索引来赋值,首先要声明数组的大小(如编辑版本)!
您需要使用push_back()
而不是通过索引器添加。
索引器可用于仅在边界内对向量进行读/写访问。
因为你使用[]
矢量不会神奇地增长。 它在第一个例子中以0个元素开始,你永远不会增长它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.