我目前正在从事一个关于浏览器历史的项目。我正在使用 STL 的列表实现来跟踪不同的网站。我已经解决了大部分问题,但我似乎无法解决错误:
Screenshot; cannot dereference end list iterator.
网站数据包含在我的网站对象中。
class BrowserHistory {
private:
list<Site> history;
list<Site>::iterator current = history.begin();
public:
void visitSite(string, size_t)
void backButton();
void forwardButton();
void readFile(string);
};
void BrowserHistory::visitSite(string x, size_t y)
{
while (current != history.end()) {
history.pop_back();
}
history.push_back({ x, y });
current++;
}
void BrowserHistory::backButton()
{
if (current != history.begin())
current--;
}
void BrowserHistory::forwardButton()
{
if (current != history.end())
current++;
}
void BrowserHistory::readFile(string filename)
{
string action, url;
size_t pageSize;
ifstream dataIn;
dataIn.open(filename);
while (!dataIn.eof()) {
dataIn >> action;
if (action == "visit") {
dataIn >> url >> pageSize;
history.push_back({ url, pageSize });
current++;
}
if (action == "back") {
current--;
}
if (action == "forward") {
current++;
}
}
dataIn.close();
}
谁能给我解释一下这是怎么回事?在此先感谢您的帮助。
最佳答案
当你初始化current
时,列表是空的。
向列表中添加元素不会突然使其成为有效的迭代器,即使它与 end
不同。
您似乎认为迭代器与指针非常相似,但事实并非如此。
迭代器用于迭代,应被视为暂时的,不应存储以备后用。
使用 vector ,并为 current
使用索引而不是迭代器。
此外,我会将“按钮”功能(按钮 历史关心什么?)重命名为“goBack”和“goForward”,并在阅读时使用您的实际界面:
void BrowserHistory::readFile(string filename)
{
ifstream dataIn(filename);
string action;
while (dataIn >> action) {
if (action == "visit") {
string url;
size_t pageSize;
if (dataIn >> url >> pageSize) {
visitSite(url, pageSize);
}
else {
// Handle error
}
}
else if (action == "back") {
goBack();
}
else if (action == "forward") {
goForward();
}
else {
// Handle error
}
}
}
关于c++ - 无法取消引用结束列表迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58426948/