簡體   English   中英

嘗試使用for循環創建和填充向量時出現超出范圍的錯誤(C ++)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM