字符串作为映射中的键,自定义比较功能
string as key in map, custom the compare function
我在地图中使用字符串作为键值并尝试自定义比较函数。当我通过比较字符串的长度来自定义比较函数时,映射无法区分具有相同大小的不同字符串。代码如下:
class Solution {
public:
int findLUSlength(vector<string>& strs) {
if(strs.size() < 2) return -1;
auto cmpByStringLength = [](const string &s1, const string &s2)->bool
{
return s1.size() < s2.size();
};
map<string, int, decltype(cmpByStringLength)> mpstringcount(cmpByStringLength);
for(int i = 0; i < strs.size(); i++)
mpstringcount[strs[i]]++;
for(auto itmp = mpstringcount.begin(); itmp != mpstringcount.end(); itmp++)
{
cout << "itmp->first: " << itmp->first << endl;
}
return -1;
}
};
如果我输入的字符串是["aba","cdc","eae","abcd"]
,代码只会输出:"abcd"
和"aba"
。
the map fail to tell the different strings with same size.
请注意,提供给 std::map 的比较器不仅用于排序,还用于相等性检查。
Everywhere the standard library uses the Compare concept, uniqueness
is determined by using the equivalence relation. In imprecise terms,
two objects a and b are considered equivalent (not unique) if neither
compares less than the other: !comp(a, b) && !comp(b, a)
.
和std::map存储具有唯一键的元素。您的比较函子根据长度比较 string
s,然后对于这些具有相同长度的 string
s 将只存储其中一个。从一个map<string, int, decltype(cmpByStringLength)>
、"aba"
、"cdc"
、"eae"
的角度来看,都是一样的string
。
我在地图中使用字符串作为键值并尝试自定义比较函数。当我通过比较字符串的长度来自定义比较函数时,映射无法区分具有相同大小的不同字符串。代码如下:
class Solution {
public:
int findLUSlength(vector<string>& strs) {
if(strs.size() < 2) return -1;
auto cmpByStringLength = [](const string &s1, const string &s2)->bool
{
return s1.size() < s2.size();
};
map<string, int, decltype(cmpByStringLength)> mpstringcount(cmpByStringLength);
for(int i = 0; i < strs.size(); i++)
mpstringcount[strs[i]]++;
for(auto itmp = mpstringcount.begin(); itmp != mpstringcount.end(); itmp++)
{
cout << "itmp->first: " << itmp->first << endl;
}
return -1;
}
};
如果我输入的字符串是["aba","cdc","eae","abcd"]
,代码只会输出:"abcd"
和"aba"
。
the map fail to tell the different strings with same size.
请注意,提供给 std::map 的比较器不仅用于排序,还用于相等性检查。
Everywhere the standard library uses the Compare concept, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent (not unique) if neither compares less than the other:
!comp(a, b) && !comp(b, a)
.
和std::map存储具有唯一键的元素。您的比较函子根据长度比较 string
s,然后对于这些具有相同长度的 string
s 将只存储其中一个。从一个map<string, int, decltype(cmpByStringLength)>
、"aba"
、"cdc"
、"eae"
的角度来看,都是一样的string
。