【问题标题】:How to copy std::regex_token_iterator to a std::vector?如何将 std::regex_token_iterator 复制到 std::vector?
【发布时间】:2017-12-06 18:44:15
【问题描述】:

以下代码无法将值从 regex_token_iterator 复制到 std::vector; Visual Studio 2015 报告带有参数的“std::copy”可能不安全。

有人知道怎么解决吗?

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <regex>

int main()
{
    // String to split in words
    std::string line = "dir1\\dir2\\dir3\\dir4";

    // Split the string in words
    std::vector<std::string> to_vector;
    const std::regex ws_re("\\\\"); 
    std::copy(std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1),
              std::sregex_token_iterator(),
              std::back_insert_iterator<std::vector<std::string>>(to_vector));

    // Display the words
    std::cout << "Words: ";
    std::copy(begin(to_vector), end(to_vector), std::ostream_iterator<std::string>(std::cout, "\n"));
}

【问题讨论】:

  • 我不确定它是否相关,但你给一个需要迭代器的函数提供了一个向量。
  • 非常感谢,我会搜索如何在向量上传递插入前向迭代器。
  • 你的向量是空的。您必须使用 back_inserter。
  • 你还要更正ws_re("\\"),应该是ws_re("\\\\")。
  • 哪个编译器/版本?所示代码在 VS 2017 和 clang 5 中编译并运行良好。没有 L3 或 L4 警告。

标签: c++ visual-c++ stl


【解决方案1】:

这是我将 regex_token_iterator 提取的值存储到向量的解决方案:

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <regex>

int main()
{
    std::string s("dir1\\dir2\\dir3\\dir4");

    // Split the line in words
    const std::regex reg_exp("\\\\");
    const std::regex_token_iterator<std::string::iterator> end_tokens;
    std::regex_token_iterator<std::string::iterator> it(s.begin(), s.end(), reg_exp, -1);
    std::vector<std::string> to_vector;
    while (it != end_tokens)
    {
        to_vector.emplace_back(*it++);
    }

    // Display the content of the vector
    std::copy(begin(to_vector), 
              end(to_vector), 
              std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

【讨论】:

    【解决方案2】:

    非常旧的代码,但我也在寻找解决方案。很简单,第三个参数应该是back_inserter to vector。

    std::copy(std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1),
              std::sregex_token_iterator(),
              std::back_inserter(to_vector));
    

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2012-01-06
      • 2014-01-11
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      相关资源
      最近更新 更多