3

我正在尝试创建一个向量,其中每个元素都是低于 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 循环指示元素的数量,我会得到超出范围的错误?

谢谢!

4

4 回答 4

2

默认构造函数(在此处调用:)vector<int> multiples_of_three;创建一个空向量。push_back如果您知道必须添加的对象数量,则可以使用或更好地填充它们,将该数字传递给构造函数,因此它会立即保留所需的内存量而不是不断增长(这意味着分配内存并复制旧的内存)进入新的)向量。

另一种选择是reserve从空的默认构造向量中调用并使用push_back来填充它。reserve保留足够的内存来保存所需数量的对象,但不改变向量的大小。的优点reserve是不会为每个对象调用默认构造函数(因为它将使用resize或参数化构造函数完成),这是不必要的,因为您在创建向量后立即在初始化循环中覆盖了该对象。

于 2014-06-03T07:41:17.197 回答
2

这工作得很好:

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

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

于 2014-06-03T08:09:15.680 回答
1

您需要使用push_back()而不是通过indexer添加。

索引器仅可用于对边界内的向量进行读/写访问。

于 2014-06-03T07:34:37.107 回答
1

向量不会因为您使用[]. 它从第一个示例中的 0 个元素开始,您从未增长过它。

于 2014-06-03T07:34:47.043 回答