Making a vector of linked lists?
How can I make a vector of linked lists?
For example I have a struct of properties (for the linked-list) defined as follows:
typedef struct property {
string info;
property* implication;
} property;
And then I have a class object:
class objects {
private:
vector<property> *traits;
public:
void giveProperty(property *x) {
traits.push_back(&x);
}
};
Where what I want to do conceptually is give an object certain properties, and each property has a series of implications (which is the linked list) which I can use later. But I am getting the error:
request for member 'push_back' in '((objects*)this)->objects::traits', which is of non-class type 'std::vector >*'
I am hav开发者_开发技巧ing trouble getting this to work. Sorry if this is unclear, if you have questions I will try clarifying myself.
in class objects
, you have declared a pointer to a vector of properties, when really you want a vector of property pointers:
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
}
};
I'm not sure why you are using raw pointers. You say you want to have a linked list, but you don't implement that anywhere. Why not use the std::list
container for your linked lists and lose the pointers altogether?
#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"));
}
Change this
traits.push_back(&x);
to this:
traits->push_back(*x);
Or probably/possibly, you would want to change this:
vector<property> *traits;
to this:
vector<property*> traits;
I would go for the latter one!
Do you understand what pointers are?
vector<property*> *traits;
You're creating a pointer to a vector, not a vector. You would need to create one:
traits = new vector<property*>;
then access it as:
traits->push_back(x);
Change -
vector<property> *traits;
to
vector<property*> traits; // Needs to be the declaration.
Since you are trying to push_back
addresses to the vector 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*
}
精彩评论