40

我想使用 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++ 很陌生。

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

谢谢!

4

6 回答 6

35

std::map::insert接受一个参数:键值对,因此您需要使用:

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

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

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

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

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

于 2010-07-18T20:44:52.430 回答
7

这是有问题的代码的工作重写:

#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;
}
于 2011-01-11T14:40:24.130 回答
5

或者詹姆斯麦克内利斯所说的:

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

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

于 2015-12-09T11:08:50.610 回答
1

这是您想要做的类似版本,只需更改数据类型,仅此而已。另外,使用 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));
}   
于 2019-04-08T21:51:12.467 回答
0

std::map::emplace是你的朋友。

mapa.emplace(p1, "Manzana");
于 2021-05-11T13:14:08.317 回答
-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;
}
于 2018-03-10T18:34:11.593 回答