制作链表的矢量?

时间:2011-03-19 20:33:10

标签: c++ vector linked-list

如何制作链表的载体?

例如,我有一个属性结构(对于链表),定义如下:

typedef struct property {
    string info;
    property* implication;
} property;

然后我有一个类对象:

class objects {
private:
    vector<property> *traits;
public:
    void giveProperty(property *x) {
    traits.push_back(&x);
    }
};

我想在概念上做的是为对象提供某些属性,并且每个属性都有一系列含义(链接列表),我稍后可以使用。但是我收到了错误:

  

请求成员'push_back'在'((objects *)this) - &gt; objects :: traits'中,这是非类型'std :: vector&gt; *'

我无法让这个工作。对不起,如果不清楚,如果您有任何疑问,我会尽量澄清自己。

5 个答案:

答案 0 :(得分:4)

在类objects中,您已经向属性向量声明了指针,当您真正需要属性指针的向量时:

class objects {
private:
    vector<property*> traits;    // Note where * is
public:
    void giveProperty(property *x) {
        traits.push_back(x);    // Note that x is already a pointer, no need to take its address
    }
};

答案 1 :(得分:3)

我不确定你为什么使用原始指针。你说你想要一个链表,但你没有在任何地方实现。为什么不将std::list容器用于链接列表并完全丢失指针?

#include <string>
#include <vector>
#include <list>

using std::string;
using std::vector;
using std::list;

struct implication {
    implication(string name) : name(name) {}
    string name;
};

struct property {
    property(string info) : info(info) {}
    string info;
    list<implication> implList;
};

class object {
private:
    vector<property> traits;
public:
    void giveProperty(const property& x) {
        traits.push_back(x);
    }
};

int f() {
    object o;
    property p1("p1");
    property p2("p2");
    implication i("implic");

    p1.implList.push_back(i);
    p1.implList.push_back(implication("other implic"));

    o.giveProperty(p1);

    o.giveProperty(property("p3"));
}

答案 2 :(得分:0)

改变 -

vector<property> *traits;

vector<property*>  traits; // Needs to be the declaration.

由于您尝试push_back地址到向量traits

void giveProperty(property *x) {
    traits.push_back(&x);
                     ^ Error : With the above modifications made, traits can hold
                       elements of type property*. By doing &x, you are trying to do
                       push_back pointer's address which in that case vector should
                       hold elements of type property**. So, just remove the & 
                       symbol before x while push_back because x is already of type
                       property*

}

答案 3 :(得分:0)

更改此

traits.push_back(&x);

到此:

traits->push_back(*x);

或者可能/可能,你想要改变这个:

vector<property> *traits;

到此:

vector<property*> traits;

我会选择后者!

答案 4 :(得分:0)

你明白指针是什么吗?

vector<property*> *traits; 

您正在创建一个指向矢量的指针,而不是矢量。你需要创建一个:

traits = new vector<property*>;

然后将其作为:

访问
traits->push_back(x);