【问题标题】:accesing iterator of vector<myClass> [closed]访问 vector<myClass> 的迭代器 [关闭]
【发布时间】:2014-09-25 21:13:20
【问题描述】:

我有一个类和该类元素的向量。我需要在向量的特定位置插入新对象,但我什至无法访问我想要的位置。我试图打印我的迭代器,但它不工作......我用整数向量测试了迭代器,它工作正常,但我无法让它与我自己的类一起工作......我错过了什么?

ToDo individualTask;
vector<ToDo> myToDoList;
vector<ToDo>::iterator it;

myToDoList.push_back(individualTask);
cout << myToDoList.size() << endl;

myToDoList.resize(10);

for (it = myToDoList.begin(); it != myToDoList.end(); ++it) {
    cout << *it << endl; // not working
}

我试过 *it->toString() 它说我的类没有 toString 方法

【问题讨论】:

  • 您需要为您的类创建 toString,它在默认情况下不存在(与 Java 或 C# 不同)与运算符
  • 你能cout 一个ToDo 对象吗?此外,resize 可能会使迭代器无效。
  • 这是我的课。我想创建一个“ToDo”对象的向量并访问这些元素,我只是想打印迭代器来检查,我的目标是插入向量的特定位置。
  • @inessadl - 如果您的 ToDo 类没有 operator &lt;&lt;,则该代码无法编译。
  • 你必须为你的班级重载operator&lt;&lt;。查看operator overloading 了解更多信息。

标签: c++ oop vector iterator


【解决方案1】:

您的代码不工作的原因是您的迭代器指向的(一个 ToDo 对象)没有定义输出运算符。

如果您想使用operator&lt;&lt;() 打印出ToDo 对象,那么您需要为您的类定义一个。

这里有一个粗略的例子来告诉你这个想法:

#include <string>
#include <ctime>
#include <iostream>

// Example ToDo class
class ToDo
{
    // declare friend to allow << to access your private members
    friend std::ostream& operator<<(std::ostream& os, const ToDo& todo);
private:
    std::time_t when; // unix time
    std::string what; // task description

public:
    ToDo(std::time_t when, const std::string& what): when(when), what(what) {}
    // etc...
};

// This should go in a .cpp file. It defines how to print
// Your ToDo class objects
std::ostream& operator<<(std::ostream& os, const ToDo& todo)
{
    // todo.when needs formatting into a human readable form
    // using library functions
    os << "{" << todo.when << ", " << todo.what << "}";
    return os;
}

// Now you should be able to output ToDo class objects with `<<`:

int main()
{
    ToDo todo(std::time(0), "Some stuff");

    std::cout << todo << '\n';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 2022-09-30
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多