How does subtracting X.begin() return the index of an iterator?

有些话、适合烂在心里 提交于 2021-02-13 17:27:49

问题


Having trouble understanding the below code:

int data[5] = { 1, 5, 2, 4, 3 }; 
 vector<int> X(data, data+5); 
 int v1 = *max_element(X.begin(), X.end()); // Returns value of max element in vector 
 int i1 = min_element(X.begin(), X.end()) – X.begin(); // Returns index of min element in vector 

Not really sure how subtracting the iterator returned by X.begin returns the index of the max/min element?


回答1:


std::vector<T>::iterator satisfies the RandomAccessIterator concept, which means that it has an operator- that allows you to subtract two iterators and obtain a std::vector<T>::iterator::difference_type that indicates the distance between the two iterators.

An under-the-hood implementation for std::vector<T>::iterator could in fact be made using pointers as iterators, in which case the subtraction operator would just be doing pointer arithmetic. There's no requirement for the iterator to be implemented using pointers, but it's a potential design.

Other containers' iterators may not have this capability. For instance, std::set<T>::iterator only satisfies the BidirectionalIterator concept, which specifies a less-rich set of functionality than the RandomAccessIterator concept.



来源:https://stackoverflow.com/questions/38919315/how-does-subtracting-x-begin-return-the-index-of-an-iterator

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