2015-06-17 30 views
0

我正在使用Qt在C++中開發類似於linkedin的軟件。 我嘗試將用戶保存到數據庫時遇到問題,特別是當我嘗試保存他的聯繫人時。使用QT時使用const_iterator的分段錯誤

調試說功能是錯的是以下

QString network::getAllContacts(const vector<user*>& d) const{ 
QString str=""; 
for(vector<user*>::const_iterator it=friends.begin();it!=friends.end(); ++it){ 
    for(vector<user*>::const_iterator it2=d.begin(); it2!=d.end(); ++it2){ 
     if(*it==*it2){ 
     if(str.size()!=0) 
      str=str+","+QString::fromStdString((*it)->getLogin()); 
     else 
      str=QString::fromStdString((*it)->getLogin()); 
     } 
    } 
} 
return str; 
} 

它給了我一個段故障,並顯示我的STL vector.h,說

{ return const_iterator(this->_M_impl._M_finish); } 
+0

想一想爲什麼你需要一個指針向量。它不僅增加了內存管理工作量,但很少這是正確的選擇。還要考慮將字符串構建爲std :: string並在最後轉換爲QString一次。 – user4581301

回答

0

STL迭代器的線可在你的函數中不會出現段錯誤的原因(只是在不適當的情況下使用)。您正在取消引用一些未初始化的指針。

在此功能的開始處設置斷點將使您能夠檢查「在線」d,它的內容(它們是指針!危險就在這裏)是正確的。對於friends也是如此。