2017-10-16 129 views
0

我想知道是否有一个标准的C++类相当于一个tailq。我可以使用tailq的c实现,但它使用了很多宏,并且有点难看。C++相当于tailq

基本上,我有一个类,其中每个实例必须是多个列表的一部分。为了避免额外的malloc /内存解除引用,我想在类中存储nextprev指针。 C++有这样一个聪明的方法,还是我使用<sys/queue.h>更好?

+5

什么是'tailq'? – Ron

+0

所以你需要有一个next/prev指针的向量是这样吗?你可以制作一个简单的结构来封装你的类和两个向量,不是吗?你所描述的内容对我而言并不明显。也许更多的背景可能是有价值的。 – AlexG

+0

您如何计划一个对象成为多个链接列表的成员并存储其自己的链接?你是否会为每个列表存储一对单独的链接? –

回答

1

C++我会有容器shared_ptr。没关系,它可以是std::liststd::vector或任何容器。因为shared_ptr你的每个元素单独分配,我看不出有什么好的理由来使用std::list,所以我会去std::vector<std::shared_ptr<X>>

例子:

#include <memory> 
#include <vector> 
#include <iostream> 

struct X { int a = 0; X() = default; X(int p) { a = p; } }; 

auto operator<<(std::ostream& os, X x) -> std::ostream& 
{ 
    os << x.a; 
    return os; 
} 

int main() 
{ 
    auto x1 = std::make_shared<X>(24); 
    auto x2 = std::make_shared<X>(11); 
    auto x3 = std::make_shared<X>(1024); 
    auto x4 = std::make_shared<X>(5); 

    std::vector<std::shared_ptr<X>> v1 = {x1, x2, x3, x4}; 
    std::vector<std::shared_ptr<X>> v2 = {x3, x1, x4};  

    // modify an object and observe the change in both lists 
    x1->a = -24; 

    for (const auto& e : v1) 
     std::cout << *e << ' '; 
    std::cout << '\n'; 

    for (const auto& e : v2) 
     std::cout << *e << ' '; 
    std::cout << '\n'; 
} 

输出为:

-24 11 1024 5 
1024 -24 5 
0

将类的指针存储在其内部没有任何问题。下面的代码编译就好:

class A 
{ 
    A* next; 
    A* prev; 
}; 

这将让你有对象内部的多个列表指针:

class A 
{ 
    std::vector<A*> next; 
    std::vector<A*> prev; 
}; 
+0

是的,但是为了遍历列表,您必须使用'offsetof()'来获取原始类指针('next = current-> next - offsetof(current,next)'' ),我很怀疑C++中是否会像预期的那样工作。 (请记住,班级中有多个列表)。 – user2766918

+0

@ user2766918您可以拥有next和prev指针的向量,每个指针对应不同的列表。编辑答案反映了这一点 –