C++ 通用
1. 类中创建指针类型的数据时,请务必重载构造函数及"="操作符
标准库的数据会用到这些重载的函数,迭代器都会用上,请注意
2.重载"<<"操作符用于打印
namespace std {
std::ostream& operator<<(std::ostream& os, const your_type& s) {
//...
return os;
}
}
C++ 11
1. decltype 获取变量的类型
int t = 0;
decltype(t) i;
2. 使用std::initializer_list 实现大括号的构造方法
EList(std::initializer_list<value_type> lst) {
this->count = lst.size();
if (lst.size() > 0) {
auto it = lst.begin();
this->first_node = new ListNode{ *it, nullptr, nullptr };
ListNode* cur = this->first_node;
++it;
for (; it != lst.end(); ++it) {
ListNode* next = new ListNode{ *it, cur, nullptr };
cur->next = next;
cur = next;
}
last_node = cur;
}
}
// 之后就可以这样构造了
EList lst1 = { 1, 4, 7, 10 };
C++ 17
- optional 选择值
#include <optional>
std::optional<int> test_optional(int i) {
if (i > 120)
return std::optional<int>(200);
return std::nullopt;
}
std::cout << "test_optional()" << test_optional(20).value_or(0);
- 结构化声明:
std::map<int, int> testMap = { {1, 1}, {2, 3} };
for (auto [key, value] : testMap) {
std::cout << key << ": " << value << ", " << std::endl;
}