日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c++中的ignore和tie

發布時間:2024/3/12 c/c++ 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c++中的ignore和tie 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、tie和ignore

std::tie和std::ignore都是定義在< tuple >這個頭文件中的,意思其實就很明了了,它肯定是輔助tuple這個數據結構的,先看一下它們的具體定義:
具體的定義:

//Defined in header <tuple> const /*unspecified*/ ignore; (since C++11) (until C++17) inline constexpr /*unspecified*/ ignore; (since C++17)template< class... Types > std::tuple<Types&...> tie( Types&... args ) noexcept; (since C++11) (until C++14) template< class... Types > constexpr std::tuple<Types&...> tie( Types&... args ) noexcept; (since C++14)

std::tie其實是“Creates a tuple of lvalue references to its arguments or instances of std::ignore.”利用參數或者std::ignore創建一個元組的左值引用,它可以用來對tuple的解包或者引入相關的字典排序數據。而std::ignore其實就類似于Go或者其它語言中的忽略元素,起到一個點位符的作用。

二、例程

說還是沒有什么說服力,看看簡單的例程就會明白這兩個數據結構的用法:

#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"的意思是說這個返回值是需要應用的,不能舍棄的,換句話說,如果這個函數的返回值沒有被使用,編譯器會發出警告。set_of_str.insert()這個函數需要注意的是可能返回std::pair也可能返回其它,而這里正好是使用pair到tie的轉換,然后忽略了返回的迭代器,而只關心成功與否。前面提到過,pair可以理解成tuple的特殊情況,這樣對上面這個例程就會很清晰的理解了。而std::ignore可以根據實際情況對返回的相關tuple的內容進行選擇性的忽略,這就是它的優勢所在。

三、總結

其實越深入發現STL中的內容,有好多東西都已經寫好,不用自己在編程時再進行處理。可實際情況可以說各種環境都有,程序員對STL的掌握和應用的熟練程度也不盡相同,這就導致有些STL封裝好的數據結構和算法其實是沒有用到。這還得需要根據自己的實際情況來取舍,能省點事兒,省點兒還是好的。
努力要從今日始!

總結

以上是生活随笔為你收集整理的c++中的ignore和tie的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。