简体   繁体   English

在字符串副本上执行迭代器算术的更简单方法

[英]Easier way to do iterator arithmetic on string copies

I have a copy ( result ) of a string ( format_ ) and then I use std::find on the original string, but I cannot use iterators obtained by this on the string copy. 我有一个字符串( format_ )的副本( result ),然后在原始字符串上使用std::find ,但是我不能在字符串副本上使用由此获得的迭代器。 This results in some cumbersome code. 这导致一些麻烦的代码。 for example: 例如:

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());

Here if I attempt to use it as an iterator rather than just for math I will get segmentation fault. 在这里,如果我尝试将其用作迭代器而不是仅用于数学运算,则会遇到分段错误。 If two strings are identical, why cannot you "share" iterators? 如果两个字符串相同,为什么不能“共享”迭代器?

You can not share iterators between strings (even if they are identical) because they occupy separate memory locations and iterators may use memory pointers internally to access the strings' elements directly. 您不能在字符串之间共享迭代器(即使它们相同),因为它们占用单独的内存位置,并且迭代器可能在内部使用内存指针直接访问字符串的元素。

As an alternative you can use index position offsets into the strings. 或者,您可以在字符串中使用索引位置偏移量。

Perhaps something like this: 也许是这样的:

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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM