I am confused on how to use pointers and vector pointers to perform the correct operation.
I want to pass elements of vector Vec to struct function updateHeap. updateHeap modifies the value of these members. I can’t quite achieve this result with my code below. I have commented sections in my code to explain my problem better.
#include <vector>
#include <iostream>
struct A
{
A() : hLoc(100){}
A(int av, int bv):a(av),b(bv),hLoc(100){}
int a, b;
int hLoc;
};
struct Heap
{
Heap() : heapMembers(new std::vector<A>) {}
Heap(std::vector<A> *members) : heapMembers(members) {}
void updateHeap(unsigned int idx)
{
(*heapMembers)[idx].a*=2;
}
std::vector<A> *heapMembers; //ptr
};
int main()
{
std::vector<A> aVec;
//I want to use updateHeap function in struct Heap to modify values of select elements of aVec
A a0(2,5), a1(4,2), a2(8,4);
aVec.push_back(a0); aVec.push_back(a1); aVec.push_back(a2);
//Here I initialized aVec
Heap minHeap1;
//In minHeap1, I want to add elements one by one
minHeap1.heapMembers->push_back(aVec[1]);
//I added a selected element (aVec[1]) in aVec to the heap;
minHeap1.updateHeap(minHeap.heapMembers->size()-1);
//I want to modify the value of aVec[1].a by calling updateHeap function
std::cout << aVec[1].a << "\n";
//Output: 4 , I want this value to be 2*4=8.
std::vector<A> heapVec;
heapVec.push_back(a1);
Heap minHeap2(&heapVec);
//In minHeap2, I want to give it a vector of selected elements
minHeap2.updateHeap(minHeap2.heapMembers->size()-1);
//I want to modify the value of aVec[1].a by calling updateHeap function
std::cout << aVec[1].a << "\n";
//Output: 4 , I want this value to be 2*4=8.
std::cout << heapVec[0].a << "\n";
//Output: 8 , This is the right answer, but I want aVec[1].a to take upon this value
delete minHeap1.heapMembers;
return 0;
}
Your problem is that
vector::push_back()copies the pushed element into the vector; it does not push a reference nor anything like that. So after:(*minHeap1.heapMembers)[0]will be a copy ofaVec[1]. Changing that (as you do inHeap::updateHeap()) changes the copy, not the original.If you want to be able to change
aVecthroughminHeap1, you will need to actually use that vector inside the heap (more or less what you do withheapVecandminHeap2) or change the vector insideHeapso it does not contain values, but references or pointers. You cannot have anstd::vectorof references, so you will have to do with pointers:And then, in your
main()function:Of course, this will create some problems with the lifetime of the elements pointed to by the pointers inside
heapMembers, but yourmain()will work as long as you take care to makeheapVecalso anstd::vector<A*>.