[問題] 請問這樣的SEARCH哪裡錯了呢

看板C_and_CPP (C/C++)作者 (呼拉拉)時間16年前 (2009/05/25 12:49), 編輯推噓2(204)
留言6則, 2人參與, 最新討論串1/1
這裡是c的bsearch跟STL的vector的混用 我覺得主要的問題應該是沒辦法取到iterator的真實的ADDRESS 給bsearch用 就是 &*(Children->begin())這部份 所以只要一跑這個search就會當掉, 說存取到0x0000000這個位址 請問這個問題要如何解決呢 謝謝各位 vector的 真實address不知道要怎麼取 class TreeNode { private: public: NodeVector * Children; TreeNode * Parent; int Item; bool ItemIsIntra; int Support; inline TreeNode( int anItem , bool Intra){ Item = anItem; ItemIsIntra = Intra; }; TreeNode * FindChild( int anItem, bool Intra ); } int TreeNodeCompare( TreeNode ** a, TreeNode ** b ) { int temp = (*a)->Item - (*b)->Item ; if( temp == 0 ){ if ( (*a)->ItemIsIntra && !(*b)->ItemIsIntra ) return -1 ; else if (!(*a)->ItemIsIntra && (*b)->ItemIsIntra ) return 1 ; else return 0 ; } else if (temp < 0) return -1 ; else return 1 ; } TreeNode * TreeNode::FindChild( int anItem, bool Intra ) { TreeNode ** Res; TreeNode * tmp = new TreeNode( anItem, Intra ); Res = (TreeNode **) bsearch( &tmp, &*(Children->begin()), Children->size(), sizeof( TreeNode *), (int (*)(const void*, const void*))TreeNodeCompare ); delete tmp; if( Res ) return (*Res); else return NULL; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.134.26.131 ※ 編輯: zesiva 來自: 140.134.26.131 (05/25 12:55)

05/25 13:08, , 1F
&(Children[0])
05/25 13:08, 1F

05/25 13:10, , 2F
而且 STL 就提供 binary_search,何苦用 bsearch
05/25 13:10, 2F

05/25 13:12, , 3F
因為STL只會回傳有沒有 想知道那個值的位置
05/25 13:12, 3F

05/25 13:18, , 4F
改了 &(Children[0])還是會存取到不合法的ADDRESS奇怪
05/25 13:18, 4F

05/25 14:00, , 5F
找到問題了 跟search無關 剛剛那樣的search是可以用的
05/25 14:00, 5F

05/25 14:16, , 6F
你可以用 lower_bound 它實際上也是 binary search
05/25 14:16, 6F
文章代碼(AID): #1A6YDJZW (C_and_CPP)
文章代碼(AID): #1A6YDJZW (C_and_CPP)