c++ - 如何打印 map 对象?

标签 c++ object printing dictionary

抱歉,如果我的问题是新手问题,但我找不到解决方案。

我有一个名为 Transition 的类,它有一个名为 inNext 的 map ,我想打印这个 Transition 对象,但我收到一个关于“找不到开始或结束成员”的错误(来自 map 类)

class Transition{

public:
    Transition():inNext(){};
    ~Transition(){};

    map<string, string>& getTransition(){
        return inNext;
    }

    void setTransition(string a, string b){

        inNext.insert(pair<string,string>(a,b));
    }

    void printTransition(Transition a){
        map <string, string>::iterator it;
        for(it = a.begin(); it != a.end(); it++){

            cout << (*it).first << ","<<(*it).second << endl;
        }

    }


private:
    map<string, string> inNext;

};

最佳答案

你的方法很奇怪:它是一个成员函数并且它需要另一个Transition实例(甚至无缘无故地复制它)作为一个论点。你可能想要

void print() {
    // you want to print the content of the map inNext:
    for(map <string, string>::iterator it = inNext.begin(); it != inNext.end(); it++) {
        cout << it->first << "," << it->second << endl;
    }
}

这样调用:

Transition myTransition = ...;

myTransition.print();

关于c++ - 如何打印 map 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19389721/

相关文章:

javascript - 初始化 "complex"嵌套的 javascript/对象

Javascript 回调丢失 'this'

functional-programming - 如何在标准 ML 中打印多态值?

c# - 在 C# 中为 Print Spooler API 设置标志?

c++ - 尝试使用未知类型的模板非类型参数

c++ - 构造函数参数的求值顺序

c++ - macOS : Correct programmatic way to determine volume info

C++ 为什么我只得到最后一行?

javascript - 将对象数组转换为数组数组

c# - 将面板保存为 JPEG,仅保存可见区域 c#