美文网首页
7.count查找

7.count查找

作者: lxr_ | 来源:发表于2021-05-07 09:38 被阅读0次
    #include<iostream>
    using namespace std;
    
    #include<vector>
    #include<algorithm>
    
    //count(iterator begin, iterator end, value);统计元素出现次数
    
    //统计内置数据类型
    void test0701()
    {
        vector<int> v;
        for (int i = 0; i < 10; i++)
        {
            v.push_back(i);
        }
        v.push_back(8);
    
        int cnt = count(v.begin(), v.end(), 8);
        cout << "有" << cnt << "个" << 8 << endl;
    
    }
    //统计自定义数据类型
    class Person
    {
    public:
        Person(string name,int age)
        {
            this->m_Name = name;
            this->m_Age = age;
        }
    
        bool operator==(const Person& p)//传常量引用
        {
            if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        string m_Name;
        int m_Age;
    };
    void test0702()
    {
        vector<Person> v;
        Person p1("xian", 11);
        Person p2("xian", 11);
        Person p3("si", 12);
        Person p4("xian", 31);
        Person p5("fan", 14);
    
        v.push_back(p1);
        v.push_back(p2);
        v.push_back(p3);
        v.push_back(p4);
        v.push_back(p5);
    
        int cnt = count(v.begin(), v.end(), p1);
        
        cout << "有" << cnt << "个" << p1.m_Name << endl;
    
    }
    int main()
    {
        test0701();
        test0702();
    
        system("pause");
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:7.count查找

          本文链接:https://www.haomeiwen.com/subject/oniirltx.html