2011-03-19 42 views
2

如何製作鏈接列表的矢量?製作鏈接列表的矢量?

比如我有屬性的結構(該鏈接列表)定義如下:

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

然後,我有一個類對象:

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

,我想什麼在概念上是給一個對象某些屬性,每個屬性都有一系列的含義(這是鏈表),我可以在以後使用。但我得到的錯誤:

request for member 'push_back' in '((objects*)this)->objects::traits', which is of non-class type 'std::vector >*'

我有麻煩得到這個工作。對不起,如果這不清楚,如果你有問題,我會嘗試澄清自己。

+3

爲什麼'traits'是一個指針? – GManNickG 2011-03-19 20:39:12

回答

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

好的。謝謝你的工作!我會盡我所能接受。 – Dair 2011-03-19 20:39:47

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* 

} 
0

更改此

traits.push_back(&x); 

這樣:

traits->push_back(*x); 

或很可能/可能的話,你想改變這一點:

vector<property> *traits; 

對此:

vector<property*> traits; 

我會去爲後者!

+0

謝謝,但我仍然收到一個錯誤:'沒有匹配的函數調用'std :: vector > :: push_back(property **)''做了兩個更改後。 – Dair 2011-03-19 20:39:00

+0

@anon:NO。第一或第二改變。不是都。我沒有說,改變兩個。我說「改變這個」或「這到那個」 – Nawaz 2011-03-19 20:52:16

0

你明白指針是什麼?

vector<property*> *traits; 

您正在創建一個指向矢量的指針,而不是矢量。您將需要創建一個:

traits = new vector<property*>; 

然後訪問它:

traits->push_back(x); 
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")); 
}