基于长度对集合<string>进行排序

Tes*_*ter 6 c++ lambda stl set c++11

我的问题与有关.

我希望借助lambda表达式作为谓词来执行sort()操作set.

我的代码是

#include <set>
#include <string>
#include <iostream>
#include <algorithm>
int main() {
  using namespace std;
  string s = "abc";
  set<string> results;
  do {
    for (int n = 1; n <= s.size(); ++n) {
      results.insert(s.substr(0, n));
    }
  } while (next_permutation(s.begin(), s.end()));

  sort (results.begin(),results.end());[](string a, string b)->bool{

              size_t alength = a.length();
              size_t blength = b.length();
              return (alength < blength);
  });
  for (set<string>::const_iterator x = results.begin(); x != results.end(); ++x) {
    cout << *x << '\n';
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但错误的数量和类型是如此复杂,我无法理解如何解决它们.有人能告诉我这段代码有什么问题.

pae*_*bal 8

编辑:请注意,Steve Townsend的解决方案实际上是您正在搜索的解决方案,因为他将C++ 0x Lambda内联为C++ 03代码.

另一种解决方案是定制std::set订购功能:

std::set已经下令...

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 ;
}
Run Code Online (Sandbox Code Playgroud)

将输出以下结果:

 - aaaaa
 - bbbbb
 - ccccccc
 - ddddddd
 - e
 - f
Run Code Online (Sandbox Code Playgroud)

...但您可以自定义其订购功能

现在,如果需要,您可以使用自己的比较功能自定义您的设置:

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
    }
} ;
Run Code Online (Sandbox Code Playgroud)

在这个比较仿函数中,我确实处理了"相同长度但不同内容意味着不同字符串"的情况,因为我相信(可能错误地)原始程序中的行为是错误的.要在原始程序中编码行为,请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 ;
}
Run Code Online (Sandbox Code Playgroud)

该集合现在将使用仿函数MyStringLengthCompare对其项目进行排序,因此,此代码将输出:

 - e
 - f
 - aaaaa
 - bbbbb
 - ccccccc
 - ddddddd
Run Code Online (Sandbox Code Playgroud)

但要注意订购错误!

创建自己的订购功能时,必须遵循以下规则:

如果(lhs <rhs)为真,则返回true,否则返回false

如果由于某种原因你的订购功能不尊重它,你的手上就会有一个破损的设置.


Pot*_*ter 5

std::sort重新排列您给出的序列的元素.序列的排列set是固定的,所以你可以拥有的唯一迭代器是const迭代器.

您需要先复制resultsvectordeque(或此类).

vector sortable_results( results.begin(), results.end() );
Run Code Online (Sandbox Code Playgroud)