0

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.

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).

AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66
  • What is `ranges::span`? – eerorika Mar 05 '21 at 21:06
  • @eerorika It's from ranges v3 - I think it can work with `std::span` as well. But unfortunately it doesn't and ranges are not supported in any STD library I know so you are stuck with `ranges::span` if you decide to follow. – AnArrayOfFunctions Mar 05 '21 at 21:08

1 Answers1

0

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • It's critical to be able to change the size - I will be most likely adding characters though not removing ones, if that makes it any easier. – AnArrayOfFunctions Mar 05 '21 at 21:28
  • @AnArrayOfFunctions Probably not any easier. I suspect you'll need to design a class of your own to do this. – eerorika Mar 05 '21 at 21:32