Partager via


vector::insert

Inserts an element or a number of elements or a range of elements into the vector at a specified position.

iterator insert(
   iterator _Where,
   const Type& _Val
);
void insert(
   iterator _Where,
   size_type _Count,
   const Type& _Val
);
template<class InputIterator>
   void insert(
      iterator _Where,
      InputIterator _First,
      InputIterator _Last
   );

Parameters

  • _Where
    The position in the vector where the first element is inserted.

  • _Val
    The value of the element being inserted into the vector.

  • _Count
    The number of elements being inserted into the vector.

  • _First
    The position of the first element in the range of elements to be copied.

  • _Last
    The position of the first element beyond the range of elements to be copied.

Return Value

The first insert function returns an iterator that points to the position where the new element was inserted into the vector.

Remarks

Any insertion operation can be expensive, see vector Class for a discussion of vector performance.

Example

// vector_insert.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

int main( )
{
   using namespace std;   
   vector <int> v1;
   vector <int>::iterator Iter;
   
   v1.push_back( 10 );
   v1.push_back( 20 );
   v1.push_back( 30 );

   cout << "v1 =" ;
   for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ )
      cout << " " << *Iter;
   cout << endl;

   v1.insert( v1.begin( ) + 1, 40 );
   cout << "v1 =";
   for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ )
      cout << " " << *Iter;
   cout << endl;
   v1.insert( v1.begin( ) + 2, 4, 50 );

   cout << "v1 =";
   for ( Iter = v1.begin( ) ; Iter != v1.end( ) ; Iter++ )
      cout << " " << *Iter;
   cout << endl;

   v1.insert( v1.begin( )+1, v1.begin( )+2, v1.begin( )+4 );
   cout << "v1 =";
   for (Iter = v1.begin( ); Iter != v1.end( ); Iter++ )
      cout << " " << *Iter;
   cout << endl;
}

v1 = 10 20 30
v1 = 10 40 20 30
v1 = 10 40 50 50 50 50 20 30
v1 = 10 50 50 40 50 50 50 50 20 30

Requirements

Header: <vector>

Namespace: std

See Also

Concepts

vector Class

vector Members

Standard Template Library