带字符串向量的插入排序

时间:2017-03-04 01:08:11

标签: c++ vector insertion-sort

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

这是我的代码:

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

它给了我错误:

  

无符号表达式的比较&gt; = 0始终为真

如果我使用j&gt;该功能正常工作但它完全忽略了字符串的第一行。

例如我有:

2 line1
3 line2
4 line3
5 line4
1 line5

然后它给了我:

2 line1
1 line5
3 line2
4 line3
5 line4

2 个答案:

答案 0 :(得分:3)

vector<T>::size_type by definition未签名,因此j >= 0不能为假。您应该使用vector<T>::difference_type

答案 1 :(得分:1)

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

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_type的返回类型size()混合使用是个坏主意。

相关问题