📌  相关文章
📜  C++程序按字典顺序(字典顺序)对元素进行排序

📅  最后修改于: 2020-09-25 06:17:58             🧑  作者: Mango

该程序按字典顺序(字典顺序)对10个字符串 (由用户输入)进行排序。

该程序从用户那里提取10个单词,并按字典顺序对其进行排序。

示例:按字典顺序对单词排序

#include 
using namespace std;

int main()
{
    string str[10], temp;

    cout << "Enter 10 words: " << endl;
    for(int i = 0; i < 10; ++i)
    {
      getline(cin, str[i]);
    }

    for(int i = 0; i < 9; ++i)
       for( int j = i+1; j < 10; ++j)
       {
          if(str[i] > str[j])
          {
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
          }
    }

    cout << "In lexicographical order: " << endl;

    for(int i = 0; i < 10; ++i)
    {
       cout << str[i] << endl;
    }
    return 0;
}

输出

Enter 10 words: 
C 
C++
Java
Python
Perl
R
Matlab
Ruby
JavaScript
PHP
In lexicographical order: 
C
C++
Java
JavaScript
Matlab
PHP
Perl
Python
R
Ruby

为了解决该程序,创建了一个字符串对象str[10]的数组。

用户输入的10个单词存储在此数组中。

然后,使用嵌套的for循环按字典顺序对数组排序,并在屏幕上显示。