如何在vector<struct>中使用count()函数根据具体标准

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

本文关键字:函数 标准 count vector struct      更新时间:2023-10-16

我有一个struct类型的向量,其中包含一些元素,并试图计算元素(值)在向量的相应列中出现的次数。我知道如何计算一个简单的向量,例如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;
}

但是,对于类型为string的向量,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;
    });

演示

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));
演示