everyone. I was doing my home task and faced some confusing stuff with vectors in c++. I've got a vector of double pointers and I'm filling it in a loop. The problem is that each iteration the value of all members of vector changes somehow.
I don't understand why it's happening what I'm doing wrong and how It should be done the proper way. This things are happening in this part of code:
std::queue<TreeNode*> vertexQueue;
std::vector<TreeNode**> vertexVector;
TreeNode* tmp;
vertexQueue.push(Tree);
while (!vertexQueue.empty()) {
tmp = vertexQueue.front();
vertexQueue.pop();
vertexVector.emplace_back(&tmp);
//this loop is for the output
for (int i = 0; i < vertexVector.size(); i++) {
std::cout << (*vertexVector[i])->info.weigth << ' ';
}
std::cout << std::endl;
if (!isLeave(tmp)) {
vertexQueue.push(tmp->leftBranch);
vertexQueue.push(tmp->rigthBranch);
}
}
Pointer tmp
is declared outside of while
loop.
In vertexVector.emplace_back(&tmp)
you add pointer containing address of tmp
into vector which is always the same. In each iteration, you change only value of tmp
what results in printing value under pointer previously assigned to tmp
.
I want to understand why double pointer vector works in such way in my program.
Then draw on paper:
vector: [pointer] [pointer] [pointer]
| | |
-------- | --------
| | |
V V V
[ tmp ]
|
|
V
<tree node>
Now what happens if you change the value of tmp?
vector: [pointer] [pointer] [pointer]
| | |
-------- | --------
| | |
V V V
[ tmp ]
|
------------
|
V
<tree node> <another node>
Correct solution is not using double, but single pointers:
vector: [pointer]
(copies) / |
[ tmp ] |
| |
----- |
| |
V V
<tree node>
And one step later:
vector: [pointer] [pointer]
| (copies) / |
| [ tmp ] |
| | |
| ---- |
| | |
V V V
<tree node> <another node>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.