Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?
This works: (of course it does)
std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);
This doesn't work: (what should I do instead?)
std::list<int> l;
std::list<int>::reverse_iterator reverse = l.rbegin();
l.insert(reverse, 10);
Essentially, you don't. See 19.2.5 in TCPPPL.
The reverse_iterator
has a member called base()
which will return a "regular" iterator. So the following code would work in your example:
l.insert(reverse.base(), 10);
Be careful though because the base()
method returns the element one after the orginal reverse_iterator
had pointed to. (This is so that reverse_iterators pointing at rbegin()
and rend()
work correctly.)
Just in case it is helpful, as this it the first hit on a search, here is a working example of using rbegin
. This should be faster than using std::stringstream
or sprint
. I defiantly call a member fmt_currency
many thousands of times in some print jobs. The std::isalnum
is for handling a minus sign.
std::wstring fmt_long(long val) {//for now, no options? Just insert commas
std::wstring str(std::to_wstring(val));
std::size_t pos{ 0 };
for (auto r = rbegin(str) + 1; r != str.rend() && std::isalnum(*r); ++r) {
if (!(++pos % 3)) {
r = std::make_reverse_iterator(str.insert(r.base(), L','));
return str;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.