在c ++中使用向量对进行排序

Rah*_*ani 1 c++

我正在使用向量对来排序我使用循环插入第一个和第二个元素的位置

vect.push_back(make_pair(count[i],arr[i]));

sort(vect.begin(),vect.end());

cout<<vect[i].second<<" ";
Run Code Online (Sandbox Code Playgroud)

如果我的计数相等,那么我想按照它们插入向量中的顺序打印第二个元素,

但它没有发生.

有人可以告诉我为什么吗?

Ola*_*che 5

std::sort

按升序对[first,last]范围内的元素进行排序.不保证保持相等元素的顺序.
1)使用operator <比较元素.

std::pair::operator<

3)如果lhs.first <rhs.first,则返回true.否则,如果rhs.first <lhs.first,则返回false.否则,如果lhs.second <rhs.second,则返回true.否则,返回false.

如此有效,排序比较count[i],如果其中两个相等,则进行比较arr[i].


如果您只想比较counts并保持相等键的原始顺序,则必须使用std::stable_sort(first, last, comp)

按升序对[first,last]范围内的元素进行排序.保证保持相等元素的顺序.

与适当的比较运算符

std::stable_sort(vect.begin(), vect.end(),
     [](const std::pair<int, T> &x, const std::pair<int, T> &y) {
        return x.first < y.first;
     }
);
Run Code Online (Sandbox Code Playgroud)