21xrx.com
2025-06-22 16:25:52 Sunday
文章检索 我的文章 写文章
如何用C++对单词进行字典顺序排序?
2023-06-23 19:06:40 深夜i     49     0
C++ 字典顺序排序 单词

在C++中,对单词进行字典顺序排序可以用许多不同的方法。下面介绍两种基本的方法。其中,第一种方法适用于C++11及以上的版本,第二种方法则适用于更早期的版本。

方法一:

使用C++11中的std::sort函数。该函数可以使用Lambda表达式对单词进行自定义排序,以实现字典顺序的排序。下面是示例代码:

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
  vector<string> words; // 定义字符串向量
  int n;
  cout<<"请输入单词数量:";
  cin>>n;
  for(int i=0; i<n; ++i){
    string word;
    cout<<"请输入第"<<i+1<<"个单词:";
    cin>>word;
    words.push_back(word); // 将单词添加到向量中
  }
  sort(words.begin(), words.end(), [](const string& a, const string& b) // 使用Lambda表达式自定义排序
    return a<b; // 按字典顺序升序排序
  );
  cout<<"排序结果为:"<<endl;
  for(const auto& word : words){ // C++11中的for each循环
    cout<<word<<endl; // 输出排序后的单词
  }
  return 0;
}

方法二:

使用C++中的字符串比较函数strcmp,结合冒泡排序算法来实现单词的字典顺序排序。下面是示例代码:

#include<iostream>
#include<cstring>
using namespace std;
int main(){
  string words[100]; // 定义字符串数组
  int n;
  cout<<"请输入单词数量:";
  cin>>n;
  for(int i=0; i<n; ++i){
    cout<<"请输入第"<<i+1<<"个单词:";
    cin>>words[i];
  }
  for(int i=0; i<n-1; ++i){
    for(int j=0; j<n-i-1; ++j){
      if(strcmp(words[j].c_str(), words[j+1].c_str())>0){ // 利用strcmp函数比较单词大小
        string temp=words[j];
        words[j]=words[j+1];
        words[j+1]=temp;
      }
    }
  }
  cout<<"排序结果为:"<<endl;
  for(int i=0; i<n; ++i){
    cout<<words[i]<<endl; // 输出排序后的单词
  }
  return 0;
}

总的来说,使用C++对单词进行字典顺序排序可以利用各种排序算法和字符串比较函数进行实现。掌握其中的基础算法和函数,有助于编写更加高效的C++代码。

  
  

评论区

    相似文章