C++ <vector> insert function

C++ container class <vector>


insertis used in vector toinsert elements at the specified positionis the most flexible insertion method in containers.

insertis a member function of the container class, used toInsert one or more elements at the specified position in the container.It accepts an iterator position and the element to be inserted.

insertprovides the ability to insert elements at any position. Although in a vector the efficiency is not as good aspush_back(requiring subsequent elements to be moved), it is more powerful.

Word Definitions: insertmeans "insert", i.e., adding an element at the specified position.


Basic Syntax and Parameters

insertis a member function of the container class, requiring the insertion position and the element to be specified.

Syntax format

// 在 pos 位置插入 value 的副本
iterator insert(iterator pos, const T& value);

// 在 pos 位置插入 value 的副本(移动)
iterator insert(iterator pos, T&& value);

// 在 pos 位置插入 n 个 value 的副本
void insert(iterator pos, size_type n, const T& value);

// 在 pos 位置插入 [first, last) 范围内的元素
template&lt;class InputIt&gt;
void insert(iterator pos, InputIt first, InputIt last);

// 初始化列表方式插入
void insert(iterator pos, std::initializer_list&lt;T&gt; ilist);

Parameter description

  • Parameter: pos
    • Type: iterator (iterator)
    • Description: Iterator of the insertion position. The new element will be insertedposbefore.
    • Parameter: value
      • Type: same as the container element type
      • Description: the value of the element to insert.
      • Parameter: n
        • Type:size_type
        • Description: the number of elements to insert.

      Function description

      • Return Value: Returns an iterator pointing to the first inserted element (for single-element insertion).
      • Effect: Inserts an element at the specified position, shifting subsequent elements backward in sequence.
      • Note: insertMay cause memory reallocation, and all existing iterators may become invalid.

      Example

      Let us thoroughly master through a series of examples.insertUsage.

      Example 1: Basic usage - Inserting a single element.

      Example

      #include <iostream>
      #include <vector>

      int main() {
          std::vector<int> numbers = {1, 2, 3, 4, 5};

          std::cout << "Original vector: ";
          for(int n : numbers) std::cout << n << " ";
          std::cout << std::endl;

          // Insert 100 at the second position (index 1)
          auto it = numbers.begin() + 1;
          numbers.insert(it, 100);

          std::cout << "After inserting 100: ";
          for(int n : numbers) std::cout << n << " ";
          std::cout << std::endl;

          return 0;
      }

      Expected Output:

      原始 vector: 1 2 3 4 5
      插入 100 后: 1 100 2 3 4 5
      

      Code analysis:

      1. numbers.begin() + 1Points to the position of the second element.
      2. insertInsert 100 before that position.
      3. Subsequent elements are shifted back by one position.

      Example 2: Inserting elements at the beginning

      Usagebegin()You can insert elements at the beginning of the container.

      Example

      #include <iostream>
      #include <vector>
      #include <string>

      int main() {
          std::vector<std::string> names = {"Bob", "Charlie"};

          std::cout << "Original: ";
          for(const auto& n : names) std::cout << n << " ";
          std::cout << std::endl;

          // Insert at the beginning
          names.insert(names.begin(), "Alice");

          std::cout << "Insert Alice at the beginning: ";
          for(const auto& n : names) std::cout << n << " ";
          std::cout << std::endl;

          return 0;
      }

      Expected Output:

      原始: Bob Charlie
      在开头插入 Alice: Alice Bob Charlie
      

      Code analysis:

      • names.begin()Points to the first element.
      • Insert at that position, and the new element becomes the first element.

      Example 3: Inserting multiple identical elements

      Can insert multiple identical elements at the specified position.

      Example

      #include <iostream>
      #include <vector>

      int main() {
          std::vector<int> numbers = {1, 5};

          std::cout << "Original: ";
          for(int n : numbers) std::cout << n << " ";
          std::endl;

          // Insert 3 zeros in the middle
          auto it = numbers.begin() + 1;
          numbers.insert(it, 3, 0);

          std::cout << After inserting 3 zeros:;
          for(int n : numbers) std::cout << n << " ";
          std::cout << std::endl;

          return 0;
      }

      Expected Output:

      原始: 1 5
      插入 3 个 0 后: 1 0 0 0 5
      

      Code analysis:

      • insert(it, 3, 0)Insert 3 elements with value 0 before position it.

      Example 4: Inserting elements from another vector.

      Can insert multiple elements from another container.

      Example

      #include <iostream>
      #include <vector>

      int main() {
          std::vector<int> v1 = {1, 2, 3};
          std::vector<int> v2 = {10, 20, 30};

          std::cout << "v1: ";
          for(int n : v1) std::cout << n << " ";
          std::cout << std::endl;

          std::cout << "v2: ";
          for(int n : v2) std::cout << n << " ";
          std::cout << std::endl;

          // Insert all elements of v2 at the second position of v1
          v1.insert(v1.begin() + 1, v2.begin(), v2.end());

          std::cout << After insertion, v1:;
          for(int n : v1) std::cout << n << " ";
          std::cout << std::endl;

          return 0;
      }

      Expected Output:

      v1: 1 2 3
      v2: 10 20 30
      插入后 v1: 1 10 20 30 2 3
      

      Code analysis:

      • v1.insert(v1.begin() + 1, v2.begin(), v2.end())Insert all elements of v2 before the second position of v1.

      Example 5: Inserting using an initializer list

      C++11 supports inserting elements using an initializer list.

      Example

      #include <iostream>
      #include <vector>

      int main() {
          std::vector<int> numbers = {1, 5};

          std::cout << "Original: ";
          for(int n : numbers) std::cout << n << " ";
          std::cout << std::endl;

          // Insert using an initializer list
          numbers.insert(numbers.begin() + 1, {2, 3, 4});

          std::cout << After insertion:;
          for(int n : numbers) std::cout << n << " ";
          std::cout << std::endl;

          return 0;
      }

      Expected Output:

      原始: 1 5
      插入后: 1 2 3 4 5
      

      Code analysis:

      • Usageinitializer_listYou can insert multiple elements at once.

      Example 6: Efficiency issues of insert.

      Used in vectorinsertInserting elements at the beginning or middle position is less efficient.

      Example

      #include <iostream>
      #include <vector>
      #include <chrono>

      int main() {
          const int N = 10000;

          // Insert at the beginning (inefficient)
          std::vector<int> v1;
          auto start1 = std::chrono::high_resolution_clock::now();
          for(int i = 0; i < N; ++i) {
              v1.insert(v1.begin(), i);
          }
          auto end1 = std::chrono::high_resolution_clock::now();
          auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(end1 - start1);

          // Insert at the end (efficient)
          std::vector<int> v2;
          v2.reserve(N);
          auto start2 = std::chrono::high_resolution_clock::now();
          for(int i = 0; i < N; ++i) {
              v2.push_back(i);
          }
          auto end2 = std::chrono::high_resolution_clock::now();
          auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>(end2 - start2);

          std::cout << Inserting at the beginning << N << elements took: << duration1.count() << " microseconds" << std::endl;
          std::cout << Inserting at the end << N << elements took: << duration2.count() << " microseconds" << std::endl;

          return 0;
      }

      Code analysis:

      • Inserting an element at the beginning of a vector requires moving all existing elements, which is very inefficient.
      • If you need to frequently insert at the beginning, consider usingdequeorlist。
      • Prefer to usepush_backAdds an element at the end.

      C++ container class <vector>

      other extensions