std::map<string, class> 打印键的值
std::map<string, class> print the value of the key
我的程序是用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"]编译失败。我如何打印值(1,2)的(x,y)对应于键"测试"?
我最好的猜测是您的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;
}
为您的类Obj
创建一个operator<<
,然后您可以做一些类似std::cout << catalog["test"];
的事情(我假设插入调用中缺少的父级只是复制粘贴-o)。
我已经改变了你的代码。
#include <map>
#include <iostream>
#include <string>
using namespace std;
class Obj {
public:
Obj( int in_x, int in_y ) : x( in_x ), y( in_y )
{};
int x;
int y;
};
int main()
{
std::map< string, Obj* > catalog;
catalog[ "test" ] = new Obj(1,2);
for( std::map<string, Obj*>::iterator i=catalog.begin(); i != catalog.end(); ++i )
{
cout << "x:" << i->second->x << " y:" << i->second->y << endl;
}
}
给定这些类型:
class Obj {
int x;
int y; };
std::map<string, Obj> catalog;
给定一个填充的catalog
对象:
for(auto ob = catalog.begin(); ob != catalog.end(); ++ob)
{
cout << ob->first << " " << ob->second.x << " " << ob->second.y;
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数