std::map<string, class> 打印键的值

std::map<string, class> print the value of the key

本文关键字:打印 gt string map lt std class      更新时间:2023-10-16

我的程序是用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;
}