fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <string>
  5.  
  6. struct my_struct
  7. {
  8. std::string first_name;
  9. std::string last_name;
  10. };
  11.  
  12. struct CompareFirstName
  13. {
  14. explicit CompareFirstName(const std::string& s) : first_name(s) {}
  15.  
  16. bool operator () (const my_struct& person) const
  17. {
  18. return person.first_name == first_name;
  19. }
  20.  
  21. std::string first_name;
  22. };
  23.  
  24. int main()
  25. {
  26. std::vector<my_struct> my_vector(5);
  27.  
  28. my_vector[0].first_name = "David";
  29. my_vector[0].last_name = "Andriw";
  30.  
  31. my_vector[1].first_name = "Jhon";
  32. my_vector[1].last_name = "Monta";
  33.  
  34. my_vector[2].first_name = "Jams";
  35. my_vector[2].last_name = "Ruth";
  36.  
  37. my_vector[3].first_name = "David";
  38. my_vector[3].last_name = "AAA";
  39.  
  40. my_vector[4].first_name = "Jhon";
  41. my_vector[4].last_name = "BBB";
  42.  
  43. for(int i = 0; i < my_vector.size(); i++)
  44. {
  45. int my_count = std::count_if(my_vector.begin(), my_vector.end(),
  46. CompareFirstName(my_vector[i].first_name));
  47. std::cout << "First_Name: " << my_vector[i].first_name << "\tCOUNT: " << my_count << std::endl;
  48. }
  49. return 0;
  50. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
First_Name: David	COUNT: 2
First_Name: Jhon	COUNT: 2
First_Name: Jams	COUNT: 1
First_Name: David	COUNT: 2
First_Name: Jhon	COUNT: 2