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<为密钥类型重载或使用自定义比较器.
这是对相关代码的重写:
#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)
除了James McNellis所说的以外:
mapa.insert(std::make_pair(p1, "Manzana"));
Run Code Online (Sandbox Code Playgroud)
你可以用 mapa.insert({p1, "Manzana"});
| 归档时间: |
|
| 查看次数: |
68164 次 |
| 最近记录: |