使用boost :: range :: sort

Olu*_*ide 2 c++ sorting boost

我很欣赏一个如何使用的例子boost::sort(我正在尝试对一个定制的对象容器进行排序,因此无法使用std::sort).文档中的示例非常少; 此外,我找不到任何有关如何创建的信息RandomAccessRange.

seh*_*ehe 5

您不创建RandomAccessRange.

范围.它应该可以使用默认的方法从获得随机访问迭代器(std::begin(r),boost::begin(r)r.begin()cbegin)

auto r1 = "I am a range of char";
auto r2 = "me too!";
auto r3[] = { r1, r2 }; // a range of const char*
auto r4 = std::vector<std::string> { r1, r2 }; // two strings
auto r5 = std::list<std::string> { begin(r3), end(r3) }; // idem
Run Code Online (Sandbox Code Playgroud)

现在无论你如何获得范围,你都可以使用

std::sort(begin(r), end(r));
Run Code Online (Sandbox Code Playgroud)

或使用Boost的范围版本:

boost::sort(r);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,boost :: sort只是完全相同的语法糖

完整示例:请注意使用什么排序谓词的细微之处(参见std::less<>那里)

Live On Coliru

#include <boost/range/algorithm.hpp>
#include <vector>
#include <list>

using namespace boost;

int main() {
    auto r1 = "I am a range of char";
    auto r2 = "me too!";
    const char* r3[] = { r1, r2 }; // a range of const char*
    auto r4 = std::vector<std::string> { r1, r2 }; // two strings
    auto r5 = std::list<std::string> { begin(r3), end(r3) }; // idem

    std::sort(begin(r3), end(r3)); // sorts by pointer value
    boost::sort(r3);               // sorts by pointer value

    std::sort(begin(r3), end(r3), std::less<std::string>()); // sorts the strings
    boost::sort(r3, std::less<std::string>());               // sorts the strings
    //// but this won't compile:
    // boost::sort(r5); // not random traversal category
}
Run Code Online (Sandbox Code Playgroud)