C++相關閑碎記錄(3)

1、reference wrapper

例如聲明如下的模板:

template <typename T>
void foo(T val);

?如果調用使用:

int x;
foo(std::ref(x));

T變成int&,而使用調用

int x;
foo(std::cref(x));

T變成const int&。

?這個特性被C++標準庫用在各個地方,例如:

make_pair()用此特性于是能夠創建一個pair<>of reference
make_tuple()用此特性可以創建一個tuple<>of reference?
?

std::vector<MyClass&> coll;       //error
std::vector<std::reference_wrapper<MyClass>> coll;    //ok

2、function type wrapper

#include <iostream>
#include <vector>
#include <functional>
using namespace std;void func(int x, int y) {std::cout << "func" << std::endl;
}class C {
public:void memfunc(int x, int y) const{std::cout << "C::memfunc" << std::endl;}
};int main()
{std::vector<std::function<void(int,int)>> tasks;tasks.push_back(func);tasks.push_back([](int x, int y) {std::cout << "lambda" << std::endl;});for (std::function<void(int,int)> f : tasks) {f(3, 33);}std::function<void(const C&, int, int)> mf;mf = &C::memfunc;mf(C(), 2, 3);return 0;
}
輸入:
func
lambda
C::memfunc

3、挑選最小值和最大值

auto extremes = std::minmax({px, py, pz}, [](int*a, int*b) {return *a < *b;                        });
兩值互換:
namespace std {template <typename T>inline void swap(T& a, T& b) {T tmp(std::move(a));a = std::move(b);b = std::move(tmp);}
}

4、class ratio<>

#include <ratio>
#include <iostream>
using namespace std;int main()
{typedef ratio<5,3> FiveThirds;cout << FiveThirds::num << "/" << FiveThirds::den << endl;typedef ratio<25,15> AlsoFiveThirds;cout << AlsoFiveThirds::num << "/" << AlsoFiveThirds::den << endl;ratio<42,42> one;cout << one.num << "/" << one.den << endl;ratio<0> zero;cout << zero.num << "/" << zero.den << endl;typedef ratio<7,-3> Neg;cout << Neg::num << "/" << Neg::den << endl;
}
輸出:
5/3
5/3
1/1
0/1
-7/3

?5、duration

#include <ratio>
#include <iostream>
#include <chrono>
using namespace std;int main()
{std::chrono::duration<int>                         twentySeconds(20);  //以秒為單位std::chrono::duration<double, std::ratio<60>>      halfAMinute(0.5);   //以60秒為單位std::chrono::duration<long, std::ratio<1, 1000>>   oneMillisecond(1);  //以1/1000秒為單位std::chrono::seconds         twentySeconds(20);std::chrono::hours           aDay(24);std::chrono::milliseconds    oneMillisecond(1);
}

// 將毫秒單位的duration切割為小時,分鐘,秒,毫秒?

#include <ratio>
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace std::chrono;milliseconds ms(7255042);template <typename V, typename R>
ostream& operator<<(ostream& os, const chrono::duration<V,R>& d) {os << "[" << d.count() << " of " << R::num << "/" << R::den << "]";return os;
}// 將毫秒單位的duration切割為小時,分鐘,秒,毫秒
int main()
{hours hh = duration_cast<hours>(ms);minutes mm = duration_cast<minutes>(ms%chrono::hours(1));seconds ss = duration_cast<seconds>(ms%chrono::minutes(1));milliseconds msec = duration_cast<milliseconds>(ms%chrono::seconds(1));cout << "raw: " << hh << "::" << mm << "::"<< ss << "::" << msec << endl;cout << "    " << setfill('0') << setw(2) << hh.count() << "::"<< setw(2) << mm.count() << "::"<< setw(2) << ss.count() << "::"<< setw(2) << msec.count() << endl;
}
#include <ratio>
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace std::chrono;template <typename C>
void printClockData ()
{using namespace std;cout << "- precision: ";// if time unit is less than or equal to one millisecondtypedef typename C::period P;   // type of time unitif (ratio_less_equal<P,milli>::value) {// convert to and print as millisecondstypedef typename ratio_multiply<P,kilo>::type TT;cout << fixed << double(TT::num)/TT::den<< " milliseconds" << endl;}else {// print as secondscout << fixed << double(P::num)/P::den << " seconds" << endl;}cout << "- is_steady: " << boolalpha << C::is_steady << endl;
}int main()
{std::cout << "system_clock: " << std::endl;printClockData<std::chrono::system_clock>();std::cout << "\nhigh_resolution_clock: " << std::endl;printClockData<std::chrono::high_resolution_clock>();std::cout << "\nsteady_clock: " << std::endl;printClockData<std::chrono::steady_clock>();
}
輸出:
system_clock: 
- precision: 0.000001 milliseconds
- is_steady: falsehigh_resolution_clock:
- precision: 0.000001 milliseconds
- is_steady: falsesteady_clock:
- precision: 0.000001 milliseconds
- is_steady: true

下面的程序將timepoint賦值給tp,并轉換為日歷表示法,window運行會報錯,LInux下運行正常:

#include <chrono>
#include <ctime>
#include <string>
#include <iostream>std::string asString (const std::chrono::system_clock::time_point& tp)
{// convert to system time:std::time_t t = std::chrono::system_clock::to_time_t(tp);std::string ts = std::ctime(&t);    // convert to calendar timets.resize(ts.size()-1);             // skip trailing newlinereturn ts; 
}int main()
{// print the epoch of this system clock:std::chrono::system_clock::time_point tp;std::cout << "epoch: " << asString(tp) << std::endl;// print current time:tp = std::chrono::system_clock::now();std::cout << "now:   " << asString(tp) << std::endl;// print minimum time of this system clock:tp = std::chrono::system_clock::time_point::min();std::cout << "min:   " << asString(tp) << std::endl;// print maximum time of this system clock:tp = std::chrono::system_clock::time_point::max();std::cout << "max:   " << asString(tp) << std::endl;
}
輸出:
epoch: Thu Jan  1 08:00:00 1970
now:   Thu Nov 30 21:29:29 2023
min:   Tue Sep 21 08:18:27 1677
max:   Sat Apr 12 07:47:16 2262
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;string asString (const chrono::system_clock::time_point& tp)
{time_t t = chrono::system_clock::to_time_t(tp); // convert to system timestring ts = ctime(&t);                          // convert to calendar timets.resize(ts.size()-1);                         // skip trailing newlinereturn ts; 
}int main()
{// define type for durations that represent day(s):typedef chrono::duration<int,ratio<3600*24>> Days;// process the epoch of this system clockchrono::time_point<chrono::system_clock> tp;cout << "epoch:     " << asString(tp) << endl;// add one day, 23 hours, and 55 minutestp += Days(1) + chrono::hours(23) + chrono::minutes(55);cout << "later:     " << asString(tp) << endl;// process difference from epoch in minutes and days:auto diff = tp - chrono::system_clock::time_point();cout << "diff:      "<< chrono::duration_cast<chrono::minutes>(diff).count()<< " minute(s)" << endl;Days days = chrono::duration_cast<Days>(diff);cout << "diff:      " << days.count() << " day(s)" << endl;// subtract one year (hoping it is valid and not a leap year)tp -= chrono::hours(24*365);cout << "-1 year:   " << asString(tp) << endl;// subtract 50 years (hoping it is valid and ignoring leap years)tp -= chrono::duration<int,ratio<3600*24*365>>(50);cout << "-50 years: " << asString(tp) << endl;// subtract 50 years (hoping it is valid and ignoring leap years)tp -= chrono::duration<int,ratio<3600*24*365>>(50);cout << "-50 years: " << asString(tp) << endl;
}
輸出:
epoch:     Thu Jan  1 08:00:00 1970
later:     Sat Jan  3 07:55:00 1970
diff:      2875 minute(s)
diff:      1 day(s)
-1 year:   Fri Jan  3 07:55:00 1969
-50 years: Thu Jan 16 07:55:00 1919
-50 years: Wed Jan 27 08:00:43 1869

?6、timepoint與日歷時間的轉換

