繁体   English   中英

C ++使用冒泡排序自定义对向量排序

[英]c++ Using bubble sort to custom sort a vector

我陷入尝试冒泡排序vector<vector<string>> vvs如果运行像

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循环的自定义循环

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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM