I am new to coding in C++ and am running into a very basic problem. The code below is a minimal example of the problem.
Basically, I am trying to append to a vector of pointers. In the code below, the desired result is three distinct pointers in the vector. However, whenever I add a pointer to the vector, it overwrites all entries of the vector to contain that same pointer.
The output I get is:
121
-500 -500
30 30 30
The output I want is:
121
121 -500
121 -500 30
It seems really stupid, but I am not sure how to go about fixing it! Any help would be appreciated.
#include <iostream>
#include <vector>
#include <array>
#include <iterator>
#include <list>
static std::vector<std::array<int, 2> *> heap_array;
void insert_into_heap(int num){
static std::array<int, 2> test;
test[0] = num;
heap_array.push_back(&test);
}
void print_heap(){
std::vector<std::array<int, 2> *>::const_iterator it;
for(it = heap_array.begin(); it != heap_array.end(); ++it){
std::cout << (*(*it))[0] << " ";
}
std::cout << "\n";
}
int main(int argc, char** argv){
insert_into_heap(121);
print_heap();
insert_into_heap(-500);
print_heap();
insert_into_heap(30);
print_heap();
return 0;
}
As an aside, the heap-related naming is not relevant at this stage.