C ++使用反向顺序用逗号打印列表

时间:2018-07-12 10:34:44

标签: c++ dictionary iterator reverse-iterator

我在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() + ",";
    }
}

它运作良好,但需要以相反的顺序进行相同的操作。 我开始就是这样

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() + ",";
    }
}

但是我不知道该写些什么

4 个答案:

答案 0 :(得分:0)

我终于使用了此解决方案

std::map<const std::string, JsonNode *>::reverse_iterator it;
for (it = vals.rbegin(); it != vals.rend(); it++){
    str += it->first + ":" +it->second->toString() + ",";
}
str.erase(str.size() - 1);

谢谢。

答案 1 :(得分:0)

如果将索引迭代器与--vals.rend()进行比较,它应该可以工作。请参见下面的示例。

#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";
}

答案 2 :(得分:0)

在第一个示例中,您不需要reverse_iterator。另外,您应该使用stringstream,因为添加字符串效率很低。这是我的处理方式:

ostringstream stream(str);
auto it = vals.begin();
auto last = --vals.end();

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

str = stream.str();

我假设您至少使用C ++ 11,如果您不这样做的话,只需将auto替换为实际类型。

关于反向顺序,您可以仅使用reverse_iterator代替上面示例中的iterator,它也可以正常工作。

答案 3 :(得分:0)

如果您有一个ostream_joiner迭代器(来自this answerstd::experimental),它将变得非常简单

std::stringstream ss;
auto elem_to_string = [](MyMap::const_reference pair){ return pair.first + ":" + pair.second; };
std::transform(vals.rbegin(), vals.rend(), make_ostream_joiner(ss, ","), elem_to_string);
return ss.str();

与非反向版本相似。

相关问题