我的程序是用 C++ 编写的。
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Details
{
int x;
int y;
};
typedef std::map<string, Details> Det;
Det det;
Details::Details(int p, int c) {
x = p;
y = c;
}
int main(){
det.clear();
insertNew("test", 1, 2);
cout << det["test"] << endl;
return 0;
}
我想用最简单的方式打印一个键的值。例如 det["test"] 编译失败。 如何打印对应于键“test”的 (x,y) 的值 (1,2)?
最佳答案
我最好的猜测是您的 Obj 中没有默认构造函数或复制构造函数(您发布的代码中没有任何构造函数,但我假设您有一个采用两个整数的构造函数)。您在 catalog.insert() 行中也有错字。使用您的代码,这对我有用:
class Obj {
public:
Obj() {}
Obj(int x, int y) : x(x), y(y) {}
int x;
int y;
};
int main (int argc, char ** argv) {
std::map<std::string, Obj> catalog;
catalog.insert(std::map<std::string, Obj>::value_type("test", Obj(1,2)));
std::cout << catalog["test"].x << " " << catalog["test"].y << std::endl;
return 0;
}
关于c++ - std::map<string, class> 打印键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895295/