How to remove constness of const_iterator?

后端 未结 9 2489
囚心锁ツ
囚心锁ツ 2020-11-27 03:21

As an extension to this question Are const_iterators faster?, I have another question on const_iterators. How to remove constness of a const_iterator

9条回答
  •  -上瘾入骨i
    2020-11-27 04:21

    You can subtract the begin() iterator from the const_iterator to obtain the position the const_iterator is pointing to and then add begin() back to that to obtain a non-const iterator. I don't think this will be very efficient for non-linear containers, but for linear ones such as vector this will take constant time.

    vector v;                                                                                                         
    v.push_back(0);
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vector::const_iterator ci = v.begin() + 2;
    cout << *ci << endl;
    vector::iterator it = v.begin() + (ci - v.begin());
    cout << *it << endl;
    *it = 20;
    cout << *ci << endl;
    

    EDIT: This appears to only work for linear (random access) containers.

提交回复
热议问题