c++ empty std::vector begin not equals to end

时光总嘲笑我的痴心妄想 提交于 2019-12-04 07:17:10

问题


Hi I have situation on windows 10, that declared empty class member variable vector, but this vector's begin()(first iterator) and end()(last iterator) differ, as I know in empty vector those 2 should be same. Any ideas? :)))

struct B  
{  
    std::string a;  

    std::string b;  
};

class A
{  
    A();  

    std::vector<B> vec_;    
};  

A::A()  
{

}

Here in costructor A vec_.begin().base() not equals vec_.end().base()

Which as I know should be equal


回答1:


The standard only requires that the iterators are equal, not that their adresses are the same. Considering the adresses of iterators is pointless.

As other have stated, the two iterators are different objects, so they need to have different adresses.

For reference, see this answer.




回答2:


std::vector<int> v;
assert(v.begin() == v.end());

This should work: begin and end compare equal.

On the other hand

auto b = v.begin();
auto e = v.end();
assert(&b == &e);

is prohibited from working: the two iterators are different objects and must have different addresses.

Compare the equivalent:

int i = 42;
int j = 42;
assert(i == j);   // ok
assert(&i == &j); // fail



回答3:


The iterators are returned by value, so the address will indeed not be the same. Even if you do:

const vector<whatever>::iterator &it1 = vect.begin();
const vector<whatever>::iterator &it2 = vect.begin();

the addresses of it1 and it2 can be different (and will be in many implementations) - even if references are used.

(note that using begin() in both is not a mistake - the same method begin() will return two different objects with different values)



来源:https://stackoverflow.com/questions/36504206/c-empty-stdvector-begin-not-equals-to-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!