|
查看: 1328|回复: 0
|
Vector + Structure + Pointer 的 問題
[复制链接]
|
|
|
我現在學著Binary Tree, 所以就做一個簡單的來玩玩, 不過遇到一個問題 >.<
我的code是這樣子的:
- #include "stdafx.h"
- #include <vector>
- using namespace std;
- struct Node
- {
- string data;
- Node *left;
- Node *right;
- float min;
- };
- int main ()
- {
- vector<Node> Region;
- Node *Struct;
- Node *Buffer;
- Node temp;
- Struct = new Node;
- Buffer = new Node;
- Struct->data = "Region 1";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 1;
- Region.push_back(*Struct);
- Struct->data = "Region 2";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 2;
- Region.push_back(*Struct);
- Struct->data = "Region 3";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 3;
- Region.push_back(*Struct);
- Struct->data = "Region 4";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 4;
- Region.push_back(*Struct);
- Struct->data = "Region 5";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 5;
- Region.push_back(*Struct);
- Struct->data = "Region 6";
- Struct->left = NULL;
- Struct->right = NULL;
- Struct->min = 6;
- Region.push_back(*Struct);
- for (int i = 0; i<Region.size(); i++)
- {
- Buffer = &Region[i];
- cout<<Buffer->data<<endl;
- }
- // Let say Region 1 and Region 2 are merged
- Struct->data = "Region 1 + 2";
- Struct->left = &Region[0];
- Struct->right = &Region[1];
- Struct->min = ((Region[0].min) + (Region[1].min))/2;
- [Breakpoint]Region.push_back(*Struct);
- temp = Region[6];
- cout<<endl<<temp.data<<"Consists of: "<<endl;
- Buffer = temp.left;
- cout<<Buffer->data;
- return 0;
- }
复制代码
我做了一個struct來裝binary tree的東西, 裏面有兩個pointer, 會指去左右兩邊的struct。全部這些struct我最後會放在vector裏面。
我要Region[6] 裏面的struct, 裏面的left 指去Region[0], right 指去Region[1], 所以我用了
Struct->data = "Region 1 + 2";
Struct->left = &Region[0];
Struct->right = &Region[1];
Struct->min = ((Region[0].min) + (Region[1].min))/2;
Region.push_back(*Struct);
不過我發現這樣子push_back的話, Region[6] left pointer 和 right pointer裏面的Data 會變成bad ptr.
不講這麽多, 上圖:
Breakpoint前 (push_back_之前)
Breakpoint 后 (push_back之後)
難道vector的 push_back 只能用在一個layer? |
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|