如何将std :: regex_token_iterator复制到std :: vector?

时间:2017-12-06 18:44:15

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

以下代码无法将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"));
}

2 个答案:

答案 0 :(得分:0)

这里是我将regex_token_iterator提取的值存储到vector:

的解决方案
#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;
}

答案 1 :(得分:0)

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

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