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

cca*_*erg 32 c++ stl map std-pair

我想使用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;

}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

Jam*_*lis 29

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

mapa.insert(std::make_pair(p1, "Manzana"));
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • @Peter:`operator []`有不同的语义,我建议不要用它来将对象插入`map`(它插入一个新对象,如果还没有,则立即覆盖新创建的临时对象) . (4认同)
  • `mapa [p1] ="Manzana";`甚至更短 (2认同)

Ale*_*son 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,因为它编译并正确执行? (7认同)
  • 为什么?这怎么比OP对'配对'更好? (2认同)
  • @Jichao 这个答案是在 C++14 之前写的。[`std::pair` 的`operator &lt;` 仅自 C++14 起存在](https://en.cppreference.com/w/cpp/utility/pair/operator_cmp)。 (2认同)

Jul*_*rcq 5

除了James McNellis所说的以外:

mapa.insert(std::make_pair(p1, "Manzana"));
Run Code Online (Sandbox Code Playgroud)

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