#include <chrono>
#include <ctime>
#include <string>
#include <iostream>// convert timepoint of system clock to calendar time string
inline std::string asString(const std::chrono::system_clock::time_point& tp) {std::time_t t = std::chrono::system_clock::to_time_t(tp);std::string ts = ctime(&t);  // convert to calendar timets.resize(ts.size()-1);      //skip trailing newlinereturn ts;
}// convert calender time to timepoint of system clock
inline std::chrono::system_clock::time_point
makeTimePoint(int year, int mon, int day, int hour, int min, int sec=0) {struct std::tm t;t.tm_sec = sec;t.tm_min = min;t.tm_hour = hour;t.tm_mday = day;t.tm_mon = mon - 1;t.tm_year = year-1900;t.tm_isdst = -1;std::time_t tt = std::mktime(&t);if (tt == -1) {throw "no valid system time";}return std::chrono::system_clock::from_time_t(tt);
}int main() {auto tp1 = makeTimePoint(2023, 11, 30, 00, 00);std::cout << asString(tp1) << std::endl;auto tp2 = makeTimePoint(2023, 03, 23, 12, 33);std::cout << asString(tp2) << std::endl;return 0;
}
輸出:
Thu Nov 30 00:00:00 2023
Thu Mar 23 12:33:00 2023

7、<cstring>中的定義式

//在ptr所指的前len個byte中找出字符c
memchr(const void* ptr, int c, size_t len)//比較ptr1和ptr2所指的前len個byte
memcmp(const void* ptr1, const void* ptr2, size_t len)//將fromPtr所指的前len個byte復制到toPtr
memcpy(void* toPtr, const void* fromPtr, size_t len)//將fromPtr所指的前len個byte復制到toPtr(區域可重疊)
memmove(void* toPtr, const void* fromPtr, size_t len)//將ptr所指的前len個byte賦值為字符c
memset(void* ptr, int c, size_t len)

?8、algorithm

(1)find
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;int main()
{list<int> coll;// insert elements from 20 to 40for (int i=20; i<=40; ++i) {coll.push_back(i);}// find position of element with value 3// - there is none, so pos3 gets coll.end()auto pos3 = find (coll.begin(), coll.end(),    // range3);                          // value// reverse the order of elements between found element and the end// - because pos3 is coll.end() it reverses an empty rangereverse (pos3, coll.end());// find positions of values 25 and 35list<int>::iterator pos25, pos35;pos25 = find (coll.begin(), coll.end(),  // range25);                       // valuepos35 = find (coll.begin(), coll.end(),  // range35);                       // value// print the maximum of the corresponding range// - note: including pos25 but excluding pos35cout << "max: " << *max_element (pos25, pos35) << endl;// process the elements including the last positioncout << "max: " << *max_element (pos25, ++pos35) << endl;
}
(2)find_if

查找最先出現的25或者35

#include <algorithm>
#include <list>
#include <iostream>
using namespace std;int main()
{list<int> coll;// insert elements from 20 to 40for (int i=20; i<=40; ++i) {coll.push_back(i);}auto pos = find_if(coll.begin(), coll.end(),[](int i) {return i == 25 || i == 35;});if (pos == coll.end()) {std::cout << "not found" << std::endl;exit(1);}list<int>::const_iterator pos25, pos35;if (*pos == 25) {// 先找到25pos25 = pos;pos35 = find(++pos, coll.end(), 35);std::cout << *pos35 << std::endl;} else {pos35 = pos;pos25 = find(++pos, coll.end(), 25);std::cout << *pos25 << std::endl;}
}

9、insert iterator

#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <iterator>
#include <deque>
#include <iostream>
using namespace std;int main()
{list<int> coll1 = {1, 2, 3, 4, 5, 6, 7, 8};vector<int> coll2;copy(coll1.begin(), coll1.end(), back_inserter(coll2));deque<int> coll3;copy(coll1.begin(), coll1.end(), front_inserter(coll3));set<int> coll4;copy(coll1.begin(), coll1.end(), inserter(coll4, coll4.begin()));for (auto &ele : coll2) {std::cout << ele << " ";}std::cout << std::endl;for (auto &ele : coll3) {std::cout << ele << " ";}std::cout << std::endl;for(auto & ele : coll4) {std::cout << ele << " ";}
}
輸出:
1 2 3 4 5 6 7 8 
8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8

inserter的作用是在“初始化時接受的第二個實參”所指的位置的前面插入元素,內部調用成員函數insert(),并以新值和新位置作為實參傳入,所有的STL容器都提供insert()成員函數,這是唯一可以用于關聯式容器身上的一種預定義inserter。

10、stream iterator?

?

#include <algorithm>
#include <vector>
#include <iterator>
#include <string>
#include <iostream>
using namespace std;int main()
{vector<string> coll;// 使用ctrl+z 回車進行終止copy(istream_iterator<string>(cin), istream_iterator<string>(),back_inserter(coll));sort(coll.begin(), coll.end());unique_copy(coll.cbegin(), coll.cend(), ostream_iterator<string>(cout, "\n"));
}

