C++ 如何将std::regex\u token\u迭代器复制到std::vector?
下面的代码无法将值从regex_token_迭代器复制到std::vector;Visual Studio 2015报告说,带有参数的“std::copy”可能不安全 有人知道怎么修吗C++ 如何将std::regex\u token\u迭代器复制到std::vector?,c++,visual-c++,stl,C++,Visual C++,Stl,下面的代码无法将值从regex_token_迭代器复制到std::vector;Visual Studio 2015报告说,带有参数的“std::copy”可能不安全 有人知道怎么修吗 #include <vector> #include <iostream> #include <algorithm> #include <iterator> #include <regex> int main() { // String to
#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_迭代器提取的值存储到向量:
#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;
}
非常旧的代码,但我也在寻找解决方案。很简单,第三个参数应该是返回向量的插入器
std::copy(std::sregex_token_iterator(line.begin(), line.end(), ws_re, -1),
std::sregex_token_iterator(),
std::back_inserter(to_vector));
我不确定它是否相关,但您给了一个需要迭代器的函数一个向量。非常感谢,我将搜索如何在向量上传递插入前向迭代器。您的向量为空。您必须使用反向插入器。您还必须更正ws\u re\\,它应该是ws\u re\\。哪个编译器/版本?如图所示的代码在VS2017和clang 5中编译并运行良好。没有L3或L4警告。