对字符串副本执行迭代器运算的更简单方法

Easier way to do iterator arithmetic on string copies

本文关键字:更简单 方法 运算 迭代器 字符串 副本 执行      更新时间:2023-10-16

我有一个字符串(format_)的副本(result),然后在原始字符串上使用std::find,但我不能在字符串副本上使用由此获得的迭代器。这导致了一些繁琐的代码。例如:

std::string result = format_;
auto it = std::find(format_.begin(), format_.end(), '%');
auto diff = it - format_.begin();
auto pos_it = result.begin() + diff;
result.insert(result.erase(pos_it, pos_it + 2), right.begin(), right.end());

在这里,如果我试图将它用作迭代器,而不仅仅是用于数学,我会遇到分段错误。如果两个字符串相同,为什么不能"共享"迭代器?

不能在字符串之间共享迭代器(即使它们相同),因为它们占用单独的内存位置,并且迭代器可能在内部使用内存指针来直接访问字符串的元素。

作为一种替代方案,您可以在字符串中使用索引位置偏移。

也许是这样的:

int main()
{
    std::string right = "INSERT";
    std::string format_ = "some % text";
    auto pos = format_.find('%', 0); // pos is std::string::size_type (not iterator)
    std::string result = format_;
    if(pos != std::string::npos)
        result.replace(pos, 1, right);
    std::cout << result << 'n';
}