【问题标题】:is it possible to combine 2 objects of class into one in c++?是否可以在 C++ 中将 2 个类对象合并为一个?
【发布时间】:2021-04-09 09:13:54
【问题描述】:

我正在阅读的文件包含

Johh, 13, soccer, cricket
Mitchell, 14, cricket
Michael, 13, football, cricket, soccer
(all three in separate lines starting from names)

我创建了一个类,其中包含名为姓名、年龄和最喜欢的运动的对象。是否可以在 C++ 中将年龄后的东西(最喜欢的运动)组合成一个对象,而不必编写最喜欢的运动 1、最喜欢的运动 2 等。 以 John 为例,它可以是 student.getname() = john, student.getAge() = 13 和 student.getFavSport = football,cricket。等等

真的卡在这部分,从来没有教过,任何帮助将不胜感激谢谢

【问题讨论】:

  • std::set 也可能是另一种选择,因为每个收藏夹只有一次有意义。
  • 感谢您的回复,喜欢为喜爱的运动创建矢量并将喜爱的运动推回其中吗?
  • @ibrahimovich 是的
  • student.getAge() = 13 不是很地道,考虑使用像void setage(int a) { age = a;}这样的setter

标签: c++ visual-c++ c++17


【解决方案1】:

有很多方法可以解决这个问题,因为有很多容器。您可以使用std::vector,并且有很多关于如何使用它们的教程。

对于这种情况,我建议使用std::set,它在标头<set> 中定义。

用法:

#include <set>
#include <string>

struct Student { //I imagine your class looks like this
    std::string name;
    int age;
    std::set<std::string> FavSports;
};

int main() {
    Student MyStudent;
    MyStudent.FavSports.insert("soccer"); //insert
    MyStudent.FavSports.insert("cricket"); //insert
    MyStudent.FavSports.insert("football"); //insert

    bool Exists = MyStudent.FavSports.contains("soccer"); //also can use count() function, which returns 1 or 0. 0 for false, as none exist, 1 for true, as one does exist, and a set can have a max of one item of a same type.
    //Ex: a std::set can not contain two "cricket"s.

    auto Iterator = MyStudent.FavSports.find("cricket"); //get a set iterator Iterator that points to cricket

    std::string data = Iterator->data(); //get data of Iterator ("cricket")

    ++Iterator; //point to one forward

    for (std::string Element : MyStudent.FavSports) { //for each element in FavSports
        //do something with each element
    }

    MyStudent.FavSports.insert("football"); //already exists, does nothing

}

您可以根据自己的需要进行调整。更多内容:https://en.cppreference.com/w/cpp/container/set

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 2017-09-22
    • 2015-06-19
    • 2010-10-18
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多