2016-12-14 26 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; 
} 
相关问题