#include <iostream>
#include <vector>
template <typename T>
class MyVector : public std::vector<T>
{
// Bingo. You already have all the properties of a std::vector
// Now suppose You want to add a new method
// which prints all the members of the container.
public:
void printAll (void)
{
typename std::vector<T>::iterator it;
for (it = this->begin (); it != this->end (); it++)
std::cout << *it << "\t";
std::cout << std::endl;
}
};
int main (void)
{
MyVector<double> v;
v.push_back (1.1); // inherited from std::vector
v.push_back (2.5); // inherited from std::vector
v.push_back (3.9); // inherited from std::vector
v.printAll (); // you have defined it yourselves.
}
Didn't work properly. A debug cout in the add_to_mystruct function told me that the structure was just fine in there.
But the cout in int main() gave me a completely different number.
Any suggestions on how I could replicate the desired behaviour? I chose to try for a class because it seemed a lot more easy to read than a structure vector.
This is a vector with pointers to MyStruct objects: vector<MyStruct*> MyVector;
What you have created is a pointer to vector of MyStruct (not pointer to MyStruct) objects: vector<MyStruct> *MyVector;
In your case, this code takes the vector pointed to by MyVector: MyStruct *tmp = MyVector[0];
, because it is the same as the expression: MyStruct *tmp = *(MyVector + 0);
and I don't even know how it compiles.
The code never allocates the objects to which the elements point: MyStruct *tmp;
and consequently the following code writes to arbitrary memory locations: tmp->x = 5;
You need to allocate the structure like this (if you indeed need vector of pointers): MyStruct *tmp = new MyStruct();
and then you have to deallocate the objects pointed by the elements of the vector somewhere. Preferably in some destructor.