class function toString() C++

class function toString() C++

本文关键字:C++ toString function class      更新时间:2023-10-16

我有一个名为Set的类,它定义了一个名为Set的函数,该函数应该返回集合作为其字符串等效项。我在理解如何实现这一点方面遇到了重大问题,因为我的老师没有很好地解释该怎么做。任何方向性的帮助或解释将不胜感激。我已经发布了我的教授想要的设置。

edit1:为了清楚起见,我了解如何立即实现大多数其他函数,但由于某种原因,toString(( 函数真的没有点击我。此外,函数的名称是专门为使用这种方式而提供给我们的,因此 Union 应该大写,因为它会干扰另一个命令。

#include <iostream>
#include <algorithm>
#include <set>
#include <iterator>

class Set
{
public:
    void add(int i);
    bool belongs(int i);
    void difference(Set B);
    void Union(Set B);
    void intersect(Set B);
    std::string toString();
};
int main()
{
    Set A;
    Set B;
    std::cout << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "printing B" << std::endl;
    B.toString();
    std::cout << std::endl << "adding 12 to A" << std::endl;
    A.add(12);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "does 4 belong to A" << std::endl;
    A.belongs(4);
    std::cout << std::endl << "does 11 belong to A" << std::endl;
    A.belongs(11);
    std::cout << std::endl << " remove B from A" << std::endl;
    A.difference(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "union of A and B" << std::endl;
    A.Union(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
    std::cout << std::endl << "intersecting A and B" << std::endl;
    A.intersect(B);
    std::cout << std::endl << "printing A" << std::endl;
    A.toString();
}
//add the number i to the set
void Set::add(int i)
{
}
//return true if i is a member of the set
bool Set::belongs(int i)
{
}
//removes B from the set A where A is the current set so A=A-B
void Set::difference(Set B)
{
}
//performs A U B where A is the current set and the result is stored in A
void Set::Union(Set B)
{
}
//performs A B where A is the current set and the result is stored in A
void Set::intersect(Set B)
{
}
//displays the set in roster notation {1, 2, 3} etc
std::string Set::toString()
{
}

你的教授希望你做的是编写一个函数std::string Set::toString(){ ... }它将返回一个包含对象内部容器元素的std::string(我怀疑可能是基于你的函数的std::vector(,它将返回一个字符串,其中包含正确格式的元素。

您将需要研究如何迭代内部容器并将元素附加到使用 string::append 返回的字符串中。希望这足以真正开始该功能并实现它,因为它相当简单。在追加之前,可能需要使用 to_string() 方法将整数转换为字符串。