У меня есть такой код.Как найти товар в векторе?
#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, поскольку они слишком похожи. Предположим, I не может изменить класс 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;
}
Посмотрите на 'станд :: find_if'. – Jarod42