c++中的ignore和tie
一、tie和ignore
std::tie和std::ignore都是定義在< tuple >這個頭文件中的,意思其實就很明了了,它肯定是輔助tuple這個數(shù)據(jù)結(jié)構(gòu)的,先看一下它們的具體定義:
具體的定義:
std::tie其實是“Creates a tuple of lvalue references to its arguments or instances of std::ignore.”利用參數(shù)或者std::ignore創(chuàng)建一個元組的左值引用,它可以用來對tuple的解包或者引入相關(guān)的字典排序數(shù)據(jù)。而std::ignore其實就類似于Go或者其它語言中的忽略元素,起到一個點位符的作用。
二、例程
說還是沒有什么說服力,看看簡單的例程就會明白這兩個數(shù)據(jù)結(jié)構(gòu)的用法:
#include <iostream> #include <string> #include <set> #include <tuple>struct S {int n;std::string s;float d;bool operator<(const S& rhs) const{// compares n to rhs.n,// then s to rhs.s,// then d to rhs.dreturn std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);} };int main() {std::set<S> set_of_s; // S is LessThanComparableS value{42, "Test", 3.14};std::set<S>::iterator iter;bool inserted;// unpacks the return value of insert into iter and insertedstd::tie(iter, inserted) = set_of_s.insert(value);if (inserted)std::cout << "Value was inserted successfully\n"; }再看看ignore的例程:
#include <iostream> #include <string> #include <set> #include <tuple>[[nodiscard]] int dontIgnoreMe() {return 42; }int main() {std::ignore = dontIgnoreMe();std::set<std::string> set_of_str;bool inserted = false;std::tie(std::ignore, inserted) = set_of_str.insert("Test");if (inserted) {std::cout << "Value was inserted successfully\n";} }"nodiscard"的意思是說這個返回值是需要應(yīng)用的,不能舍棄的,換句話說,如果這個函數(shù)的返回值沒有被使用,編譯器會發(fā)出警告。set_of_str.insert()這個函數(shù)需要注意的是可能返回std::pair也可能返回其它,而這里正好是使用pair到tie的轉(zhuǎn)換,然后忽略了返回的迭代器,而只關(guān)心成功與否。前面提到過,pair可以理解成tuple的特殊情況,這樣對上面這個例程就會很清晰的理解了。而std::ignore可以根據(jù)實際情況對返回的相關(guān)tuple的內(nèi)容進行選擇性的忽略,這就是它的優(yōu)勢所在。
三、總結(jié)
其實越深入發(fā)現(xiàn)STL中的內(nèi)容,有好多東西都已經(jīng)寫好,不用自己在編程時再進行處理。可實際情況可以說各種環(huán)境都有,程序員對STL的掌握和應(yīng)用的熟練程度也不盡相同,這就導(dǎo)致有些STL封裝好的數(shù)據(jù)結(jié)構(gòu)和算法其實是沒有用到。這還得需要根據(jù)自己的實際情況來取舍,能省點事兒,省點兒還是好的。
努力要從今日始!
總結(jié)
以上是生活随笔為你收集整理的c++中的ignore和tie的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ std::ios::tie
- 下一篇: C++ —— 类的使用