【问题标题】:c++ Using bubble sort to custom sort a vectorc++ 使用冒泡排序对向量进行自定义排序
【发布时间】:2015-07-02 22:24:58
【问题描述】:

我被困在尝试冒泡排序 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
}

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

【问题讨论】:

标签: c++ sorting vector


【解决方案1】:
for (auto i : o)
    std::cout << i << std::endl;

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

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

【讨论】:

    【解决方案2】:

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

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

    然后对列表进行排序就很简单了:

    vvs.sort(compare_nocase);
    

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-09-06
        • 1970-01-01
        • 2019-05-10
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 2016-07-25
        • 2016-01-01
        • 1970-01-01
        相关资源
        最近更新 更多