将std::map<string, string>中的第一个值转换成字符串。

3

我想创建一个std::string,其中包含由某个分隔符分开的std::map<std::string, std::string>的第一个元素(可以使用STL或Boost)。是否有比循环更好的解决方法(一行代码)?类似于std::vector<std::string>boost::algorithm::join


1
不太清楚。假设您有一个包含两个元素的映射表。您要寻找的输出结果是类似于“key1: value1,key2: value2”的东西吗? - Rerito
请参阅如何从std::map中检索所有键(或值)?,并修改解决方案以将结果追加到字符串中。 - M.M
不,@Rerito。对于“key1:value1,key2:value2”和逗号分隔符,我想要的是:“key1,key2”。 - peter55555
5个回答

7

5

如果您不想使用boost,那么可以尝试使用std::accumulate

const std::string delimiter = "#";
const std::string result = std::accumulate(M.begin(), M.end(), std::string(),
[delimiter](const std::string& s, const std::pair<const std::string, std::string>& p) {
    return s + (s.empty() ? std::string() : delimiter) + p.first;
});

在上面的代码中,M是一个std::map<std::string, std::string>

1
Mvalue_typepair<const string, string>。请注意额外的 const - Barry
最好加上:#include <numeric> - Goblinhack

1
你的算法应该类似于这样:

std::string get_keys(const std::map<std::string, std::string>& map) {
  std::string result;
  std::for_each(map.cbegin(),
                map.cend(),
                [&result](const decltype(map)::value_type& p) {
                  result += p.first;
                  result += ", ";
                });

  // Erase the last ", " from the string, if present
  if (result.size() > 0) {
    result.erase(result.size() - 2, 2);
  }

  return result;
}

基本上你需要为地图中的每个元素循环并将其添加到字符串中。复杂度为 O(N),其中 N 是地图中元素的数量。
可以通过在字符串结果上应用 reserve 来改善算法的性能。
如果你知道 字符串键 的平均长度,则可以使用以下方式初始化变量:
std::string result;
result.reserve(map.size() * AVG_LENGTH_STR_KEY);

这将大大改善循环中的operator+=操作。

1

正如M.M.正确指出的那样,您可以使用boost::range(我还添加了boost::string)来完成此操作。

如果您的映射是m,则最后一行为

std::vector<std::string> o;
boost::copy(m | boost::adaptors::map_keys, std::back_inserter(o));
boost::algorithm::join(o, ", ");

这是结果。(不幸的是,这需要大量的头文件。)
示例
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/assign.hpp>
#include <boost/algorithm/string/join.hpp>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>

int main()
{
    std::map<std::string, std::string> m;
    m["hello"] = "world";
    m["goodbye"] = "now";

    std::vector<std::string> o;
    boost::copy(m | boost::adaptors::map_keys, std::back_inserter(o));
    std::cout << boost::algorithm::join(o, ", ") << std::endl;
}

这会输出。
$ ./a.out 
goodbye, hello
$

0

如果你正在使用像仅有头文件的nlohmann::json这样的JSON库

你可以简单地尝试将其转换为一个JSON对象,只需要一行代码。 注意:要小心异常。

std::cout << "My map or vector: " << ((json)myMap)) << "\n";

编辑:我觉得这可能有点懒,但它完成了工作lol。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接