c++ - 如何在结构 vector 中创建结构链表

标签 c++ stl

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

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;
};

但是,我真的很难弄清楚如何访问 vector 内部的列表。

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;

我的理解是,当试图从router访问dest时,它应该已经是一个指针类型并且访问dest里面的内容> 我不得不取消对指针的引用,但我一直收到错误 base operand of '->' has non-pointer type

最佳答案

试试这个 -

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;

基本上,您正在存储节点对象的 vector ,每个节点都有一个列表“对象”和“不是指针”到 std::list。因此,当您说“router.at(0).dest”时,您实际上指的是 destinfo 列表,而不是指向 destinfo 列表的指针。因此,您会收到错误消息“‘->’的基操作数具有非指针类型”。要么您必须遍历列表并访问 nh 字段。

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

关于c++ - 如何在结构 vector 中创建结构链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33513824/

相关文章:

android - 如何在没有 STL 的情况下构建 Android NDK.so?

c++ - DirectX 11 多常量缓冲区

c++ - pthread_mutex_t 类型的模糊引用

c++ - 是否可以以任何方式(使用C++预处理器等)将shared_ptr<T>替换为T$,将weak_ptr<T>替换为T%,将unique_ptr<T>替换为T?

c++ - 为什么C++ STL字符串的find函数有时出错有时正确?

c++ - 使用可变参数模板以更多参数概括 STL 算法

c++ - std::allocator 是否处理 C++17 中的过度对齐类型?

c++ - 如何强制用户/操作系统输入 Ascii 字符串

c++ - 计算 remove_if 中的删除(c++ STL)

c++ - 使用以位集为键的 map 时出现问题