Skip to content

Latest commit

 

History

History
87 lines (68 loc) · 1.63 KB

File metadata and controls

87 lines (68 loc) · 1.63 KB

C++ 程序:按字典顺序对元素进行排序

原文: https://www.programiz.com/cpp-programming/examples/lexicographical-order

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

要理解此示例,您应该了解以下 C++ 编程主题:


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


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

#include <iostream>
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循环按字典顺序对数组排序,并在屏幕上显示。