2016-12-14 64 views
3
#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

struct coffeeBean 
{ 
    string name; 
    string country; 
    int strength; 
}; 

std::vector<coffeeBean> coffee_vec[4]; 

int main(int argc, char ** argv) 
{ 
    coffee_vec[1].name; 
    return 0; 
} 

當我嘗試運行此代碼,我得到'class std::vector<coffeeBean>' has no member named 'name' 我以爲我們可以訪問該結構這樣成員。難道我做錯了什麼?類的std ::向量沒有命名

+4

在聲明向量你需要像使用數組一樣使用'()'或'{}',而不是'[]'。 – NathanOliver

回答

5

您正在創建一個包含四個向量的數組,而不是具有四個元素的向量。

在您的代碼中,coffee_vec[1]指的是vector<coffeeBean>對象,而不是coffeeBean對象。

+1

「爲什麼無法從矢量訪問結構?」的好答案?和「我做錯了什麼?」也許你也可以回答隱含的「我如何讓它變得更好?」 –

5

coffe_vec[1]您沒有訪問的coffeBean實例但std::vector<coffeBean>因爲coffe_vec一個實例是矢量的陣列。如果你想訪問coffeBean元素,你需要調用例如coffe_vec[1][0],這對你的情況不太好,因爲你的數組中的所有向量都是空的。

也許你想創建4個元素的向量,這將看起來像:

std::vector<coffeBean> coffe_vec(4); 

或使用{ }

1

載體可以push和pop的對象,因爲它可以與內置數據。

,如果我們只建立一個載體,我們可以把它推達塔:

std::vector<int> vecInt; // vector of integers 
std::vector<int> vecInt[4]; // an array of vectors to integers 

so the array of vectors is like a multi-dimensional array. so to access the data we double the subscript operator `[][]`: 

vecInt[0].push_back(5); 
cout << vecInt[0][0]; // the first for first vector in the array and the second index is for the first data in the first vector in the array. 

在你的榜樣,你有一個數組,以載體爲結構coffeebeen:

std::vector<coffeeBean> coffee_vec[4]; 

int main(int argc, char ** argv) 
{ 

    coffeeBean cofB = { "Raindrop7", "England", 5 }; 
    coffee_vec[0].push_back(cofB); // push the object in the first vector in the array 

    cout << (coffee_vec[0][0]).name << endl; 


    cin.get(); 
    return 0; 
}