【问题标题】:how print nth split of string with boost c++?如何使用 boost c++ 打印字符串的第 n 个拆分?
【发布时间】:2018-07-18 15:51:45
【问题描述】:

我需要对字符串进行第二次拆分,在“二”以下的情况下。

我尝试运行此代码:

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));

    std::cout << results[1] << "";
}

我收到此错误:

error: no match for 'operator[]'

我该如何解决?

【问题讨论】:

  • 有什么问题?
  • 我知道如何拆分,但我不知道在这种情况下如何让第 n 部分得到“两个”
  • cout 行不行吗?它打印什么?顺便说一句,比起std::list,更喜欢std::vectorstd::list 是一个链接列表,它通常比 std::vector 慢,在这里没有任何好处。
  • 这部分不起作用 cout
  • 我很困惑,我正在寻找一些例子,但我没有找到

标签: c++ boost split


【解决方案1】:

给出的其他答案显示了错误的原因,因为您使用的是std::list,而后者又不提供operator []。最简单的方法就是使用std::vector

但是,如果您真的想使用std::list,则到达列表中某个位置的方法是前进到该位置。因此,除了 std::next 之外,还有一个 std::advance 函数可以执行此操作,它只是 std::advance 的包装器。

所以这里有一个使用std::liststd::advance 的解决方案。

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));
    auto iter = results.begin();
    std::advance(iter, 1);
    std::cout << *iter << "";
}

Live Example


现在使用std::next

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>

int main()
{
    std::string s = "one,two,three,four";
    std::list<std::string> results;

    boost::split(results, s, boost::is_any_of(","));
    auto iter = std::next(results.begin(), 1);
    std::cout << *iter << "";
}

Live Example

【讨论】:

    【解决方案2】:

    cout &lt;&lt; results[1] &lt;&lt; "";

    这不起作用,因为resultsstd::liststd::list does not provide the [] operator. 在您的用例中,您应该改用 std::vector

    【讨论】:

    • 但是我怎么能用 list 和 boost 来做到这一点呢?
    • 你为什么要使用std::list而不是std::vector
    • 我是 C++ 新手,我知道 boost 因为使用这个,我不知道向量
    • 它也可以与std::vector 一起使用......你不需要在这里std::list
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多