C++ std::map 的返回值引用



我有一个 :std::map<string,Star> galaxy,我希望下面的find_star()方法返回对此映射中值的引用。我没有收到任何编译错误,但它不会返回任何引用。

Star& Galaxy::find_star(const string& name){
try{
return galaxy.at(name);
}
catch(out_of_range a){
cerr<<"Error: "<<a.what()<<" Key not found!"<<endl;
}
}

调试器在传递"返回"行时收到未知信号。

main.cpp
int main(){
Galaxy g("stars-newline-leer.txt");
g.print();
Star s;
s=g.find_star("Caph");//Working correctly until here 
return 0;
}
Star.cpp
Star::Star() {
}
Star::Star(const Star& obj) {
this->id=obj.id;
this->ms=obj.ms;
this->prim_id=obj.prim_id;
this->bez=obj.bez;
this->sb=obj.sb;
this->x=obj.x;
this->y=obj.y;
this->z=obj.z;

}
Star::~Star() {
}
istream& operator>>(istream& is, Star& obj) {
string str = "";
int i = 0;
getline(is, str); //Id einlesen
obj.id = stoi(str);
getline(is, str); //Bezeichnung einlesen
obj.bez = str;
getline(is, str); //x-Koordinate
obj.x = stod(str);
getline(is, str); //y-Koordinate
obj.y = stod(str);
getline(is, str); //z-Koordinate
obj.z = stod(str);
getline(is, str); //Sternenbild
obj.sb = str;
getline(is, str); //Mehrfachsternsys
obj.ms = stoi(str);
getline(is, str); //Primärstern-Id
obj.prim_id = stoi(str);

return is;
}

ostream& operator<<(ostream& os, Star& obj) {
os << "ID: " << obj.id << endl;
os << "Name: " << obj.bez << endl;
os << "Koordinaten: " << obj.x;
os << ", " << obj.y;
os << ", " << obj.z << endl;
os << "Sternenbild: " << obj.sb << endl;
os << "System-Id: " << obj.ms << endl;
os << "Pimärstern: " << obj.prim_id << endl;
return os;
}
void Star::print()const {

cout << "ID: " << id << endl;
cout << "Name: " << bez << endl;
cout << "Koordinaten: " <<fixed<< x;
cout << ", " <<fixed<< y;
cout << ", " <<fixed<< z << endl;
cout << "Sternenbild: " << sb << endl;
cout << "System-Id: " << ms << endl;
cout << "Pimärstern: " << prim_id << endl;
}

对不起,我是Stackoverflow的新手,我不习惯这个。为什么我需要添加非代码来提交我的编辑。我想我只是说了一切。

正如@CoryKramer评论的那样,您的find_star函数存在设计问题。

当你得到out_of_range异常时,你不会返回Star引用,此时你可以抛出另一个异常,但它会使你的代码变得不必要的复杂......

我的建议是,您只需在主函数中使用map::find即可。

int main(){
Galaxy g("stars-newline-leer.txt");
g.print();
Star s;
map<string,Star>::iterator it = s.find("Caph");
if(it != m.end())
{
//element found;
s = it->second;
}
else
{
cout<<"Error: "<< it->first << " Key not found!" << endl;
}
return 0;
}

编辑

如果你想使用你的自定义查找函数抛出(o重新抛出异常(,你可以这样做,如下:

Star& Galaxy::find_star(const string& name){
try{
return galaxy.at(name);
}
catch(const std::out_of_range& a){
cerr<<"Error: "<<a.what()<<" Key not found!"<<endl;
throw; //an internal catch block forwards the exception to its external level
}
}

然后,您需要在main块中再次捕获异常。

int main(){
Galaxy g("stars-newline-leer.txt");
g.print();
Star s;
try{
s=g.find_star("Caph");
}
catch(const std::exception& e){
//Do something here
}
return 0;
}

最新更新