我对如何使用指针和向量指针来执行正确的操作感到困惑。
我想将 vector 的元素传递Vec
给 struct function updateHeap
。updateHeap
修改这些成员的值。我不能用下面的代码完全实现这个结果。我在我的代码中注释了部分以更好地解释我的问题。
#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;
}