Khairuzzaman Mamun

  • About
  • Expeience
  • Education
  • Skills
  • Publications
  • w/R interest
  • SWOT Analysis
  • Hobbies
  • Connect me
June 26, 2025

Vectors insert function in C++

Vectors insert: The below code is an example of a vector insert function. It may help the beginners.

#include <iostream>

#include <vector>

int main()

{

std::vector<int> v = {1, 2, 4, 5};

// Insert a single element at position 2

v.insert(v.begin() + 2, 3);

// v = {1, 2, 3, 4, 5}

// Insert multiple copies of a value

v.insert(v.begin() + 1, 3, 9);

// Inserts three 9s at index 1

// v = {1, 9, 9, 9, 2, 3, 4, 5}

// Insert a range of elements from another vector

std::vector<int> other = {7, 8};

v.insert(v.end(), other.begin(), other.end());

// Appends 7 and 8

// v = {1, 9, 9, 9, 2, 3, 4, 5, 7, 8}

// Insert using an initializer list at the beginning

v.insert(v.begin(), {10, 11}); // Inserts 10 and 11 at the start

// v = {10, 11, 1, 9, 9, 9, 2, 3, 4, 5, 7, 8}

// Print the final result

std::cout << "Vector contents: ";

for (int val : v)

{

std::cout << val << " ";

}

std::cout << std::endl;

return 0;

}

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Telegram (Opens in new window) Telegram
  • Share on WhatsApp (Opens in new window) WhatsApp
  • Share on X (Opens in new window) X
  • Print (Opens in new window) Print
  • Email a link to a friend (Opens in new window) Email
Like Loading…
ai
ai

Leave a comment Cancel reply

Menu

  • About
  • Expeience
  • Education
  • Skills
  • Publications
  • w/R interest
  • SWOT Analysis
  • Hobbies
  • Connect me

Contact

020-0127, Morioka, Iwate

Zenkunen, 3-9-3-305

presidentmamun@gmail.com

+81-80-9632-6849

Khairuzzaman Mamun

A multidisciplinary research engineer. To discover more about him—click here.

Designed by Khairuzzaman Mamun

  • Comment
  • Reblog
  • Subscribe Subscribed
    • Khairuzzaman Mamun
    • Already have a WordPress.com account? Log in now.
    • Khairuzzaman Mamun
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Copy shortlink
    • Report this content
    • View post in Reader
    • Manage subscriptions
    • Collapse this bar
%d