代碼在 VC++ 2010 運行正常,但在其他編譯器(如 GCC、Clang、VS 新版)報警告或錯誤:
char * judgement(int state) {
return ((0 == state) ? "左岸" : "右岸"); // 警告:返回局部字符串字面量地址類型不匹配
}
const char* judgement(int state) {
return (state == 0) ? "左岸" : "右岸";
}
#include
std::string judgement(int state) {
return (state == 0) ? "左岸" : "右岸";
}
// 調用時:cout << judgement(1); // 自動管理內存,無指針風險
char* judgement(int state) {
const char* src = (state == 0) ? "左岸" : "右岸";
char* dest = new char[strlen(src) + 1];
strcpy(dest, src);
return dest; // 調用者必須 delete[]
}
若需完整求解(狼、羊、白菜),核心是**狀態空間搜索(BFS/DFS)**:
可用 `std::queue` 實現 BFS 找最短步驟,`std::unordered_set` 去重訪問狀態。