对于存储了 1000 多条 CString 数据的 vector,可以使用以下方法来对容器进行快速排序:

  1. 使用 std::sort 函数:std::sort 函数是 C++ 标准库提供的排序函数,可以对容器进行排序。使用该函数需要包含 <algorithm> 头文件。
#include <algorithm>

std::sort(container.begin(), container.end());

这将对容器中的数据进行升序排序。如果要进行降序排序,可以使用 std::greater 作为第三个参数。

std::sort(container.begin(), container.end(), std::greater<>());
  1. 使用 std::stable_sort 函数:如果希望保留相等元素之间的原始顺序,可以使用 std::stable_sort 函数。使用该函数需要包含 <algorithm> 头文件。
#include <algorithm>

std::stable_sort(container.begin(), container.end());

std::sort 函数类似,std::stable_sort 也可以通过传递 std::greater 作为第三个参数来进行降序排序。

std::stable_sort(container.begin(), container.end(), std::greater<>());
  1. 使用 std::setstd::multiset:如果要确保排序后的容器中不包含重复元素,可以使用 std::setstd::multiset 容器。这些容器会自动对元素进行排序并去重。
#include <set>

std::set<CString> sortedSet(container.begin(), container.end());

这将创建一个已排序且不包含重复元素的 std::set 容器。如果允许容器中包含重复元素,可以使用 std::multiset

  1. 使用 std::mapstd::multimap:如果需要将数据与键关联在一起进行排序,可以使用 std::mapstd::multimap 容器。这些容器会根据键对元素进行排序。
#include <map>

std::map<CString, ValueType> sortedMap;

for (const auto& item : container) {
    sortedMap[item] = value; // 将数据与键关联
}

这将创建一个已排序的 std::map 容器,其中键为 CString 类型的数据,值为 ValueType 类型的数据。如果允许容器中包含重复键,可以使用 std::multimap

以上是几种常用的排序方法,根据具体情况选择适合的方法来对容器进行排序。

快速排序 MFC 中包含中英文混合的 CString 数据的 vector 容器

原文地址: https://www.cveoy.top/t/topic/qEXX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录