我在下面创建了这两个结构。我基本上希望能够将 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/