Feel the change: Meet the new C++23 insert_range()

Ruth Haephrati

If you need to insert a range of elements in a container, C++23 allows you to do so using a single function call — because looping is so 2020.

C++23 brought a new and useful addition to the language: insert_range(). This new member function provides a more efficient way to insert a range of elements into a vector. Until C++23, the only way to insert a range of elements into a vector was to use a loop. For example:

std::vector<int> vec1 = {1, 2, 3, 4, 5};
std::vector<int> vec2 = {6, 7, 8, 9, 10};

for (int i = 0; i < vec2.size(); i++)
{
vec1.insert(vec1.begin() + 2 + i, vec2[i]);
}
// Print the vector
for (int i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i] << " ";
}

Our output will be: 1 2 6 7 8 9 10 3 4 5

However, especially when we use large vectors, loops could be very inefficient. When you loop through a large container, you are essentially accessing each element in the container one at a time. This can be a very slow process, especially if the container is very large.

The insert_range() function solves this problem by providing a single function that can be used to insert a range of elements into a vector with a single function call. So now, instead of using the loop in our previous code, we can simply write:

std::vector<int> vec1 = {1, 2, 3, 4, 5};
std::vector<int> vec2 = {6, 7, 8, 9, 10};

auto iter = vec1.insert_range(vec1.begin() + 2, vec2.begin(), vec2.end());

for (int i = 0; i < vec1.size(); i++)
{
std::cout << vec1[i] << " ";
}

As you can see, we don’t need to use a loop, we simply add the new range to our vector.

The new insert_range() function is a really valuable addition to the C++ language, and we expect it will be widely used.

In my new book, Learning C++, published by Manning Publications and co-written with Michael Haephrati, you can learn all about C++ core language, including new C++23 features.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ruth Haephrati
Ruth Haephrati

Written by Ruth Haephrati

Co Founder of Secured Globe, Inc https://www.securedglobe.net | Author | Entrepreneur and C++ master | Cyber Security | Cyber Intelligence

No responses yet

Write a response