如何在struct vector中创建struct链接列表

时间:2015-11-04 04:39:55

标签: c++ stl

我在下面创建了这两个结构。我基本上希望能够将destInfo的列表附加到node的向量中。

enum status{
    connected, lost };

enum association{
    neighbor, notNeighbor };

struct destInfo{
    destInfo(association type, status health, int destID, int nh, int cost, double pTime):
    type(type), health(health), destID(destID), nh(nh), cost(cost), pTime(pTime){}
    association type;
    status health;
    int destID;
    int nh;
    int cost;
    double pTime;
};


struct node{
    node(int id, int size):id(id), size(size){}
    int id;
    int size;
    std::list <destInfo> dest;
};

然而,我真的很难实际知道如何访问向量内的列表。

std::vector <node> router;
node p(0, 0);
router.push_back(p);

destInfo info(neighbor, connected, 4,3,2,.123);
router.at(0).dest.push_back(info);
std::cout << router.at(0).dest->nh <<std::endl;

我的理解是,当尝试从dest访问router它应该已经是指针类型并访问dest内的内容时,我必须取消引用指针,但我继续收到错误base operand of ‘->’ has non-pointer type

1 个答案:

答案 0 :(得分:1)

试试这个 -

std::vector <node> router;
node p(0, 0);
router.push_back(p);

destInfo info(neighbor, connected, 4,3,2,.123);
router.at(0).dest.push_back(info);
std::cout << router.at(0).dest.front().nh <<std::endl;

基本上,您正在存储节点对象的向量,并且每个节点都有一个列表“object”和“not a pointer”到std :: list。所以,当你说“router.at(0).dest”时,你实际上是指destinfo列表而不是指向destinfo列表的指针。因此,您得到错误“基本操作数' - &gt;'具有非指针类型”。要么你必须遍历列表并访问nh字段。

上面的代码使用STL list.front()方法,该方法返回对列表中第一个对象的引用。

相关问题