gpt4 book ai didi

c++ - 如何打印 C++ 中的迭代器?

转载 作者:可可西里 更新时间:2023-11-01 17:31:07 35 4
gpt4 key购买 nike

假设,我在 C++ 中声明了一个 vector ,如下所示:

vector<int>numbers = {4,5,3,2,5,42};

我可以通过以下代码对其进行迭代:

for (vector<int>::iterator it = numbers.begin(); it!=numbers.end(); it++){
// code goes here
}

现在,我想谈谈for循环 block 中的编码。

我可以使用这个迭代器访问和更改任何值。比如说,我想将每个值增加 10 和打印。因此,代码将是:

*it+=10;
cout << *it << endl;

我可以打印迭代器和正在迭代的元素的地址。

迭代器的地址可以通过以下方式打印:

cout << &it << endl;

可以通过以下方式打印迭代元素的地址:

cout << &(*it) << endl;

但是为什么通过执行以下操作无法打印迭代器本身?

cout << it <<endl;

起初我认为约定来自 JAVA 考虑到安全目的。但如果是,那为什么我可以打印它的地址?

但是,还有其他方法吗?如果不是,为什么?

最佳答案

是的,有办法做到!

您无法打印迭代器,因为它未定义为具有值。但是您可以对它们执行算术运算,这有助于打印值(迭代器的)。

执行以下操作。

cout << it - v.begin();  

例子:

#include <iostream>     
#include <algorithm>
#include <vector>
#include <iterator>

using namespace std;

int main () {
vector<int> v = {20,3,98,34,20,11,101,201};
sort (v.begin(), v.end());

vector<int>::iterator low,up;
low = lower_bound (v.begin(), v.end(), 20);
up = upper_bound (v.begin(), v.end(), 20);

std::cout << "lower_bound at position " << (low - v.begin()) << std::endl;
std::cout << "upper_bound at position " << (up - v.begin()) << std::endl;

return 0;
}

以上代码的输出:

lower_bound at position 2
upper_bound at position 4

注意:这只是完成任务的一种方式,我并没有声称我们可以打印迭代器。

...

关于c++ - 如何打印 C++ 中的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574737/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com