Search code examples
c++dictionaryiteratorreverse-iterator

C++ Printing lists with commas using reverse order


I have the following code in C++

std::map<const std::string, JsonNode *>::iterator it;
std::map<const std::string, JsonNode *>::reverse_iterator last = vals.rbegin();
last++;

for (it = vals.begin(); it != vals.end(); it++){
    if (it == last.base())
    {
        str += it->first + ":" +it->second->toString();
    }else{
        str += it->first + ":" +it->second->toString() + ",";
    }
}

It work well, but a need to to the same thing in reverse order. I began like that

std::map<const std::string, JsonNode *>::iterator first = vals.begin();
std::map<const std::string, JsonNode *>::reverse_iterator it;
first++;

for (it = vals.rbegin(); it != vals.rend(); it++){

    if (<condition>)
    {
        str += it->first + ":" +it->second->toString();
    }else{
        str += it->first + ":" +it->second->toString() + ",";
    }
}

but I don't know what to write as if condition


Solution

  • If you compare the indexing iterator to --vals.rend() it should work. See the example below.

    #include <map>
    #include <string>
    #include <iostream>
    
    using MyMap = std::map<const std::string, std::string>;
    
    std::string f(MyMap const &vals)
    {
      std::string str;
      MyMap::const_reverse_iterator it;
      MyMap::const_reverse_iterator first = --vals.rend();
    
      for (it = vals.rbegin(); it != vals.rend(); it++) {
        if (it == first) {
          str += it->first + ":" + it->second;
        } else {
          str += it->first + ":" + it->second + ",";
        }
      }
    
      return str;
    }
    
    int main()
    {
      MyMap a{{"a", "b"}, {"c","d"}};
    
      std::cout << f(a) << "\n";
    }