gpt4 book ai didi

c++ - 如何根据特定条件在 vector 中使用 count() 函数

转载 作者:行者123 更新时间:2023-11-30 01:46:32 44 4
gpt4 key购买 nike

我有一个带有一些元素的结构类型的 vector ,并试图计算一个元素(值)在其对应的 vector 列中出现的次数。我知道如何依靠一个简单的 vector ,例如 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;
}

但是,字符串类型的 vector 的相同代码,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

关于c++ - 如何根据特定条件在 vector<struct> 中使用 count() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035065/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com