我有一个std::vector
指针Person
对象,它有一个成员函数std::string getName() const
。使用 STL 算法,我想计算Person
向量中getName()
返回“Chad”的所有对象。
简单地迭代循环的行为将是:
int num_chads = 0;
for(std::vector<Person *>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if((*it)->getName() == "Chad")
++num_chads;
}
我想重新设计它,以便它使用所有 STL 算法和仿函数等(使其更加面向功能)。这是我认为我需要做的:
const int num_chads = std::count_if(vec.begin(), vec.end(),
std::bind1st(std::bind2nd(std::equal_to, mem_fun(Person::getName)), "Chad"));
正如您可能会说的那样,这是行不通的。首先,据我了解,您不能在 binder1st/binder2nd 对象上使用 bind1st/bind2nd,因为它们是专门为使用std::binary_functions
. 其次,更重要的是,我认为我没有使用正确的技术。我确实想将其中一个参数绑定到“Chad”,但是对于迭代器参数,我实际上只想在调用绑定版本之前将迭代器值转换为字符串equals_to
。
我认为使用 Boost 可以做到这一点,但是否可以只使用核心 C++03(即没有 C++0x 羔羊!)?
编辑:谁能想出一个不使用用户定义谓词的示例(即仅使用 std 工具包中提供的工具)?
编辑:虽然 Matthieu 的答案是关于如何在 STL 算法中使用函子的教科书答案,但 Cubbi 的答案来自我正在寻找的方法(尽管在我编辑问题以使其更具体之前,Mathieu 确实回答了,所以在这里道歉!)。