c++使用冒泡排序对向量进行自定义排序

c++ Using bubble sort to custom sort a vector

本文关键字:自定义 排序 向量 冒泡排序 c++      更新时间:2023-10-16

我一直在尝试对vector<vector<string>> vvs进行冒泡排序如果运行类似的for循环

for ( auto x : vvs )它包含一条类似的线路

if ( x.at(pos) == (*need next x position*).at(pos) {
    //perform sort and swap if needed
}

是否可以获得基于范围的循环的下一个位置?

for (auto i : o)
    std::cout << i << std::endl;

基于范围的for循环仅用于对数组或向量中的每个元素进行排序,用于传统的循环

for (unsigned i = 2; i != 10; ++i)
      std::cout << arr[i] << std::endl; 

不用矢量,只需使用std::list,它比手动操作简单快捷得多,

std::list<std::string> vvs;

然后订购列表就像:一样简单

vvs.sort(compare_nocase);

按字母顺序对列表进行排序,不区分大小写;

或者,定义一个类似的基于迭代器的Bubble Sort

template <class Iterator>
inline void BubbleSort(Iterator begin, Iterator end) {
    for (Iterator i = begin; i != end; ++i)
        for (Iterator j = begin; j < i; ++j)
            if (*i < *j)
                std::iter_swap(i, j);
}

应用于矢量

for (auto & v : vvs) {
    BubbleSort(v.begin(), v.end());
}