我正在嘗試遍歷地圖中的所有鍵。我有這個代碼:
map<string, array<string, 3>> dat;
array<string, 3> dt({ "var","TEXT","" });
dat["atest"] = dt;
array<string, 3> at({ "var","DATA","" });
dat["testplusalot"] = at;
array<string, 3> t({ "var","NONE","" });
dat["testalot"] = t;
for (const auto& p : dat) {
cout << p.first << endl;
}
我想讓它說
testplusalot
testalot
atest
但我明白了
atest
testalot
testplusalot
我怎么能這樣做。
uj5u.com熱心網友回復:
由于您想按長度對鍵進行排序,然后如果長度相同,則按字母順序排序(最簡單的后備排序),則可以執行以下操作:
#include <map>
#include <string>
#include <array>
#include <iostream>
// Create a type that describes the sort order
struct strCompare
{
bool operator()(const std::string& Left, const std::string& Right) const
{
// Sort by length
if ( Left.length() != Right.length() )
return Left.length() > Right.length();
// Fall back to string < ordering
return Left < Right;
}
};
int main()
{
std::map<std::string, std::array<std::string, 3>, strCompare> dat;
std::array<std::string, 3> dt({ "var","TEXT","" });
dat["atest"] = dt;
std::array<std::string, 3> at({ "var","DATA","" });
dat["testplusalot"] = at;
std::array<std::string, 3> t({ "var","NONE","" });
dat["testalot"] = t;
std::array<std::string, 3> t2({ "var","NONE","" });
dat["testblot"] = t2;
for (const auto& p : dat) {
std::cout << p.first << std::endl;
}
}
輸出:
testplusalot
testalot
testblot
atest
strCompare是一種具有<確定鍵排序標準的多載型別。
然后創建需要您在
#include <map>
#include <array>
#include <string>
#include <iostream>
int main()
{
std::map<std::string, std::array<std::string, 3>, std::greater<std::string>> dat;
std::array<std::string, 3> dt({ "var","TEXT","" });
dat["test"] = dt;
std::array<std::string, 3> at({ "var","DATA","" });
dat["testplusalot"] = at;
std::array<std::string, 3> t({ "var","NONE","" });
dat["testalot"] = t;
for (const auto& p : dat) {
std::cout << p.first << std::endl;
}
return 0;
}
輸出將是:
testplusalot
testalot
test
PS,這段代碼也會回傳
testplusalot
testalot
atest
對于 [testplusalot, testalot, atest] 鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410789.html
標籤:
