[英]Easier way to do iterator arithmetic on string copies
我有一个字符串( 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';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.