【问题标题】:Insertion sort with a string vector使用字符串向量进行插入排序
【发布时间】:2017-03-04 01:08:10
【问题描述】:

我正在尝试使用插入排序对字符串向量进行排序。

这是我的代码:

void insertionsort(std::vector<std::string> &strings) 
{
    typedef std::vector<std::string>::size_type size_type;
    for(size_type i = 0;i < strings.size(); i++) 
    {
        std::string const tmp = strings[i];
        size_type j = i - 1;
        while(j >= 0 && tmp < strings[j]) //this is the problem
        {
            strings[j + 1]= strings[j];
            j--;

        }
        strings[j + 1]=tmp;
    }
}

它给了我错误:

无符号表达式的比较 >= 0 始终为真

如果我使用 j > 0,该函数可以正常工作。但它完全忽略了字符串的第一行。

如果我有:

2 line1
3 line2
4 line3
5 line4
1 line5

然后它给了我:

2 line1
1 line5
3 line2
4 line3
5 line4

【问题讨论】:

  • 使用有符号类型。 (并非无可争议,但标准委员会的几位杰出成员与我一起参与其中)。

标签: c++ vector insertion-sort


【解决方案1】:

vector&lt;T&gt;::size_typeby definition 无符号,所以 j &gt;= 0 不能为假。你应该使用vector&lt;T&gt;::difference_type

【讨论】:

    【解决方案2】:

    类模板std::vector 的类型别名size_type 始终为非负整数类型。所以抑郁症

    j >= 0
    

    总是正确的。

    你需要在函数实现中做一些小的改动。很明显,只包含一个元素的向量总是被排序的。所以你应该从索引等于 1 开始外循环。

    你来了

    #include <iostream>
    #include <vector>
    #include <string>
    
    void insertionSort( std::vector<std::string> &strings ) 
    {
        typedef std::vector<std::string>::size_type size_type;
    
        for ( size_type i = 1; i < strings.size(); ++i ) 
        {
            std::string tmp = strings[i];
    
            size_type j = i;
    
            for ( ; j !=  0 && tmp < strings[j-1]; --j )
            {
                strings[j] = strings[j-1];
            }
    
            if ( j != i ) strings[j] = tmp;
        }
    }
    
    int main() 
    {
        std::vector<std::string> v = { "E", "D", "C", "B", "A" };
    
        for ( const auto &s : v ) std::cout << s << ' ';
        std::cout << std::endl;
    
        insertionSort( v );
    
        for ( const auto &s : v ) std::cout << s << ' ';
        std::cout << std::endl;
    }   
    

    程序输出是

    E D C B A 
    A B C D E 
    

    注意这个添加的语句

    if ( j != i ) strings[j] = tmp;
    

    如果一个元素已经在向量中占据了所需的位置,那么将它分配给它自己是没有意义的。这使得函数更高效。

    difference_type 类型与成员函数size() 的返回类型size_type 混合是一个坏主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 2018-08-17
      • 1970-01-01
      • 2021-12-07
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多