是否可以构造字符串中部分的可修改视图? [英] Is it possible to construct a modifiable view of portion in a string?
问题描述
我有一个匹配表,其中包含数组的一部分(在回调中)的开始和结束索引-我将该数组包装到字符串向量中-现在最近我确实需要修改字符串的原始部分./p>
I have a match table with start and end indices of portions, in array (in a callback) - I wrap that array into vector of strings - now recently I did have the need to modify the original portions of the string.
struct regexcontext {
std::vector<std::optional<std::string>> matches;
std::string subject;
};
int buildmatchvector(size_t(*offset_vector)[2], int max, regexcontext* pcontext) {
pcontext->matches.clear();
ranges::transform(ranges::span{ offset_vector, max }, std::back_inserter(pcontext->matches), [&](const auto& refarr) {
return refarr[0] == -1 ? std::optional<std::string> {} : std::optional<std::string>{ pcontext->subject.substr(refarr[0], refarr[1] - refarr[0]) };
});
return 0;
}
是否可以通过修改匹配向量来更改上述定义,我也将修改主题字符串.
Is it possible to change the above definition in a way that by modifying the match vector I will modify the subject string as well.
我听说过字符串视图,但也听说不能用可变大小的字符串修改它.
I've heard of string view but I've also heard it can't be modified with a variable sized string.
请注意,我使用的是 ranges-v3
,这是目前唯一实现标准范围的库,另外还使用了非标准的 ranges :: span
msvc(由于某些原因 std :: span
在该处不起作用).
Note I'm using ranges-v3
which is the only library that implements standard ranges at the moment plus the nonstandard ranges::span
which allows me to compile on msvc (since std::span
doesn't work there for some reason).
推荐答案
只要您只需要将字符更改为其他字符,而无需添加或删除字符,则可以使用 span
.支持添加或删除将更加复杂,我认为标准库中没有任何简单的解决方案.示例:
As long as you only need to change characters to others, but not add or remove characters, then you could use a vector of span
. Supporting addition or removal would be much more complicated and I don't think there's any simple solution in the standard library. Example:
return refarr[0] == -1
? span<char> {}
: span<char> {
&pcontext->subject[refarr[0]],
refarr[1] - refarr[0]
};
请注意,对指向的字符串进行的任何无效操作都会使这些范围无效,因此将字符串设为私有是个好主意.
Note that any invalidating operation on the pointed string would invalidate these spans, so it would be a good idea to make the string private.
这篇关于是否可以构造字符串中部分的可修改视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!