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

查看:16
本文介绍了减去 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 返回的迭代器返回最大/最小元素的索引?

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

推荐答案

std::vector::iterator 满足RandomAccessIterator 概念,表示它有一个operator-,可以让你将两个迭代器相减,得到一个std::vector::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天全站免登陆