【问题标题】:I overloaded operator<< to print all the elements in the vector, but It is not working?我重载了 operator<< 以打印向量中的所有元素,但它不起作用?
【发布时间】:2019-08-08 08:25:48
【问题描述】:

我正在为一个项目处理向量指针,但我无法打印向量中的所有元素。我尝试过运算符重载,但它不正确:

vector<list<int*>*> *v = new vector<list<int*>*> { 
    new list<int*> {new int(2), new int (7)}, 
    new list<int*> {new int(2), new int (7)}
};

for (int i = 0; i < v->size(); i++) {
    auto a = v[i].begin();
    while (a != v[i].end()) {
        cout << **a;
        a++;
    }
}

【问题讨论】:

  • 欢迎来到 StackOverflow。请不要发布代码图像,而是将实际代码添加到问题中。另外花一些时间阅读How to Ask,然后编辑您的问题以澄清您的问题。
  • 天哪,为什么会有这么多指针

标签: c++ pointers vector operator-overloading


【解决方案1】:

试试这个:

for(const auto& i : *v)
    for(const auto& j: *i)
        cout<<*j<<" ";

有使用这么多指针的理由吗?你的代码可以像这样简单得多:

   vector<list<int>> v {
   list<int> {2, 7},
   list<int> {2, 7}
};

for(const auto& i : v)
    for(const auto& j: i)
        cout<<j<<" ";

【讨论】:

    【解决方案2】:

    指针太多了,但要正确重写代码,以与您相同的风格,试试这个

    for (int i = 0; i < v->size(); i++) {
        auto a = (*v)[i]->begin();
        while (a != (*v)[i]->end()) {
            cout << **a;
            a++;
        }
    }
    

    因为v 是一个指向向量的指针,所以你必须写(*v)[i] 才能从向量中取出一个元素。那么由于该元素本身就是一个指向列表的指针,所以您必须编写 -&gt;begin() 来获取列表迭代器。

    没有那么多指针也可以写程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2012-01-18
      • 2022-09-29
      • 1970-01-01
      • 2021-11-27
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多