c++ - 类函数 toString() C++

标签 c++ function set tostring

我有一个名为 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()在追加之前将整数转换为字符串的方法。

关于c++ - 类函数 toString() C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620138/

相关文章:

c++11 - C++ std::set upper_bound 迭代器行为

java - Hibernate OneToOne 关系 java.lang.NullPointerException

java - 识别集合中的数字集合

c++ - Windows下获取当前窗口位置

c++ - 检查UTF16字符串中的所有字符是否有效?

c++ - 如何让 Qt Tree 模型与 QSet 一起工作?

c++ - Qt setUseOpenGL(true) 和 removeSeries() 不更新 QChart

javascript - 在html中打印JS文件的结果

php - 如何添加 woocommerce 自定义订单状态?

jquery - 延迟后如何链接自定义函数?