Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++字符串排序

作者:木の兮   发布日期:2026-03-30   浏览:69

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    // 创建一个字符串向量
    vector<string> words = {"banana", "apple", "orange", "grape", "cherry"};

    // 使用sort函数对字符串向量进行排序
    sort(words.begin(), words.end());

    // 输出排序后的结果
    cout << "排序后的字符串:" << endl;
    for (const auto& word : words) {
        cout << word << endl;
    }

    return 0;
}

解释说明:

  1. 包含头文件#include <iostream>#include <vector>#include <algorithm>#include <string> 分别用于输入输出流、向量容器、算法库和字符串处理。
  2. 命名空间using namespace std; 简化了标准库的调用,避免每次使用标准库元素时都要加上 std:: 前缀。
  3. 创建字符串向量vector<string> words 定义了一个字符串类型的向量,并初始化了一些水果名称。
  4. 排序sort(words.begin(), words.end()); 使用 C++ 标准库中的 sort 函数对向量中的字符串进行字典序排序。
  5. 输出结果:通过 for 循环遍历排序后的向量,并逐个输出每个字符串。

这样可以实现对一组字符串的简单排序。

上一篇:c++swap函数

下一篇:c++ else if

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

c++ string类

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站