简体   繁体   中英

why the iterators can't refer to the container they belong to when container calls assign?

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() .

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 into a

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM