在地图中使用pair作为键(C ++ / STL)

问题描述 投票:29回答:5

我想使用STL中的一对作为地图的关键。

#include <iostream>
#include <map>

using namespace std;

int main() {

typedef pair<char*, int> Key;
typedef map< Key , char*> Mapa;

Key p1 ("Apple", 45);
Key p2 ("Berry", 20);

Mapa mapa;

mapa.insert(p1, "Manzana");
mapa.insert(p2, "Arandano");

return 0;

}

但是编译器会抛出一堆不可读的信息,而且我对C和C ++很新。

如何在地图中使用一对作为键?一般而言,我如何使用任何类型的结构(对象,结构等)作为地图中的键?

谢谢!

c++ stl map std-pair
5个回答
28
投票

std::map::insert只有一个参数:键值对,所以你需要使用:

mapa.insert(std::make_pair(p1, "Manzana"));

您应该在类型中使用std::string而不是C字符串。就像现在一样,您可能无法获得预期的结果,因为在地图中查找值将通过比较指针而不是通过比较字符串来完成。

如果你真的想要使用C字符串(再次,你不应该),那么你需要在你的类型中使用const char*而不是char*

一般而言,我如何使用任何类型的结构(对象,结构等)作为地图中的键?

您需要为密钥类型重载operator<或使用自定义比较器。


6
投票

这是对相关代码的重写:

#include <map>
#include <string>

class Key
{
  public: 
    Key(std::string s, int i)
    {
      this->s = s;
      this->i = i;
    }
    std::string s;
    int i;
    bool operator<(const Key& k) const
    {
      int s_cmp = this->s.compare(k.s);
      if(s_cmp == 0)
      {
        return this->i < k.i;
      }
      return s_cmp < 0;
    }
};

int main()
{


  Key p1 ("Apple", 45);
  Key p2 ("Berry", 20);

  std::map<Key,std::string> mapa;

  mapa[p1] = "Manzana";
  mapa[p2] = "Arandano";

  printf("mapa[%s,%d] --> %s\n",
    p1.s.c_str(),p1.i,mapa.begin()->second.c_str());
  printf("mapa[%s,%d] --> %s\n",
    p2.s.c_str(),p2.i,(++mapa.begin())->second.c_str());

  return 0;
}

5
投票

詹姆斯麦克尼利斯所说的话可以选择:

mapa.insert(std::make_pair(p1, "Manzana"));

你可以使用mapa.insert({p1, "Manzana"});


0
投票

这是您想要做的类似版本,只需更改数据类型即可。另外,使用c ++字符串,而不是我们在c中使用的字符串。

#include<bits/stdc++.h>
using namespace std;
#define  ll long long int
typedef pair<ll,ll> my_key_type;
typedef map<my_key_type,ll> my_map_type;
int  main()
{
    my_map_type m;
    m.insert(make_pair(my_key_type(30,40),6));
}   

-1
投票

这将完全符合您的要求

#include<bits/stdc++.h>
using namespace std;
int main()
{
    map<pair<string, long long int>, string> MAP;
    pair<string, long long int> P;
    MAP.insert(pair<pair<string, long long int>, string>(pair<string, long long int>("Apple", 45), "Manzana"));
    MAP.insert(pair<pair<string, long long int>, string>(pair<string, long long int>("Berry", 20), "Arandano"));
    P = make_pair("Berry", 20);
    //to find berry, 20
    cout<<MAP[P]<<"\n";
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.