1. vector 的 front() 和 back()
vector.front() 和 vector.back() 在空容器上調(diào)用會(huì)導(dǎo)致未定義的行為。
所以,如果想要使用 front() 和 back(),需要滿足容器不為空。
if (!arr.empty())
{
// arr.front();
// arr.back();
}
2. unordered_map 賦值后不保證順序
unordered_map 是基于哈希表的無(wú)序結(jié)構(gòu),在將 unordered_map 對(duì)象賦值給一個(gè)新的 unordered_map 時(shí),前后兩個(gè) unordered_map 的元素順序是不一致的。
std::unordered_map<int, std::string> um;
um.emplace(1001, "111");
um.emplace(1012, "222");
um.emplace(1023, "333");
um.emplace(1044, "444");
um.emplace(1005, "555");
um.emplace(1016, "666");
for (auto const & i : um) {
std::cout << i.first << " " << i.second << std::endl;
}
std::cout << "----------------------" << std::endl;
auto new_um = um;
for (auto const& i : new_um) {
std::cout << i.first << " " << i.second << std::endl;
}
// 結(jié)果
// 1044 444
// 1001 111
// 1012 222
// 1023 333
// 1005 555
// 1016 666
// ----------------------
// 1001 111
// 1044 444
// 1012 222
// 1023 333
// 1005 555
// 1016 666
3. 獲取對(duì)象類型
C++ 中使用typeid()來(lái)獲取對(duì)象的類型信息
#include <iostream>
#include <typeinfo>
int main() {
int i;
std::cout << "i type is: " << typeid(i).name() << '\n';
return 0;
}
// 結(jié)果
// i is: int
4. decltype
decltype用于選擇并返回操作數(shù)的數(shù)據(jù)類型,解決復(fù)雜的類型聲明。
- 作用于變量:得到變量的類型
- 作用于表達(dá)式:左值的表達(dá)式得到類型的引用;右值的表達(dá)式得到類型。且都不計(jì)算表達(dá)式的值
- 作用于函數(shù)名:得到函數(shù)類型,不轉(zhuǎn)換成指針
auto、typeid、decltype區(qū)別:
- auto:推到類型,且必須初始化
- typeid:獲取類型,可用于類型的比較
- decltype:獲取類型,僅用于聲明
decltype的使用場(chǎng)景:用于聲明模板函數(shù),此模板函數(shù)的返回值類型依賴于其參數(shù)類型
// C++ 11
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u)
{
return t + u;
}
// C++ 14
template<typename T, typename U>
auto add(T t, U u)
{
return t + u;
}
// 在其所調(diào)用的函數(shù)返回引用的情況下
// 函數(shù)調(diào)用的完美轉(zhuǎn)發(fā)必須用 decltype(auto)
template<class F, class... Args>
decltype(auto) PerfectForward(F fun, Args&&... args)
{
return fun(std::forward<Args>(args)...);
}
// C++17 支持 auto 形參聲明
template<auto n>
auto f() -> std::pair<decltype(n), decltype(n)> // auto 不能從花括號(hào)初始化器列表推導(dǎo)
{
return { n, n + 1 };
}
int main()
{
auto arr = f<9>();
std::cout << "arr.first :" << arr.first << " arr.second :" << arr.second << std::endl;
return 0;
}
// 結(jié)果
// arr.first :9 arr.second :10