开发者

How does STL return 2 iterators with the same function?

开发者 https://www.devze.com 2023-01-25 13:04 出处:网络
I noticed that vec开发者_如何学编程tor.begin() will return a const iterator, or an iterator based on what is given on the left. How is something like this implemented since the arguments given to the

I noticed that vec开发者_如何学编程tor.begin() will return a const iterator, or an iterator based on what is given on the left. How is something like this implemented since the arguments given to the function are the same.

Thanks


Its return-type is based on whether the vector itself is being accessed through a const reference (or pointer) or not. Also, an iterator can be implicitly converted to a const_iterator, which is why something like this works: std::vector<T> v; std::vector<T>::const_iterator it = v.begin();.


begin() and end() are overloaded on the const-ness of *this, something like:

iterator begin();
const_iterator begin() const;

iterator end();
const_iterator end() const;


They are overloaded on the const-ness of the member function:

struct Foo
{
    int bar() { return 1; }
    int bar() const { return 2; }
};

int main()
{
    Foo a;
    const Foo b;
    assert(a.bar() == 1);
    assert(b.bar() == 2);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消