[英]Cannot iterate through map in print() method
在循環遍歷地圖沒問題之前,我已經做過一些練習。 現在我在 class 中這樣做,我收到了我根本不理解的奇怪錯誤。 它似乎發生在 print() 方法中迭代器的實例化時。
錯誤:從 'std::mapstd::__cxx11::basic_string<char, bool>::const_iterator' {aka 'std::_Rb_tree_const_iterator<std::pair<const std::__cxx11::basic_string, bool> >' 轉換} 到非標量類型 'std::mapstd::__cxx11::basic_string<char, bool>::iterator' {aka 'std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string, bool> >'} 要求 33 | for (map<string, bool>::iterator i = jobs.begin(); i.= jobs;end(); i++) {
這是我的代碼:
class Employee {
private:
string name;
map<string, bool> jobs;
public:
Employee() {
name = "";
jobs[""] = false;
}
Employee(const Employee &other) {
cout << "Copied." << endl;
name = other.name;
jobs = other.jobs;
}
Employee(string name, string task, bool trained) {
this->name = name;
jobs[task] = trained;
}
void setTask(string task, bool trained) {
jobs[task] = trained;
}
void print() const {
for (map<string, bool>::iterator i = jobs.begin(); i != jobs.end(); i++) {
pair<string, bool> jobs = *i;
cout << name << " is trained on " << jobs.first << "? " << jobs.second << endl;
}
}
};
我promise 來之前盡量在網上找解決方法。 對不起,如果我誤解了一些非常基本的東西。
我試過使打印方法為常量或非常量,並且我已經嘗試使用 const_iterator 和 .cbegin()/.cend() 以防它對此很挑剔。 可悲的是,我還不太擅長調試。
成員function print
是一個常量成員function。也就是說在function數據成員中class是常量。 因此,您需要使用map<string, bool>::const_iterator
而不是map<string, bool>::iterator
在 for 循環中重新聲明名稱jobs
也是一個壞主意。 而且這個聲明是多余的。
你應該寫
void print() const {
for (map<string, bool>::const_iterator i = jobs.cbegin(); i != jobs.cend(); i++) {
cout << name << " is trained on " << i->first << "? " << i->second << endl;
}
}
如果您的編譯器支持 C++ 17 那么您可以通過以下方式使用基於范圍的 for 循環
void print() const {
for ( const auto &[first, second] : jobs ) {
cout << name << " is trained on " << first << "? " << second << endl;
}
}
您的print
成員 function 被聲明為const
,因此在其中發生的 class 的數據成員的所有出現/使用也將被視為const
。
因此,對jobs.begin()
和jobs.end()
的調用將調用這些函數的const
重載,這些函數的返回類型為const_iterator
。 因此,要解決您的問題,請將i
設為const_iterator
:
void print() const {
for (map<string, bool>::const_iterator i = jobs.begin(); i != jobs.end(); i++) {
pair<string, bool> localjob = *i; // Avoid "shadowing" member variable!
cout << name << " is trained on " << localjob.first << "? " << localjob.second << endl;
}
}
void print() const
最后那個const
就是說這個class方法是一個const
class方法。 它可以在這個 class 的const
實例上調用。它的意思是,就這個方法而言,它的 class 的所有成員都是const
。
map<string, bool>::iterator i = jobs.begin();
由於this
是const
, begin()
重載返回一個const_iterator
,而不是iterator
,這就是編譯錯誤的原因。
我試過使打印方法為 const 或不是 const,
但是您沒有嘗試做的是使用當前的 C++ 標准,您顯然是在使用非常非常過時的教科書來學習 C++。當前的 C++ 使所有這些變得更加容易:
void print() const {
for (auto &job:jobs)
cout << name << " is trained on " << job.first << "? " << job.second << endl;
}
這甚至不是最好的方法。 我會留給你去更新你的教科書,並了解結構化綁定,使它更容易閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.