Home C++ Strings Functions assign_range() C++ std::string assign_range() Function Definition In C++, std::string::assign_range() replaces the string with every character from a range (C++23).
Include <string> and compile as 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 a range of characters.
s.assign_range(vec);
s.assign_range(std::string_view{"abc"}); Call What it does s.assign_range(rg)Replace contents with characters from rg.
On older C++, assign from iterators: s.assign(v.begin(), v.end()).
Library declarations template<class R>
constexpr void assign_range(R&& rg); // C++23 Parameters Parameter Description rgRange of char-convertible elements.
Return Value Return Value Description voidNo return value.
C++ Examples 1. From vector 2. From view 3. Empty range Example 1 — Assign Vector Chars Replace with vector contents.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string s = "old";
std::vector<char> v = {'n', 'e', 'w'};
s.assign_range(v);
std::cout << s << '\n';
return 0;
} How It Works Previous text is discarded. Each vector char becomes part of the string. Result is "new". Example 2 — Assign string_view Assign from a view.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s = "x";
s.assign_range(std::string_view{"OK"});
std::cout << s << '\n';
return 0;
} How It Works The view provides two characters. assign_range copies them into s. Printed value is "OK". Example 3 — Assign Empty Assigning an empty range clears the string.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string s = "gone";
std::vector<char> v;
s.assign_range(v);
std::cout << std::boolalpha << s.empty() << '\n';
return 0;
} How It Works The range has no elements. The string becomes empty. empty() reports true.Frequently Asked Questions What is assign_range? C++23 member that replaces the string with a range of characters.
Fallback? s.assign(r.begin(), r.end()) on older modes.
Does it append? No. It replaces, like assign.
Can the range be empty? Yes. Then the string becomes empty.
Next: at() Keep going through the string functions. Read or change a character by index; throws if out of range.
at() 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