如何使用sregex_token_iterator对象初始化向量
How to initialize a vector using sregex_token_iterator objects
在此代码中,我将逗号分隔的刺痛转换为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);
如果需要整数,可以手动转换为int
s 的向量,或者编写一个自定义迭代器适配器,将字符串即时转换为整数。
相关文章:
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 对象初始化中是否允许指向此成员的指针?
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么两种不同的对象初始化方式给出不同的输出
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- afxmem.cpp中的对象初始化差异
- 删除通过取消引用新对象初始化的对象
- 如何使用sregex_token_iterator对象初始化向量
- 关于默认构造函数,对象初始化/使用C++ OOP
- C++ 基元类型初始化与对象初始化
- 哪个函数负责C++全局范围内的类对象初始化?
- C++中构造函数的对象初始化出现问题
- 如何修复模板 BST 类的对象初始化
- 无法在 QML/C++ 中使用绑定对象初始化 UI
- 为什么参数可以在对象初始化时通过赋值运算符传递给构造函数?
- 类对象初始化的二维向量
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 对象初始化
- 类对象初始化
- 使用从另一个类继承的类的对象初始化成员对象