gpt4 book ai didi

c++ - 在对象的指针 vector 上使用 STL 算法 (C++)

转载 作者:行者123 更新时间:2023-11-30 02:05:24 27 4
gpt4 key购买 nike

我需要计算指针数组的对象与提供给成员函数的参数具有相同名称(成员变量)的次数。我尝试了不同的方法,但都没有奏效。我的代码甚至无法编译。错误是:“错误 C2514:‘MyComparator’:类没有构造函数”,这是我用于比较的类的代码和用于计算并发的函数。

 //definition of the vector
vector<Class1*> files;
...
int Class2::countNames(string name)
{
return count_if(files.begin(), files.end(), bind2nd(MyComparator(),name));
}
...
class MyComparator{
public:
bool operator()(const CFileType*& ob1, const string &str)
{
return ob1->getName()==str;
}
};

我为此苦苦挣扎了几个小时,我想使用 STL 来完成。这里的问题是我有一个指针 vector ,如果我有一个普通 vector ,它就不需要谓词函数,在我的例子中,我必须给它一个参数,我认为 bind2nd() 是正确的方法。任何帮助将不胜感激!

最佳答案

在 C++11 下,您可以使用 lambda 表达式,这比古老的 bind2nd 容易得多。例如:

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

class Class1 {
public:
Class1(const std::string& name) : Name(name) {
}
const std::string& getName() const {
return Name;
}
private:
std::string Name;
};

size_t CountMatchingNames(const std::vector<Class1*>& v, const std::string& name) {
return std::count_if(
v.begin(),
v.end(),
[&name](Class1* c1) { return name == c1->getName(); }
);
}

int main() {

Class1 rob("rob");
Class1 bob("bob");
Class1 mitch("mitch");

std::vector<Class1*> v;
v.push_back(&bob);
v.push_back(&mitch);
v.push_back(&rob);
v.push_back(&mitch);
v.push_back(&bob);
v.push_back(&bob);

std::cout << "rob count:\t" << CountMatchingNames(v, "rob") << std::endl;
std::cout << "bob count:\t" << CountMatchingNames(v, "bob") << std::endl;
std::cout << "mitch count:\t" << CountMatchingNames(v, "mitch") << std::endl;

return EXIT_SUCCESS;

}

这打印:

rob count:      1
bob count: 3
mitch count: 2

关于c++ - 在对象的指针 vector 上使用 STL 算法 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9575752/

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