How does subtracting X.begin() return the index of an iterator?(减去 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 满足RandomAccessIterator 概念,表示它有一个operator-,可以让你将两个迭代器相减,得到一个std::vector 表示两个迭代器之间的距离.
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() 如何返回迭代器的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:减去 X.begin() 如何返回迭代器的索引?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
