stl vector::插入Windows和linux中的差异

stl vector::insert difference in Windows and linux?

本文关键字:linux vector 插入 Windows stl      更新时间:2023-10-16

那里。我在这里搜索了我的问题,但没有找到任何相关的内容。这就是问题所在
我的程序中有这样的代码,通过插入进行愚蠢的排序
我在MSVS2008中开发了它,它一切都很好,但当我试图用g++编译它时,由于下面的list::insert函数,它失败了;

//...
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具有与NewList内容具有相同内容类型的类型pair

在那里你可以看到响应(不可读(:

main.cpp:447:错误:没有用于调用"的匹配函数;CCD_ 8";

/usr/include/c++/4.4/bits/vvector.tcc:106:注意:候选为:__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:注意: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> >]

原因是什么?可能的解决方案是什么

您尝试使用的insert成员函数的签名可能是:

iterator insert( iterator, const value_type& );

但是传递给函数的第一个参数是const_iterator,它不能隐式转换为非常量iterator。该代码也不应该在VS上工作。

简单的解决方案是,如果您打算修改容器,则使用非常量iterator:将li定义为std::vector< std::pair<uint,double> >::iterator li = NewList.begin();

此外,您确定要插入std::向量中吗?出于性能原因,std::列表将是一个更好的选择。此外,列表上的插入不会像对向量那样使现有迭代器无效。