如何在vector<struct>中使用count()函数根据具体标准
How to use count() function in a vector<struct> according to specific criteria
我有一个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));
演示相关文章:
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 如何使用模板化标准::函数作为参数?
- 使用宏编译时使用用户定义的数学函数,或者仅使用 c++ 中标准数学库中的函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 如何将临时数组传递给标准 C++17 中的函数
- 在双重继承的情况下如何处理非标准构造函数
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 覆盖程序中的标准 C 库函数C++
- 是否有任何 C 标准函数将值"1"传递给所有 (%s)
- VS2017 #error: : snprintf 的宏定义与标准库函数声明冲突
- 可变参数模板和标准::函数
- 为什么C++标准库容器函数 empty() 标记为 [[nodiscard]]?
- 是否有一个标准函数可以打印/监视stdin文件的内容,同时将数据留在stdin中
- 在Xcode中使用C++17标准库中的bessel数学函数
- 解释标准库排序函数C++的比较谓词的工作原理?
- C++标准是否定义了结构中成员函数的函数内定义是否必须具有静态链接?
- 标准在哪里指定类中定义的函数是内联的?
- C++11:标准::result_of<>模板参数与标准::函数<>
- 为什么我的程序说长度函数不在我的标准库中?
- 错误:调用 to 没有匹配函数...(标准::字符串&)