Edit: 请注意史蒂夫汤森的解决方案 https://stackoverflow.com/questions/3844909/sorting-a-setstring-on-the-basis-of-length/3846129#3846129实际上就是您要搜索的那个,因为他将我在下面编写为 C++03 代码的内容内联为 C++0x Lambda。
另一种解决方案是自定义std::set
订购功能:
The std::set
已经订购了...
The std::set
有自己的顺序,一旦构建完成,您就不应该更改它。所以,下面的代码:
int main(int argc, char* argv[])
{
std::set<std::string> aSet ;
aSet.insert("aaaaa") ;
aSet.insert("bbbbb") ;
aSet.insert("ccccccc") ;
aSet.insert("ddddddd") ;
aSet.insert("e") ;
aSet.insert("f") ;
outputSet(aSet) ;
return 0 ;
}
将输出以下结果:
- aaaaa
- bbbbb
- ccccccc
- ddddddd
- e
- f
...但是你可以自定义它的排序功能
现在,如果您愿意,您可以使用自己的比较函数来自定义您的集合:
struct MyStringLengthCompare
{
bool operator () (const std::string & p_lhs, const std::string & p_rhs)
{
const size_t lhsLength = p_lhs.length() ;
const size_t rhsLength = p_rhs.length() ;
if(lhsLength == rhsLength)
{
return (p_lhs < p_rhs) ; // when two strings have the same
// length, defaults to the normal
// string comparison
}
return (lhsLength < rhsLength) ; // compares with the length
}
} ;
在这个比较函子中,我确实处理了“相同长度但不同内容意味着不同字符串”的情况,因为我相信(也许是错误的)原始程序中的行为是一个错误。要在原始程序中编码行为,请删除if
阻止代码。
现在,您构建该集合:
int main(int argc, char* argv[])
{
std::set<std::string, MyStringLengthCompare> aSet ;
aSet.insert("aaaaa") ;
aSet.insert("bbbbb") ;
aSet.insert("ccccccc") ;
aSet.insert("ddddddd") ;
aSet.insert("e") ;
aSet.insert("f") ;
outputSet(aSet) ;
return 0 ;
}
该集合现在将使用函子MyStringLengthCompare
订购其商品,因此,此代码将输出:
- e
- f
- aaaaa
- bbbbb
- ccccccc
- ddddddd
但要注意顺序错误!
当您创建自己的排序函数时,必须遵循以下规则:
如果 (lhs
如果由于某种原因你的订购功能不尊重它,你的手上就会有一套破损的产品。