C++ 映射查找值和关联的键

c++ map finding value and associated key

本文关键字:关联 映射 查找 C++      更新时间:2023-10-16

我用 c++ 开发了一个程序,其中我必须使用值在 stl map 中找到键。但是分配给键的值是 5 个元组(srcip,端口,destip,端口,srcno)

现在我想检查地图中是否有与值关联的键。我正在尝试这样的事情。

但它显示的错误像模板参数数量错误。注意(在我的程序中,成对键>值)值由 5 个变量的元组组成。

template<class T>
struct map_data_compare : public std::binary_function<typename T::value_type,typename T::mapped_type,bool>
{
public:
bool operator() (typename T::value_type &pair,typename T::mapped_type i)
{
return pair.second == i;
}
}

class Values
{
private:
std::string C_addr;
int C_port;
std::string S_addr;
int S_port;
int C_ID;
public:
Values(std::string,int,std::string,int,int);
void printValues();
};

Values :: Values(std::string Caddr,int Cport,std::string Saddr,int Sport,int Cid)
{
C_addr=Caddr;
C_port=Cport;
S_addr=Saddr;
S_port=Sport;
C_ID=Cid;
}
void Values::printValues()
{
cout << C_addr<<":" <<C_port<<":" << S_addr <<":" <<S_port << ":"<<C_ID  <<endl;
}

//In main
    {
    typedef std::map<int, Values> itemsType;
    itemsType items;

    Values connection (inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port),inet_ntoa(servaddr.sin_addr),ntohs(servaddr.sin_port),clientID);

    std::map<std::int,Values>::iterator it = std::find_if( items.begin(), items.end(), std::bind2nd(map_data_compare<itemsType>(),connection));
    if ( it != items.end() )
    {
    assert( connection == it->second);
    std::cout << "Found index:" << it->first << " for values:" << it->second << std::endl;
    }
    else
    {
    std::cout << "Did not find index for values:" << connection <<endl;
    }

我用 c++ 开发了一个程序,其中我必须使用值在 stl map 中找到键。

这不是地图的目的。如果您需要这种访问权限,我建议您使用Boost.Bimap

如果"键"必须是唯一的,也许你可以尝试将键和值组合成一个std::pair并将它们推送到std::set中。

否则,您应该将键设置为值,将值设置为键,

因为您似乎主要使用原始值作为我们对待的"键"。然后你可以使用内置的map::find()函数