2012-03-11 154 views
0

我一直拔出我的頭髮來找出這段錯誤,並決定要求一些幫助。
我有一個boost::multi_index容器,其中包含(string, string, double),它在某個點上遇到段錯誤。SIGSEGV在探索提升:: multi_index

這裏是我的代碼的簡化版本:

#include<iostream> 
.... 

// mySet is a multi_index container which contains <(string str1), (string str2), (double val)> 

typedef mySet::index<str1>::type set_by_str1; 

... 

for(unsigned int i=0; i < token.size(); ++i) 
{ 
    set_by_str1::iteration it = myContainer.get<str1>().find(token[i]); 
    while(it->str1() == token[i]) 
    { 
     cout << it->str1() << ", " << it->str2() << ", " << it->val << endl; 
    } 
    *it++; 
} 

此代碼似乎相當不錯的了,但只有當它擊中了一些特定的令牌崩潰(相反地說,它永遠不會崩潰的時候,這並不符合。令牌)。
我想這是因爲it高於容器本身的範圍,但不明白它可能如何發生。

GDB顯示錯誤消息:

Program received signal SIGSEGV, Segmentation fault. 
0x08052e83 in std::string::size (this=0x806e190) at /usr/include/c++/4.4/bits/basic_string.h:629 
629  { return _M_rep()->_M_length; } 

(gdb) bactrace full 
#0 0x08052e83 in std::string::size (this=0x806e190) at /usr/include/c++/4.4/bits/basic_string.h:629 
No locals. 
#1 0x08050475 in std::operator<< <char, std::char_traits<char>, std::allocator<char> > (__os=..., __str=...) 
    at /usr/include/c++/4.4/bits/basic_string.h:2503 
No locals. 
#2 0x0804e4e0 in MyClass:MyFunction (this=0xbffff534) at src/MyCode.cpp:353 (This is where while condition exists) 
... dump of HUGE trace for multi_index ... 

,當我打電話it->str1()在while條件,不能因爲標記向量的它顯然崩潰。我怎樣才能防止這一點? 我試圖在*it++的正下方添加if(it == myContainer.get<str1>().end()) break;,但沒有幫助。
有人會給我一些線索嗎?
謝謝!

回答

0

有許多與你的代碼的問題:

  • ,如果有在容器等同於token[i]沒有元素,它會崩潰,從此find回報end(),這是不提領。
  • while循環中it可以到達容器的末端,並且再次您將無法遵守它。
  • find不會給你第一個元素的密鑰等於token[i],這可能是你想要的;改爲使用lower_bound

我建議你更改代碼如下:

pair<set_by_str1::iterator, set_by_str1::iterator> p = 
    myContainer.get<str1>().equal_range(token[i]); 

while(p.first!=p.second) 
{ 
    cout << p.first->str1() << ", " << p.first->str2() << ", " 
     << p.first->val << endl; 
    ++(p.first); 
} 
0

it->str1()爲空或token[i]爲空。

確保它們不爲空,並且分段錯誤將消失。

您可能希望與if更換while,也注意,如果發現是算法從here發現,如果該項目沒有找到返回的迭代器作爲最後一個元素的迭代器,這可能str1爲空值。

你是否確定要遍歷每個字符的標記字符串,並打印每個標記字符的每個匹配項,而不僅僅爲整個標記字符串打印一個匹配項?(至少我認爲它是一個字符串,因爲你的示例代碼沒有定義它)。