[英]std::map: overloading the operator< with a parameter other than the key's class
這是我的第一篇文章-很抱歉,如果我弄亂了網站的任何約定。 請指出我犯的任何錯誤,以便我可以解決/不重復。
我希望能夠通過將std::string
放在方括號之間來使用std::map
的operator[]
-即使map
的鍵不是std::string
。
這是代碼
class myKey
{
public:
std::string _name;
myKey(std::string name)
{
_name = name;
}
bool operator<(const myKey& other) const
{
if (this->_name < other._name)
{
return true;
}
else
{
return false;
}
}
};
int main()
{
std::map<myKey, int> map;
myKey temp("keyString");
map[temp] = 1;
std::cout << map[temp];
system("pause");
return 0;
}
到目前為止,它可以正常工作-但如您所見,操作員唯一使用的是該類的std::string _name
字段。 我僅通過輸入像這樣的字符串就無法在地圖中查找值: map["keyString"]
。
我嘗試重載myKey
的operator<
,但沒有幫助。
bool operator<(const std::string name) const
{
if (this->_name < name)
{
return true;
}
else
{
return false;
}
}
如何做呢?
""
是字符串文字,類型為const char*
。 當您執行map["keyString"]
時,它不起作用的原因是因為"keyString"
首先轉換為std::string
,然后才能作為鍵傳遞。
但是因為必須先將其轉換(轉換為std::string
),所以這是非法的。
您可以只添加一個接受const char*
的構造const char*
:
myKey(const char* name) : _name{ name } {}
如果您不想添加新的構造函數,則可以使用std::string_literals::operator""s
。
using namespace std::string_literals;
//Note 's' after "", this means that "keyString" is of type std::string, not const char*
map["keyString"s] = 1;
感謝rakete-您指出了問題所在。 但是有一個更簡單的解決方案:步驟:
使用采用所需參數的方法重載operator<
(在這種情況下,為std::string
。請確保您使用的是函數的正確簽名)簽出myoperator operator<
函數
當嘗試使用operator[]
在地圖中獲取值時,請確保在括號之間輸入正確的值(這是我做錯的,請輸入如下string literal
map["keyString"]
而不是輸入std::string
像這樣map[std::string("keyString")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.