我有一块这样的代码。如何在矢量中查找物品?
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class A
{
public:
A(int iVal) : _val(iVal) {}
int getVal() const { return _val; }
private:
int _val;
};
class B
{
public:
B(int iNum) : _num(iNum) {}
int getNum() const { return _num; }
private:
int _num;
};
bool isInVecA(vector<A> vectorA, int iVal)
{
for(vector<A>::const_iterator it=vectorA.begin(); it != vectorA.end(); it++)
{
if(it->getVal() == iVal)
return true;
}
return false;
}
bool isInVecB(vector<B> vectorB, int iNum)
{
for(vector<B>::const_iterator it=vectorB.begin(); it != vectorB.end(); it++)
{
if(it->getNum() == iNum)
return true;
}
return false;
}
int main()
{
A arrayA[] = { A(1), A(2), A(3) };
vector<A> vectorA(arrayA, arrayA + sizeof(arrayA)/sizeof(A));
B arrayB[] = { B(3), B(4), B(5) };
vector<B> vectorB(arrayB, arrayB + sizeof(arrayB)/sizeof(B));
int key = 3;
if(isInVecA(vectorA, key) && isInVecB(vectorB, key))
cout << "Key " << key << " is in both vectors." << endl;
else
cout << "Key " << key << " is not in both vectors." << endl;
return 0;
}
我想要做的就是创造一些替换功能isInVecA和isInVecB,因为他们太相似了。假设我不能变化A级和B级。
非常感谢大家。 我是StackOverflow的新手。不知道在哪里发布我的朋友和我提出的解决方案。所以,我把它放在这里。
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <functional>
#include <boost/bind.hpp>
using namespace std;
class A
{
public:
A(int iVal) : _val(iVal) {}
int getVal() const { return _val; }
private:
int _val;
};
class B
{
public:
B(int iNum) : _num(iNum) {}
int getNum() const { return _num; }
private:
int _num;
};
template<typename T>
bool isInVec(vector<T> vec, int (T::*func)() const, int iVal)
{
return find_if(vec.begin(), vec.end(), boost::bind(func, _1) == iVal) != vec.end();
}
int main()
{
A arrayA[] = { A(1), A(2), A(3) };
vector<A> vectorA(arrayA, arrayA + sizeof(arrayA)/sizeof(A));
B arrayB[] = { B(3), B(4), B(5) };
vector<B> vectorB(arrayB, arrayB + sizeof(arrayB)/sizeof(B));
int key = 3;
if(isInVec<A>(vectorA, &A::getVal, key) && isInVec<B>(vectorB, &B::getNum, key))
cout << "Key " << key << " is in both vectors." << endl;
else
cout << "Key " << key << " is not in both vectors." << endl;
return 0;
}
查看'std :: find_if'。 – Jarod42