Obtain iterator from pointer or reference

回眸只為那壹抹淺笑 提交于 2019-11-29 14:54:02

Specifically for std::vector (and other contiguous containers like std::string), given a pointer to an object in the vector p, we can simply do:

auto iter = v.begin() + std::distance(v.data(), p);

This is guaranteed by the contiguity contract. Note that random access is insufficient here, the above will not work for std::deque.

For any other container, there's no easy way of doing this. You'd have to just use find_if:

auto iter = std::find_if(c.begin(), c.end(), [p](auto const& o) { return &o == p; });

For intrusive containers, the iterator will be encoded into the object itself somehow so there will be some direct mechanism for converting p to an iterator. But that will be dependent on the intrusive container itself.

You can use the find function---it returns an iterator---, supported on (almost?) all containers, to find your objects. If there are several objects which are equal under the operator==, iterate until the one with the same address has been found.

Since C++11 you can use the keyword auto to deduce the type, it makes writing the type easier.

If we know the index we can get an iterator to it bybegin() + index.

And if we don't know the index we could use the std::distance() from begin and the other iterator, which will give us an iterator to the same element.

// if we know the index
auto it1 = begin(vec) + 4;
cout << *it1;

// if we don't know the index
auto p = begin(vec) + 3;
auto it2 = begin(vec) + distance(begin(vec), p+1);
cout << *it2;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!