从所有迭代中删除尾随逗号

时间:2017-04-11 00:22:12

标签: c++

我知道如何删除尾随逗号,但我似乎无法弄清楚如何从所有迭代中删除尾随逗号,因为我的代码只删除了最后一个。多次调用此方法时,我得到的输出如下:

A:on 0 -> B, on 1 -> A, 
B:on 0 -> C, on 1 -> A, 
C:on 0 -> C, on 1 -> A
string FSA::transitions_to_string(string s) {

    std::ostringstream oss;
    string output = "";
    map<string, string>::iterator itr1;
    map<string, map<string, string> >::iterator itr2;
    map<string, map<string, string> >::iterator itr3;

    itr3 = table_.find(s);

    if (itr3 == table_.end()) {
        throw domain_error (s + " doesn't exist");
    }

   for (itr2 = table_.begin(); itr2 != table_.end(); itr2++) {
    oss << itr2->first << ":";
        for (itr1 = itr2->second.begin(); itr1 != itr2->second.end(); itr1++) {
            oss << "on " << itr1->first << " -> " << itr1->second << ", ";
            output = oss.str();
        }

    oss << endl;
    }

    return output.substr(0, output.size() - 2);
}

1 个答案:

答案 0 :(得分:1)

不像@BoundaryImposition指出的那样删除尾随的逗号,你可以不写它

for (itr2 = table_.begin(); itr2 != table_.end(); itr2++) {
    string delim = ""; // set blank for first element of each inner loop
    oss << itr2->first << ":";
    for (itr1 = itr2->second.begin(); itr1 != itr2->second.end(); itr1++) {
        oss << delim << "on " << itr1->first << " -> " << itr1->second;
        delim = ", "; // after first loop this is a nop
    }
    oss << endl;
}
return oss.str();