11、reverse iterator?

#include <algorithm>
#include <vector>
#include <iterator>
#include <string>
#include <iostream>
using namespace std;int main()
{vector<int> coll;for (int i = 1; i <= 9; i++) {coll.push_back(i);}copy(coll.crbegin(), coll.crend(), ostream_iterator<int>(cout, " "));
}
輸出:
9 8 7 6 5 4 3 2 1 

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/207252.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/207252.shtml
英文地址,請注明出處:http://en.pswp.cn/news/207252.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

fijkplayer flutter 直播流播放

fijkplayer flutter 直播流播放 fijkplayer 是 ijkplayer 的 Flutter 封裝&#xff0c; 是一款支持 android 和 iOS 的 Flutter 媒體播放器插件&#xff0c; 由 ijkplayer 底層驅動。 通過紋理&#xff08;Texture&#xff09;接入播放器視頻渲染到 Flutter 中。 前言 目前使用…

設置單擊右鍵可以選擇用VS Code打開文件

設置單擊右鍵可以選擇用VS Code打開文件_通過code打開-CSDN博客

PostgreSQL 技術內幕(十二) CloudberryDB 并行化查詢之路

隨著數據驅動的應用日益增多&#xff0c;數據查詢和分析的量級和時效性要求也在不斷提升&#xff0c;對數據庫的查詢性能提出了更高的要求。為了滿足這一需求&#xff0c;數據庫引擎不斷經歷創新&#xff0c;其中并行執行引擎是性能提升的重要手段之一&#xff0c;逐漸成為數據…

sh腳本移動文件

內容&#xff1a;兩臺服務器&#xff0c;one 和 two ,在one的指定目錄下&#xff0c;找到指定結尾的文件&#xff0c;將這個文件移到two服務器的指定路徑下&#xff0c;同時將one的源文件 移到 其他目錄下。 #!/bin/bash# 指定源路徑 source_path"/u01/isi/75_files_te…

One-to-Few Label Assignment for End-to-End Dense Detection閱讀筆記

One-to-Few Label Assignment for End-to-End Dense Detection閱讀筆記 Abstract 一對一&#xff08;o2o&#xff09;標簽分配對基于變換器的端到端檢測起著關鍵作用&#xff0c;最近已經被引入到全卷積檢測器中&#xff0c;用于端到端密集檢測。然而&#xff0c;o2o可能因為…

[動態規劃及遞歸記憶搜索法]1.鋼條切割問題

摘要 本系列從6道經典的動態規劃題入手&#xff0c;去理解動態規劃的基本思路和想法&#xff0c;以及動態規劃和遞歸記憶搜索法存在的某些聯系&#xff0c;對于每道題目&#xff0c;我們將用兩種方法去實現&#xff0c;這里講解第一道題目&#xff0c;作個開頭。 前言 我們知…

elasticsearch 內網下如何以離線的方式上傳任意的huggingFace上的NLP模型(國內避坑指南)

es自2020年的8.x版本以來&#xff0c;就提供了機器學習的能力。我們可以使用es官方提供的工具eland&#xff0c;將hugging face上的NLP模型&#xff0c;上傳到es集群中。利用es的機器學習模塊&#xff0c;來運維部署管理模型。配合es的管道處理&#xff0c;來更加便捷的處理數據…

吳恩達《機器學習》12-1:優化目標

在機器學習的旅程中&#xff0c;我們已經接觸了多種學習算法。在監督學習中&#xff0c;選擇使用算法 A 還是算法 B 的重要性逐漸減弱&#xff0c;而更關鍵的是如何在應用這些算法時優化目標。這包括設計特征、選擇正則化參數等因素&#xff0c;這些在不同水平的實踐者之間可能…

