要让自定义类型支持std::sort和std::map,需重载operator<以定义严格弱序比较规则,如Book类中按价格升序、年份降序排列,从而使标准库算法和容器能正确处理该类型。

当C++的自定义类型(比如你精心设计的类或结构体)需要与标准库的强大功能(如各种算法和容器)协同工作时,核心在于让你的自定义类型“说”标准库能听懂的语言。这通常意味着你需要通过重载特定的运算符、提供自定义的比较逻辑或者哈希函数,来告诉标准库如何处理你的对象,比如如何对它们进行排序、查找或存储。
你有没有遇到过这样的情况:写了一个漂亮的
Product
std::vector
std::sort
Product
std::map
std::unordered_map
这其实是C++泛型编程哲学的一个体现:标准库算法和容器是高度通用的,它们对所操作的类型知之甚少,只知道这些类型必须满足某些“概念”或“要求”。当你的自定义类型不满足这些要求时,就需要你来“适配”它。
最直接的适配方式就是运算符重载。如果你想让
std::sort
operator<
operator<
std::cout
operator<<
std::map
operator<
立即学习“C++免费学习笔记(深入)”;
然而,运算符重载并非万能。有时你可能不希望修改类的定义(例如,它是一个第三方库的类),或者你需要多种不同的排序或比较方式。这时,自定义比较器(通常是函数对象,即仿函数,或C++11引入的Lambda表达式)就派上用场了。你可以将这些比较器作为参数传递给
std::sort
std::map
PHP 独特的语法混合了 C、Java、Perl 以及 PHP 自创新的语法。它可以比 CGI或者Perl更快速的执行动态网页。用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML文档中去执行,执行效率比完全生成HTML标记的CGI要高许多。下面介绍了十个PHP高级应用技巧。 1, 使用 ip2long() 和 long2ip() 函数来把 IP 地址转化成整型存储到数据库里
440
对于基于哈希表的容器,如
std::unordered_map
std::unordered_set
std::hash
operator==
std::hash
理解这些,就如同掌握了一套“翻译”工具,让你的自定义类型能够与C++标准库这个庞大的“国际组织”无障碍地交流。
std::sort
std::map
让自定义类型能够被
std::sort
std::map
std::sort
operator<
std::map
operator<
最直接的办法是在你的自定义类型内部重载
operator<
#include <iostream>
#include <vector>
#include <algorithm> // For std::sort
#include <map> // For std::map
#include <string> // For std::string
struct Book {
std::string title;
std::string author;
int publication_year;
double price;
// 重载小于运算符,定义排序规则:首先按价格升序,价格相同则按出版年份降序
bool operator<(const Book& other) const {
if (price != other.price) {
return price < other.price; // 价格低的排在前面
}
return publication_year > other.publication_year; // 价格相同,出版年份新的排在前面
}
// 重载等于运算符,虽然std::sort不直接用,但对于查找或std::unique等算法有用
bool operator==(const Book& other) const {
return title == other.title && author == other.author && publication_year == other.publication_year;
}
};
// 辅助函数,用于打印Book对象
std::ostream& operator<<(std::ostream& os, const Book& b) {
os << "Title: \"" << b.title << "\", Author: " << b.author
<< ", Year: " << b.publication_year << ", Price: $" << b.price;
return os;
}
int main() {
std::vector<Book> library = {
{"The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979, 12.50},
{"Pride and Prejudice", "Jane Austen", 1813, 8.99},
{"1984", "George Orwell", 1949, 10.00},
{"Dune", "Frank Herbert", 1965, 15.00},
{"The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979, 10.00} // 同名但价格不同
};
std::cout << "Original library:\n";
for (const auto& book : library) {
std::cout << book << "\n";
}
std::sort(library.begin(), library.end());
std::cout << "\nSorted library (by price asc, then year desc):\n";
for (const auto& book : library) {
std::cout << book << "\n";
}
// 将Book作为std::map的键
// std::map也需要Book定义operator<来对其键进行排序以上就是C++自定义类型与标准库函数结合使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号