如何使用sregex_token_iterator对象初始化向量

How to initialize a vector using sregex_token_iterator objects

本文关键字:对象 初始化 向量 iterator token 何使用 sregex      更新时间:2023-10-16

在此代码中,我将逗号分隔的刺痛转换为sregex_token_iterator对象。

但是当我尝试使用sregex_token_iterator对象初始化向量时,我得到静态断言失败:结果类型必须可从输入范围错误的值类型构造。

#include <iostream>
#include <vector>
#include <regex>
using namespace std;
int main() {
string uinput = "1,2, 3";
const regex regex(R"(s*,s*)");
sregex_token_iterator beg(uinput.begin(), uinput.end(), regex, -1), end;
for_each(beg, end, [](auto& token) { cout << token << 'n'; }); // just for checks
vector<int> v(beg, end); // Gives this error:
// static assertion failed: result type must be constructible from value type of input range
}

如何使用sregex_token_iterator对象正确初始化向量? 谢谢。

std::sregex_token_iterator的值类型是std::sub_match。这不能隐式转换为int,因为没有相应的强制转换运算符。

但是,std::sub_match有一个字符串转换运算符。因此,您可以通过以下方式构造std::vector<std::string>

std::vector<std::string> v(beg, end);

如果需要整数,可以手动转换为ints 的向量,或者编写一个自定义迭代器适配器,将字符串即时转换为整数。