如何使用其中一个键搜索具有多个键的地图

How to search a map with multiple keys with one of its keys?

本文关键字:搜索 地图 何使用 一个      更新时间:2023-10-16

我有一个类,它的键包含两个整数

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) );

免責聲明:

在浏览器中编写。未编译!取自这个答案。