如何将std :: Regex_token_iterator复制到std :: vector

How to copy std::regex_token_iterator to a std::vector?

本文关键字:std vector 复制 iterator Regex token      更新时间:2023-10-16

以下代码无法将值从regex_token_iterator复制到std :: vector;Visual Studio 2015报告说,参数的" std ::复制"可能不安全。

有人知道如何修复它吗?

#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"));
}

在这里我的解决方案将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;
}

非常古老的代码,但是当我也在寻找解决方案时。这是非常简单的第三个参数应为back_inserter到向量。

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