I am currently trying to make a light copy of a vector
. A light copy meaning that the content of the copy, is a vector
of pointer of the original vector
. I am for some reasons having problems doing so... Each time I push_back
a new entry into the copy vector
, I seem to overwrite all the entries in the vector
, to the element I just push_back
, why is this happening:
MWE:
// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <experimental/filesystem>
#include <vector>
#include <algorithm>
struct abstract_data_structure
{
int x;
int y;
std::vector<int> points;
std::string name;
abstract_data_structure(int x, int y , std::vector<int> points, std::string name)
{
this->x= x;
this->y = y;
this->points = points;
this->name = name;
}
};
int main()
{
std::vector<abstract_data_structure> storage;
std::vector<abstract_data_structure*> copy_of_storage;
std::srand(std::time(0));
for (int i = 0; i< 5 ; i++)
{
int x = std::rand();
int y = std::rand();
std::vector<int> vecOfRandomNums(10);
std::generate(vecOfRandomNums.begin(), vecOfRandomNums.end(), []() {
return rand() % 100;
});
std::string name = "something"+std::to_string(i);
abstract_data_structure something(x,y,vecOfRandomNums,name);
storage.push_back(something);
}
std::cout << storage.size() << std::endl;
std::cout << "Make the copy" << std::endl;
for (auto element : storage)
{
std::cout << "in storage" << std::endl;
std::cout << element.name << std::endl;
copy_of_storage.push_back(&(element));
std::cout << "in copy storage" << std::endl;
for (auto copy_element: copy_of_storage)
{
std::cout << copy_element->name << std::endl;
}
}
}
https://wandbox.org/permlink/Xn96xbIshd6RXTRa
which outputs this:
5
Make the copy
in storage
something0
in copy storage
something0
in storage
something1
in copy storage
something1
something1
in storage
something2
in copy storage
something2
something2
something2
in storage
something3
in copy storage
something3
something3
something3
something3
in storage
something4
in copy storage
something4
something4
something4
something4
something4
0
As one might see are all the entries in the copy vector, modified to point to last element inserted? why?