class std :: vector没有名为的成员

时间:2016-12-14 19:41:30

标签: c++ c++11

#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' 我以为我们可以这样访问结构。难道我做错了什么?

3 个答案:

答案 0 :(得分: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);

或使用{ }

答案 2 :(得分:1)

矢量可以使用内置数据尽可能地推送和弹出对象。

如果我们只创建一个向量,我们可以将其推入数据:

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.

在你的例子中,你有一个数组到矢量struct 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;
}