【问题标题】:Is there an out of the box function for performing the reverse a string splitter? [duplicate]是否有用于执行反向字符串拆分器的开箱即用功能? [复制]
【发布时间】:2019-08-28 08:16:27
【问题描述】:

为了将字符串拆分为向量,我使用了

std::vector<std::string> v;
boost::split(v, input, boost::is_any_of("|"));

在 Boost 或 STL 中是否有一个函数可以执行此操作的反向操作,即连接函数,形式为

join(v, output, "|")

【问题讨论】:

  • 请花点时间刷新the help pages,尤其是"What topics can I ask about here?"的部分
  • 也许这可以帮助你:stackoverflow.com/questions/9277906/…
  • @Jarod42:谢谢-我粗心没看到-,请作为答案,我会投票并接受。
  • @P45Imminent “要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源的问题对于 Stack Overflow 来说是无关紧要的,因为它们往往会吸引固执己见的答案和垃圾邮件。相反,请描述问题以及迄今为止为解决该问题所做的工作。”请求函数(即使在标准库中)是题外话。如果您尝试过某事,并包含minimal reproducible example 并解释了您的尝试如何不起作用(预期和实际输出),那么这将是一个很好的问题。

标签: c++ boost


【解决方案1】:

boost::join

std::vector<std::string> v = {"Hello", "world"};
const std::string separator = " ";
std::string s = boost::join(v, separator);

Demo

【讨论】:

    【解决方案2】:

    是的,有这样一个功能,叫std::accumulate

    #include <algorithm>
    #include <iostream>
    #include <vector>
    
    
    int main() {
        std::vector<std::string> v { "a", "b" };
        std::string r = std::accumulate( v.begin(), v.end(), std::string(""),[](std::string a,std::string b){ return a + " | " + b; });
        std::cout << r;
    }
    

    输出:

     | a | b
    

    正确处理边界(开头没有|),代码变得有点冗长:传递v.begin() + 1 和相应的初始字符串,但要注意空v 的边缘情况。

    然而,并不是说std::accumulate 这个幼稚的应用程序远非高效(详见here)。

    【讨论】:

    • @Oblivion 我前段时间不再关心选票...我在您发布的链接中没有得到O(n^2) 参数。传递参考而不是值是我在写答案时已经考虑过的事情,实际上我不记得我为什么不这样做。 PS:我确实关心建设性的批评,所以谢谢你的链接
    猜你喜欢
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2011-12-03
    • 2014-09-01
    • 2014-07-21
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多