我从外部获取大量字符串并将它们连接到一个 std::string 中。然后我需要恢复这些行,所以在每个条目之后,我计划在条目结束的地方保存一个迭代器或索引。如果我已经存储了第 N 个迭代器并且在字符串中重新分配了内存(例如,在调用 append 方法时),这些迭代器仍然有效吗?
例如像这样:
#include <iostream>
#include <string>
#include <vector>
int main() {
using std::cout;
using std::endl;
using std::string;
using std::vector;
string str{};
vector<string::iterator> ends_of_notes{};
while (true) {
string tmp{};
std::cin >> tmp;
if (tmp == "exit") {
break;
}
str.append(tmp);
ends_of_notes.push_back(str.end());
}
cout << endl << "--------------" << endl;
string::iterator last_it{str.begin()};
for (auto c : ends_of_notes) {
cout << string(last_it, c) << endl;
last_it = c;
}
return 0;
}
当内存被重定位到它们所引用的字符串对象时,它们就会死掉,也就是说,在每个
str.append(tmp);. 从一开始就存储偏移量,而不是迭代器: