4
int main ()
{
    vector<int> myvector (3,100);

    int myarray [] = { 501,502,503 };
    myvector.insert (myvector.begin(), myarray, myarray+3);

    return 0;
}

这样可行。

这不会:

typedef struct
{
    float latitude;
    float longitude;
} coordinate;

int main ()
{
    std :: vector <coordinate> previousPoints;

    coordinate start;
    start.latitude  = 22.3;
    start.longitude = 33.4;
    previousPoints.insert (previousPoints.begin (), start, 1);

    return 0;
}

错误:

anisha@linux-trra:~> g++ y.cpp 
y.cpp: In function ‘int main()’:
y.cpp:18:58: error: no matching function for call to ‘std::vector<coordinate>::insert(std::vector<coordinate>::iterator, coordinate&, int)’
/usr/include/c++/4.5/bits/vector.tcc:106:5: note: candidates are: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::iterator, const value_type&) [with _Tp = coordinate, _Alloc = std::allocator<coordinate>, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<coordinate*, std::vector<coordinate> >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = coordinate*, value_type = coordinate]
/usr/include/c++/4.5/bits/stl_vector.h:858:7: note:                 void std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::iterator, std::vector::size_type, const value_type&) [with _Tp = coordinate, _Alloc = std::allocator<coordinate>, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<coordinate*, std::vector<coordinate> >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = coordinate*, std::vector::size_type = long unsigned int, value_type = coordinate]
anisha@linux-trra:~>

错误在说什么?这两个例子有什么不同?

4

1 回答 1

7

没有将值作为第二个参数的三参数std::vector::insert方法。如果你想在前面插入,你可以试试

previousPoints.insert(previousPoints.begin(), start);

顺便说一句,如果您要经常在大型向量上执行此操作,您可能需要考虑使用 anstd::deque而不是,并使用它的push_front方法,该方法具有复杂的时间复杂度。

于 2012-09-28T05:31:17.903 回答