迭代器的打印地址

Print address of iterator

为什么无法通过以下方式更改 cout 行以获取迭代器的地址?

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main (int argc, const char* argv[]) {
    vector<int> inputs = {15, 20, 10, 5, 19};
    vector<int>::iterator i;
    i = inputs.begin();
    cout << *i << endl;
    return 0;
}

上面的迭代器示例。清除。

cout << i << endl;

这是不可能的,因为 operator<< 没有将 vector<>::iterator 作为第二个参数的重载。如果你想打印迭代器对象的地址,你需要 &i.

或者您可以自己重载它:

std::ostream &operator<<(std::ostream &os, const std::vector<int>::iterator &i) {
  os << &i;
  return os;
}

Live sample

让我们上一点 C++ 课。

&i是一个变量的地址 *i 是对指针的尊重 i本身就是变量

所以如果你有,i 是可变的:

int i = 5;
cout << "print variable i: " << i << "\n";
cout << "print address of variable i: " << &i << "\n";

如果你有:

int* i = new int();
*i = 5;
cout << i << "\n";

会给你存储 5 的地址。

cout << &i << "\n";

将为您提供一个地址,其中存储指向 5 的指针。

cout << *i << "\n";

将打印 5.

对于打印 int 元素,您可以覆盖 io 运算符:

// here `&i` is reference to iterator 
//      (address that you cannot change)
std::ostream &operator<<(std::ostream &os, 
                         const std::vector<int>::iterator &i)
{
    os << *i;
    return os;
}

如果你去 cppreferenceiterator.bet 现在在 C++ 中你有派生类型,iteratorvector 是其中的一些。

有问题: 打印iterator是什么意思?这是维基定义

In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface.

本质上打印 iterator 本身没有意义(在你的情况下 i),因此没有实现迭代器的 io 流。

另一个不实现 IO 流的原因,就像 vector(也是 iterators)的情况一样,是它们是模板 类,这意味着您可以自定义类型。

举个例子:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class myNumb {
public:
    myNumb (int i) : num (i) {}

private:
    int num;
};

int main (int argc, const char* argv[]) {
    vector<myNumb> inputs = {15, 20, 10, 5, 19};
    vector<myNumb>::iterator i;
    i = inputs.begin();
    cout << inputs[i] << endl;
    return 0;
}

如果你有:

class myCoord {
public:
   myCoord (double lo, double la) :
                longitude (lo), latitude(la) {}
private:
   double longitude, latitude;
}

如果我们有这个怎么办:

class city {
public:
    city (string n, long p) :
         name (n), population (p)
private:
    string name;
    long population;
    myCoord location;
}

所以从本质上讲,为这些派生类型覆盖 is stream 更有意义,因此您可以在打印 arrayvectorlist 或 [=40 的元素时使用它们=] 或自定义一些其他容器。