2011-04-20 25 views
0

那裏。我在這裏搜索了我的問題,但沒有找到任何相關的信息。 這是問題所在。
我在我的程序的一部分中有這樣的代碼,通過插入做了一種愚蠢的排序。
我開發的MSVS 2008中,它都運行良好,但是當我試圖用g ++編譯時,由於下面的list::insert函數失敗;stl vector :: insert在Windows和linux中的區別?

//... 
pair<uint, double> NewElem(i, Prob.at(i)); 
bool inserted(false); 
vector<pair<uint, double> >::const_iterator li = NewList.begin(); 
for (vector<double>::const_iterator ji = BlocksMemory.begin() ; ji != BlocksMemory.end() ; ++ji) 
{ 
    if (NewElem.second <= *ji) 
     li += _SORT_BLOCK; 
    else 
     break; 
} 
for(;li != NewList.end() ; ++li) 
{ 
    if (NewElem.second > li->second) 
    { 
     NewList.insert(li, NewElem); 
     inserted = true; 
     break; 
    } 
} 

如人們可以看到,liNewListconst_iterator; 和NewElem的類型爲pair,內容類型與NewList內容相同;

在那裏,你可以看到響應(不可讀):

main.cpp:447: error: no matching function for call to " std::vector<std::pair<unsigned int, double>, std::allocator<std::pair<unsigned int, double> > >::insert(__gnu_cxx::__normal_iterator<const std::pair<unsigned int, double>*, std::vector<std::pair<unsigned int, double>, std::allocator<std::pair<unsigned int, double> > > >&, std::pair<unsigned int, double>&) "

/usr/include/c++/4.4/bits/vector.tcc:106: note: candidates are: __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> > std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = std::pair<unsigned int, double>, _Alloc = std::allocator<std::pair<unsigned int, double> >]

/usr/include/c++/4.4/bits/stl_vector.h:850: note: void std::vector<_Tp, _Alloc>::insert(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, size_t, const _Tp&) [with _Tp = std::pair<unsigned int, double>, _Alloc = std::allocator<std::pair<unsigned int, double> >]

什麼能是什麼原因?什麼是可能的解決方案?

回答

2

您嘗試使用insert成員函數的簽名可能是:

iterator insert(iterator, const value_type&); 

但是要傳遞給函數的第一個參數是const_iterator,不能被隱式轉換爲非常數iterator。該代碼不應該在VS上工作。

簡單的解決辦法是,如果你打算修改容器您使用非const iterator:定義listd::vector< std::pair<uint,double> >::iterator li = NewList.begin();

+0

是的,謝謝...我會被詛咒的,看起來我在編寫代碼的這一部分時非常疲倦:)這是有點自動化的,我通常在'const&'上傳遞參數,所以萬一它不能用簡單的'vector :: iterator'迭代。在我的情況下,我已經定義了在本地範圍內的向量,那裏不需要使用'const_iterator'。謝謝。 – 2011-04-21 03:29:40

1

此外,你確定要被插入到一個std :: vector的?出於性能原因,std :: list將是更好的選擇。此外,列表上的插入操作並不會像現有的矢量那樣使現有的迭代器失效。

+0

+1教育背景 – sehe 2011-04-20 21:17:00

+0

是的,你是對的,在大量數據的情況下也不需要使用順序存儲器塊。我會修改代碼。 – 2011-04-21 03:35:02

相關問題