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

标签 c++ stl

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

相关文章:

c++ - 在二维数组 C++ 中读取图像并保存

c++ - C++ 中的 binary_search 意外行为

c++ - STL/ranges 算法计算加权平均值

c++ - 尝试使用 *this 引用已删除的函数

c++ - C++中大尺寸的堆栈分配

c++ - 为什么会这样编译?期待 "cannot assign a constant to a non-const reference"

c++ - 查找两个字符串共有的最大字符数

c++ - 有没有办法使用 std::copy 复制不冲突的映射值?

c++ - 重置 cin 流状态 C++

c++ - “error: overloaded ' 运算符 *' must have at least one parameter of class or enumeration type” 是什么意思