减去 X.begin() 如何返回迭代器的索引?

How does subtracting X.begin() return the index of an iterator?(减去 X.begin() 如何返回迭代器的索引?)
本文介绍了减去 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() 如何返回迭代器的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)