How to remove constness of const_iterator?

后端 未结 9 2402
囚心锁ツ
囚心锁ツ 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条回答
  • 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<int> v;                                                                                                         
    v.push_back(0);
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vector<int>::const_iterator ci = v.begin() + 2;
    cout << *ci << endl;
    vector<int>::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.

    0 讨论(0)
  • 2020-11-27 04:21

    you can convert your const iterator value pointer to a non const value pointer and use it directly something like this

        vector<int> v;                                                                                                         
    v.push_back(0);
    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    vector<int>::const_iterator ci = v.begin() + 2;
    cout << *ci << endl;
    *const_cast<int*>(&(*ci)) = 7;
    cout << *ci << endl;
    
    0 讨论(0)
  • 2020-11-27 04:23

    I believe this conversion is not needed in good designed program.

    If you need do this - try redesign code.

    As workaround you can do next:

    typedef std::vector< size_t > container_type;
    container_type v;
    // filling container code 
    container_type::const_iterator ci = v.begin() + 3; // set some value 
    container_type::iterator i = v.begin();
    std::advance( i, std::distance< container_type::const_iterator >( v.begin(), ci ) );
    

    But I'm think that sometimes this conversion is impossible, because your algorithms can haven't access to container.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题