WeiHandsome 2023-07-09 21:00 采纳率: 85%
浏览 39
已结题

c++自定义数据求交集

大家主要看test02;我想实现自定义数据求并集该怎么做?
我已经重载了==运算符,还是报错


#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<ctime>
#include<numeric>
using namespace std;


class Person
{
public:
    Person()
    {

    }
    Person(string name, int age);
    ~Person();

    bool operator==(const Person& p) const
    {
        if (this->m_Age == p.m_Age && this->m_Name == p.m_Name)
            return 1;
        else
            return 0;
    }

    int getAge() 
    {  
        return m_Age;
    }

private:
    string m_Name;
    int m_Age;

    friend void test02();
    friend class MyPrint;
};

Person::Person(string name, int age)
{
    this->m_Name = name;
    this->m_Age = age;
}

Person::~Person()
{

}

class MyPrint
{
public:
    void operator()(const Person& p)
    {
        cout << "姓名" << p.m_Name << "年龄 "<< p.m_Age << endl;
    }
};

void myPrint(int value)
{
    cout << value << " ";
}

void test01()
{
    vector<int>v1,v2,v3;

    for (int i = 1; i < 11; i++)
    {
        v1.push_back(i);
    }

    for (int i = 5; i < 16; i++)
    {
        v2.push_back(i);
    }

    cout << "v1" << endl;
    for_each(v1.begin(), v1.end(), myPrint); cout << endl;

    cout << "v2" << endl;
    for_each(v2.begin(), v2.end(), myPrint); cout << endl;

    cout << "交集为" << endl;
    v3.resize(min(v1.size(), v2.size()));
    vector <int>::iterator itEnd=set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    for_each(v3.begin(), itEnd, myPrint); cout << endl;


}

void test02()
{

    vector<Person>v1,v2,v3;
    char nameSeed[8][2] = { "A","B","C","D","E", "F", "G", "H" };
    srand((unsigned int)time(NULL));

    for (int i = 0; i < 8; i++)
    {
        int age = rand() % 100 + 1;
        v1.push_back(Person((const char*)nameSeed[i], age));
    }



    Person pp("C", 0);
    Person ppp("D", 9999);
    v2.push_back(pp);
    v2.push_back(ppp);


    cout << "人员如下:" << endl;
    for_each(v1.begin(), v1.end(), MyPrint()); cout << endl;
    for_each(v2.begin(), v2.end(), MyPrint()); cout << endl;
       v3.resize(min(v1.size(), v2.size()));
    vector <Person>::iterator itEnd = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    for_each(v3.begin(), itEnd, MyPrint()); cout << endl;

}
int main()
{
    test01(); cout << endl;
    //test02(); cout << endl;
    std::cout << "Hello World!\n";
}
  • 写回答

2条回答 默认 最新

  • Huazie 优质创作者: 编程框架技术领域 2023-07-09 21:17
    关注

    Person 类中 还缺少个 对 < 进行重载的函数

        bool operator<(const Person& p) const 
        {
            return this->m_Age < p.m_Age;
        }
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月21日
  • 已采纳回答 7月13日
  • 创建了问题 7月9日