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() 如何返回迭代器的索引?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
