如何根据特定条件在 vector<struct> 中使用 count() 函数

How to use count() function in a vector<struct> according to specific criteria

我有一个包含一些元素的结构类型的向量,并试图计算一个元素(值)在其对应的向量列中出现的次数。我知道如何依靠一个简单的向量,例如 vector of type string。但是我卡在了 vector<struct>。任何可能的解决方案或建议?

示例代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

struct my_struct
{
    std::string first_name;
    std::string last_name;
};

int main()
{
  std::vector<my_struct> my_vector(5);

  my_vector[0].first_name = "David";
  my_vector[0].last_name = "Andriw";

  my_vector[1].first_name = "Jhon";
  my_vector[1].last_name = "Monta";

  my_vector[2].first_name = "Jams";
  my_vector[2].last_name = "Ruth";

  my_vector[3].first_name = "David";
  my_vector[3].last_name = "AAA";

  my_vector[4].first_name = "Jhon";
  my_vector[4].last_name = "BBB";

  for(int i = 0; i < my_vector.size(); i++)
  {
      int my_count=count(my_vector.begin(), my_vector.end(),my_vector[i].first_name);
      /*I need help to count the number of occerencess of each "First_name" in a vector
         For example:   First_Name:- David   COUNT:- 2 ...and so on for each first_names*/    
      std::cout << "First_Name: " << my_vector[i].first_name << "\tCOUNT: " << my_count << std::endl;
  }
 return 0;
}

但是,类型字符串std::vector<std::string> 向量的相同代码可以正常工作。见下文:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

int main()
{
  std::vector<std::string> my_vector;
  my_vector.push_back("David");
  my_vector.push_back("Jhon");
  my_vector.push_back("Jams");
  my_vector.push_back("David");
  my_vector.push_back("Jhon");

  for(int i = 0; i < my_vector.size(); i++)
  {
      int my_count = count(my_vector.begin(), my_vector.end(),my_vector[i]); //this works good
      std::cout << "First_Name: " << my_vector[i] << "\tCOUNT: " << my_count << std::endl;
  }
 return 0;
}

您必须将 std::count_if 与正确的谓词一起使用:

int my_count = std::count_if(my_vector.begin(), my_vector.end(),
    [&](const my_struct& s) {
        return s.first_name == my_vector[i].first_name;
    });

Demo

在 C++03 中替换 lambda 的仿函数:

struct CompareFirstName
{
    explicit CompareFirstName(const std::string& s) : first_name(s) {}

    bool operator () (const my_struct& person) const
    {
        return person.first_name == first_name;
    }

    std::string first_name;
};

然后

int my_count = std::count_if(my_vector.begin(), my_vector.end(),
                             CompareFirstName(my_vector[i].first_name));

Demo