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

C++ 对字符串副本执行迭代器算术的更简单方法,c++,string,iterator,C++,String,Iterator,我有一个字符串(格式)的副本(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.i

我有一个字符串(
格式
)的副本(
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';
}
intmain()
{
std::string right=“插入”;
std::string format=“some%text”;
auto pos=format_u.find('%',0);//pos是std::string::size_类型(不是迭代器)
std::string result=格式;
if(pos!=std::string::npos)
结果:更换(位置1,右侧);

STU::CUT @ PIOTR,它是STD的返回值:查找。上面的代码只是用右替换子字符串。迭代器可以在内部使用指针,这两个字符串具有不同的内存位置。可能考虑使用字符串中的索引位置而不是迭代器。字符串的代码> find *()
函数可以处理索引位置。@Piotr std::find(format_u.begin(),format_u.end(),“%”)@Piotr yes i do result=format_u在代码开头已经给出了答案(使用位置,而不是迭代器),但我想知道为什么在创建副本后必须对原始字符串执行查找操作,然后将结果重新用于副本。这听起来很像程序设计本身的缺陷。