Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to assign a container using its own iterators?

Tags:

c++

As an example:

string s = "123";
s.assign(find(s.begin(),s.end(),'2'), s.end());

Is the behavior of the above code defined? Or it leads to undefined behavior?

like image 649
Artavo Avatar asked Dec 03 '19 10:12

Artavo


1 Answers

Yes. This version of assign is defined as

template<class InputIterator>
  constexpr basic_string& assign(InputIterator first, InputIterator last);

Constraints: InputIterator is a type that qualifies as an input iterator.

Effects: Equivalent to: return assign(basic_­string(first, last, get_­allocator()));

which shows a temporary computed before changes taking place.

like image 164
AProgrammer Avatar answered Nov 08 '22 13:11

AProgrammer