UG NX二次開發(C#)-求曲線在某一點處的法矢和切矢

提示:文章寫完后,目錄可以自動生成,如何生成可參考右邊的幫助文檔 文章目錄 1、前言2、在UG NX中創建一個曲線3、直接放代碼4、測試案例1、前言 最近確實有點忙了,好久沒更新博客了。今天恰好有時間,就更新下,還請家人們見諒。 今天我們講一下如何獲取一條曲線上某一條曲…

注意力機制的快速學習

注意力機制的快速學習 注意力機制 將焦點聚焦在比較重要的事物上 我&#xff08;查詢對象Q&#xff09;&#xff0c;這張圖&#xff08;被查詢對象V&#xff09; 我看一張圖&#xff0c;第一眼&#xff0c;就會判斷那些東西對我而言比較重要&#xff0c;那些對于我不重要&…

Pytorch從零開始實戰12

Pytorch從零開始實戰——DenseNet算法實戰 本系列來源于365天深度學習訓練營 原作者K同學 文章目錄 Pytorch從零開始實戰——DenseNet算法實戰環境準備數據集模型選擇開始訓練可視化總結 環境準備 本文基于Jupyter notebook&#xff0c;使用Python3.8&#xff0c;Pytorch2.…

Elasticsearch、Logstash、Kibana(ELK)環境搭建

下面是 Elasticsearch、Logstash、Kibana&#xff08;ELK&#xff09;環境搭建的具體操作步驟&#xff1a; 安裝 Java ELK 是基于 Java 編寫的&#xff0c;因此需要先安裝 Java。建議安裝 Java 8 或以上版本。 下載并安裝 Elasticsearch Elasticsearch 是一個基于 Lucene 的…

DevEco Studio 運行項目有時會自動出現.js和.map文件

運行的時候報錯了&#xff0c;發現多了.js和.map&#xff0c;而且還不是一個&#xff0c;很多個。 通過查詢&#xff0c;好像是之前已知問題了&#xff0c;給的建議是手動刪除(一個一個刪)&#xff0c;而且有的評論還說&#xff0c;一周出現了3次&#xff0c;太可怕了。 搜的過…

【網絡編程】-- 02 端口、通信協議

網絡編程 3 端口 端口表示計算機上的一個程序的進程 不同的進程有不同的端口號&#xff01;用來區分不同的軟件進程 被規定總共0~65535 TCP,UDP&#xff1a;65535 * 2 在同一協議下&#xff0c;端口號不可以沖突占用 端口分類&#xff1a; 公有端口&#xff1a;0~1023 HT…

【android開發-23】android中WebView的用法詳解

1&#xff0c;WabView的用法 在Android中&#xff0c;WebView是一個非常重要的組件&#xff0c;它允許我們在Android應用中嵌入網頁&#xff0c;展示HTML內容。WebView是Android SDK中提供的標準組件&#xff0c;使用它我們可以很方便地將web頁面直接嵌入到Android應用中。Web…

亞信安慧AntDB數據庫中級培訓ACP上線,中國移動總部首批客戶認證通過

近日&#xff0c;亞信安慧AntDB數據庫ACP&#xff08;AntDB Certified Professional&#xff09;中級培訓課程于官網上線。在中國移動總部客戶運維團隊、現場項目部伙伴和AntDB數據庫成員的協同組織下&#xff0c;首批中級認證學員順利完成相關課程的培訓&#xff0c;并獲得Ant…

自然語言處理22-基于本地知識庫的快速問答系統,利用大模型的中文訓練集為知識庫

大家好,我是微學AI,今天給大家介紹一下自然語言處理22-基于本地知識庫的快速問答系統,利用大模型的中文訓練集為知識庫。我們的快速問答系統是基于本地知識庫和大模型的最新技術,它利用了經過訓練的中文大模型,該模型使用了包括alpaca_gpt4_data的開源數據集。 一、本地…

C //例10.3 從鍵盤讀入若干個字符串,對它們按字母大小的順序排序,然后把排好序的字符串送到磁盤文件中保存。

C程序設計 &#xff08;第四版&#xff09; 譚浩強 例10.3 例10.3 從鍵盤讀入若干個字符串&#xff0c;對它們按字母大小的順序排序&#xff0c;然后把排好序的字符串送到磁盤文件中保存。 IDE工具&#xff1a;VS2010 Note: 使用不同的IDE工具可能有部分差異。 代碼塊 方法…

2023_Spark_實驗二十五:SparkStreaming讀取Kafka數據源:使用Direct方式

SparkStreaming讀取Kafka數據源&#xff1a;使用Direct方式 一、前提工作 安裝了zookeeper 安裝了Kafka 實驗環境&#xff1a;kafka zookeeper spark 實驗流程 二、實驗內容 實驗要求&#xff1a;實現的從kafka讀取實現wordcount程序 啟動zookeeper zk.sh start# zk.sh…