C++ 程序按字典顺序对元素排序
字典顺序表示单词在列表中的排列方式,基于其字母表的字母顺序。例如此处 −
List of words: Harry Adam Sam Lexicographical order of words: Adam Harry Sam
一个按字典顺序对元素排序的程序如下 −
示例
#include <iostream>
using namespace std;
int main() {
int i,j;
string s[5], temp;
cout<<"Enter the elements..."<<endl;
for(i = 0; i < 5; ++i)
getline(cin, s[i]);
for(i = 0; i < 4; ++i)
for(j = i+1; j < 5; ++j) {
if(s[i] > s[j]) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
cout << "The elements in lexicographical order are... " << endl;
for(int i = 0; i < 5; ++i)
cout << s[i] << endl;
return 0;
}输出
上述程序的输出如下 −
Enter the elements… Orange Grapes Mango Apple Guava The elements in lexicographical order are... Apple Grapes Guava Mango Orange
在上述程序中,定义了字符串 s[],元素由用户输入。如下所示 −
string s[5], temp; cout<<"Enter the elements..."<<endl; for(i = 0; i < 5; ++i) getline(cin, s[i]);
使用嵌套 for 循环对元素按字母顺序进行排列。代码片段如下所示 −
for(i = 0; i < 4; ++i)
for(j = i+1; j < 5; ++j) {
if(s[i] > s[j]) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}最后,按字典顺序显示所有元素。如下所示 −
cout << "The elements in lexicographical order are... " << endl; for(int i = 0; i < 5; ++i) cout << s[i] << endl;
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP