I have been trying to manipulate data which has been stored as list of objects in a separate class but since I dont have very solid concepts in STL I am failing again and again.
i tried a basic code and it isn't working can any one help?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class testclass
{
public: int a;
list<int> b(10);
};
int main()
{
testclass obj1;
for(int i=0;i<obj1.b.size();i++)
{
push_front(i);
}
}
Still there is error. The error is some thing else:
list3_test.cpp:8:14: error: expected identifier before numeric constant
list3_test.cpp:8:14: error: expected ‘,’ or ‘...’ before numeric constant
list3_test.cpp: In function ‘int main()’:
list3_test.cpp:14:22: error: ‘obj1.testclass::b’ does not have class type
list3_test.cpp:16:9: error: ‘obj1.testclass::b’ does not have class type
I'm not sure you can call the list's constructor like that inside of a class. Try removing the (10) and see if it works. If you want to set the size, one solution is could be to use a pointer to a list:
1 2 3 4 5 6 7 8 9 10 11
class testclass
{
public:
testclass();
list<int> *b;
};
testclass::testclass()
{
b = new list<int>(10);
}
Don't forget to delete appropriately when you're done.
Also, I think you're probably better off using an iterator to loop through the list. If you want to use the regular loop, you can't use the size() function of the list, though, because as you push to the list, you're incrementing the size (as ne555) says, so you're always expanding and your loop end condition is never met.
You could do something like:
1 2 3 4 5 6
int list_size = obj1.b.size();
for (int i=0; i < list_size; i++)
{
// Push stuff here
}
I should note that what you're doing when you're pushing to the list is adding new elements to the front, not assigning to the already existing elements.
Finally understood. Forgot that the concept of list is to let us add objects dynamically thats why no need for that 10 :)
Program is also working.
Still have one doubt. If i want to specify the number (of objects in a list of objects of a class) where the list is a member of a second class?
OR
1 2 3 4 5 6 7 8
class a
{
list<b> bobjects;
};
class b
{
members;
}
If i want to specify the length of list bobjects statically Is there a method?