[英]accessing c++ map
我試圖為家庭作業創建一個地圖,我在標題中聲明了它,並試圖訪問它,但我不斷出錯。 我不確定代碼有什么問題。 我將代碼實現到加載功能中,但是如果您可以幫助的話,我似乎無法使其在獲取功能中正常工作
這是頭文件
class Movies {
// data is private by default
Movie *movies;
int movieCnt;
map<string,**string> Mymap;
public:
Movies(string);
int getMovieCount() const;
const Movie * getMovie(string) const;
~Movies();
private:
void loadMovies(string);
int getMovieHash(string) const;
};
這是代碼
const Movie * Movies::getMovie(string mc) const {
if(mc.length()==0)
return NULL; // not found
else
return &(Mymap.find(mc));
}
Movies::~Movies() {delete[] movies; movies = NULL;}
void Movies::loadMovies(string fn) {
ifstream iS(fn); // technically should be c_str
string s;
getline(iS, s); // skip heading
getline(iS, s);
movieCnt=0;
while(!iS.eof()) {
Movie* m = new Movie(s);
Mymap[(m->getTitle())] = *m;
movieCnt++;
getline(iS, s);
}
iS.close();
}
您將指針星號放在錯誤的位置。 應該是這樣的:
map<string,string**> Mymap;
甚至更多的C ++
map<std::string, std::vector<std::vector<std::string>>> Mymap;
您的getMovie(string f)
函數可以通過以下方式進行改進:
const Movie Movies::getMovie(string mc) const
{
if(mc.length() > 0)
{
auto it = Mymap.find(mc);
if (it != Mymap.end())
return *it; //by value
}
else
throw std::runtime_error;
}
地圖的值應為Movie
對象。
map<string, Movie> Mymap;
請更詳細地說明您的錯誤。 怎么了? 同時,請看以下內容:
const Movie * Movies::getMovie(string mc) const {
if(mc.length()==0)
return NULL; // not found
else
return &(Mymap.find(mc));
}
作為return &(Mymap.find(mc));
您正在返回一個指向臨時對象的指針,這不太可能起作用。 嘗試返回對象本身,
const Movie Movies::getMovie(string mc) const {
if(mc.length()==0)
return NULL; // not found
else
std::map<string, string**>::const_iterator it = Mymap.find(mc);
Movie m = it*;
return m;
}
或該條目的索引,然后使用該索引從地圖中獲取它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.