Reputation: 11
string s="zhangzhizhong";
s.assign(s.begin()+2, s.end()-2);
string is correct!
vector<int> ivec{0,1,2,3,4,5};
ivec.assign(ivec.begin()+1, ivec.end()-1);
vector is also correct!!!
The above code is correct, but what is written in the book is that the iterators can't refer to the container they belong to when container calls assign()
.
Upvotes: 1
Views: 69
Reputation: 52471
This is illegal for sequential containers, like vector
or deque
.
[sequence.reqmts]/4 Table 100
a.assign(i,j)
pre:i
,j
are not iterators intoa
But I believe it's explicitly made valid for std::string
:
[string::assign]/20
template<class InputIterator> basic_string& assign(InputIterator first, InputIterator last);
Effects: Equivalent to
assign(basic_string(first, last))
.
The standard requires that the implementation make a copy of the sequence before performing the assignment (or at least, behave as if it does). There is no requirement I can see that iterators not point into the string being assigned.
I'm not sure why it doesn't work this way for containers, but if I had to guess, I'd say it's precisely to avoid forcing the implementation to make extra copies.
Upvotes: 3