繁体   English   中英

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”]无法编译。 如何为与键“测试”相对应的(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;
}

为您的类Obj创建一个operator<< ,然后您可以执行类似std::cout << catalog["test"]; (我假设插入调用中缺少的括号只是一个copy-paste-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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM