我有一个类,其中一个键包含两个整数
class TKey {
public:
int iKey1;
int iKey2;
};
class TData : public TKey {
public:
int iData;
};
typedef map<TKey, TData, less <TKey> > MapData;
typedef MapData::iterator ItData;
TMapData mapData;
mapData.push_back(...);
mapData.push_back(...);
现在我想找到iKey1 == 10的项目!
我不能用
TKey theKey;
theKey.iKey1 = 10;
theKey.iKey2 = void; // <<<<<
ItData it = mapData.find(theKey);
我怎样才能做到这一点?
class TKey {
public:
int iKey1;
int iKey2;
TKey( int v1, int v2):iKey1(v1), iKey2(v2){}
bool operator<( const TKey& r ) const
{
if( iKey1 < r.iKey1 )
return true;
return false;
}
};
/// class TData : public TKey { - wrong!
class TData{
public:
int iData;
TData() {};
TData( int v):iData(v){}
};
typedef map<TKey, TData/*, less <TKey>*/ > MapData; /// less by default
typedef MapData::iterator ItData;
int main()
{
MapData mapData;
mapData[TKey( 5, 0 )] = TData( 9 );
mapData[TKey( 3, 0 )] = TData( 2 );
mapData[TKey( 10, 4 )] = TData( 6 );
auto i = mapData.find( TKey( 10,5 ) );
if( i != mapData.end() )
cout << i->second.iData << endl;
else
cout << "not found" << endl;
return 0;
}
您可以使用std::find_if
函数执行自定义搜索。
struct check_iKey1
{
check_iKey1( int iKey1) : iKey1_(iKey1) {}
bool operator()( const std::pair<int, int>& v ) const
{
return v.first == iKey1_;
}
private:
int iKey1_;
};
ItData it = std::find_if( mapData.begin(), mapData.end(), check_iKey1(10) );
写在浏览器中。没编译!取自this answer。