Home C++ Strings Functions insert_range() C++ std::string insert_range() Function Definition In C++, std::string::insert_range() inserts every character from a range before an iterator position (C++23).
Include <string> and enable C++23.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax Pass an iterator and a range.
s.insert_range(s.begin() + 1, vec); Call What it does s.insert_range(pos, rg)Insert all of rg before iterator pos.
On older standards, insert in a loop or use iterator-pair insert overloads.
Library declarations template<class R>
constexpr iterator insert_range(const_iterator pos, R&& rg); // C++23 Parameters Parameter Description posIterator before which to insert. rgRange of characters.
Return Value Return Value Description iterator Iterator to the first inserted character (or pos if the range was empty).
C++ Examples 1. Insert vector 2. Insert at front 3. Empty range Example 1 — Insert Range in Middle Insert chars from a vector at index 1.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string s = "AC";
std::vector<char> v = {'B'};
s.insert_range(s.begin() + 1, v);
std::cout << s << '\n';
return 0;
} How It Works Iterator at offset 1 points before 'C'. The range inserts 'B' there. Result is "ABC". Example 2 — Range at begin() Insert a prefix from a string_view.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s = "Fun";
s.insert_range(s.begin(), std::string_view{"CodeTo"});
std::cout << s << '\n';
return 0;
} How It Works Insertion happens at begin(). All view characters are copied in order. Original "Fun" shifts right. Example 3 — Insert Empty Range Empty range leaves text unchanged.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string s = "keep";
std::vector<char> v;
s.insert_range(s.end(), v);
std::cout << s << '\n';
return 0;
} How It Works The vector is empty. Nothing is inserted. The string stays "keep". Frequently Asked Questions What is insert_range? C++23 API to insert a whole range of characters at an iterator.
What does it return? An iterator to the first inserted character.
Can the range be a string_view? Yes.
Fallback on C++20? Use insert with iterators or a loop.
Next: length() Keep going through the string functions. Same as size(): how many characters are in the string.
length() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
10 people found this page helpful
Helpful Share Copy link Suggestion