减去X.begin()如何返回迭代器的索引? [英] How does subtracting X.begin() return the index of an iterator?

查看:47
本文介绍了减去X.begin()如何返回迭代器的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法理解以下代码:

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 

不是很确定如何减去X.begin返回的迭代器会返回max/min元素的索引吗?

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

推荐答案

std::vector<T>::iterator满足 RandomAccessIterator概念,这意味着它具有一个operator-,它允许您减去两个迭代器并获得一个std::vector<T>::iterator::difference_type,该值指示两个迭代器之间的距离.

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.

实际上,可以使用指针作为迭代器来实现std::vector<T>::iterator的幕后实现,在这种情况下,减法运算符将只是在执行指针算术.没有使用指针实现迭代器的要求,但这是一种潜在的设计.

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.

其他容器的迭代器可能不具有此功能.例如,std::set<T>::iterator仅满足 BidirectionalIterator概念,该概念指定了一个比RandomAccessIterator概念丰富的功能集.

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.

这篇关于减去X.begin()如何返回迭代器的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