如何使用其中一个键搜索具有多个键的地图
How to search a map with multiple keys with one of its keys?
我有一个类,它的键包含两个整数
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) );
免責聲明:
在浏览器中编写。未编译!取自这个答案。
相关文章:
- 为什么我在地图中搜索STL时差很大?
- C++以迭代方式搜索混合类型地图
- 我们可以使用地图而不是二叉搜索吗?
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 在地图中搜索结构元素
- unordered_maps的向量,在地图中搜索太慢
- 如何在地图中搜索一对本身的键
- 如何从特定位置开始搜索地图/多映像
- 我想使用列表中的项目在地图中搜索
- 如何在C 中搜索地图
- 在地图中按矢量搜索键
- 在地图中搜索值时'operator='不匹配
- C - 搜索地图中具有相同值的所有键的最快方法是什么
- 按值搜索地图
- 在插入之前使用 lower_bound 搜索地图的好处.相当于ptr_map?
- 为什么向量和地图搜索比静态比较要慢得多
- 如何使用其中一个键搜索具有多个键的地图
- 可以同时搜索相同成本的值和关键字的地图?象征主义地图
- 使用地图库构建电话目录搜索向量
- 使用多关键字地图进行有效搜索