Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用比较器和向量作为参数合并排序_C++_Sorting_Mergesort - Fatal编程技术网

C++ 使用比较器和向量作为参数合并排序

C++ 使用比较器和向量作为参数合并排序,c++,sorting,mergesort,C++,Sorting,Mergesort,我遇到的问题涉及到编写一个函数来使用合并排序对向量进行排序,我还需要使用一个函子。如何使用比较器/函子作为合并排序函数的参数对向量进行排序?您可以这样定义比较器运算符 struct MyLessThanFunctor { bool operator() (int i,int j) { return (i<j); } }; !!!警告std::sort不应是稳定的排序算法。 使用std::stable_sort,这在大多数情况下是作为合并排序实现的 stru

我遇到的问题涉及到编写一个函数来使用合并排序对向量进行排序,我还需要使用一个函子。如何使用比较器/函子作为合并排序函数的参数对向量进行排序?

您可以这样定义比较器运算符

struct MyLessThanFunctor
{
    bool operator() (int i,int j)
    {
    return (i<j);
    }
};

!!!警告std::sort不应是稳定的排序算法。 使用std::stable_sort,这在大多数情况下是作为合并排序实现的

struct comparator
{
    bool operator () (int i1, int i2) const { return i1 < i2; }
};

int main()
{
    vector<int> v = {0,13,76,46,53,22,4,68,68,94,38,52,83,3,5,53,67 };
    std::stable_sort (v.begin(), v.end(), comparator() );
    for (auto e : v) cout << e << " " ;
}
你可以从中寻找灵感。
struct comparator
{
    bool operator () (int i1, int i2) const { return i1 < i2; }
};

int main()
{
    vector<int> v = {0,13,76,46,53,22,4,68,68,94,38,52,83,3,5,53,67 };
    std::stable_sort (v.begin(), v.end(), comparator() );
    for (auto e : v) cout << e << " " ;
}