C++ 工具函數庫

在寫一些大型項目的過程中經常需要一些工具函數,例如獲取隨機數、計時器、打印函數、重要常量(如最大值)、信號與槽等,由于每一個工程都自己手動實現一個實在是太傻,我將其總結放入一個文件中。


utils.h

// Copyright(C), Edward-Elric233
// Author: Edward-Elric233
// Version: 1.0
// Date: 2022/6/27
// Description: 
#ifndef UTILS_H
#define UTILS_H#include "json.hpp"
#include <iostream>
#include <random>
#include <chrono>
#include <fstream>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <functional>namespace edward {constexpr int INF = 0x3f3f3f3f;//extern std::ofstream ofs;inline void print() {std::cout << "\n";
//    ofs << "\n";
}
template<typename T, typename... Args>
void print(T&& first, Args&&... args) {std::cout << first << " ";
//    ofs << first << " ";print(std::forward<Args>(args)...);
}template<typename Iter>
void printArr(Iter begin, Iter end) {while (begin != end) {std::cout << *begin++ << " ";}std::cout << "\n";
}template<typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pr) {os << pr.first << " " << pr.second;return os;
}template<typename Container>
void printArr(const Container& container) {for (auto x : container) {std::cout << x << " ";}std::cout << "\n";
}class Random {
public:// random number generator.static std::mt19937 pseudoRandNumGen;static void initRand(int seed) { pseudoRandNumGen = std::mt19937(seed); }   //設置隨機數種子static int fastRand(int lb, int ub) { return (pseudoRandNumGen() % (ub - lb)) + lb; }static int fastRand(int ub) { return pseudoRandNumGen() % ub; }static int rand(int lb, int ub) { return std::uniform_int_distribution<int>(lb, ub - 1)(pseudoRandNumGen); }static int rand(int ub) { return std::uniform_int_distribution<int>(0, ub - 1)(pseudoRandNumGen); }
};class Timer {std::chrono::time_point<std::chrono::system_clock> timePoint_;
public:Timer(): timePoint_(std::chrono::system_clock::now()) {}Timer(const Timer&) = delete;~Timer() = default;void operator() (const std::string& msg) {auto duration = std::chrono::system_clock::now() - timePoint_;print(msg, static_cast<double>(duration.count()) / decltype(duration)::period::den, "s");}void reset() {timePoint_ = std::chrono::system_clock::now();}void operator() (nlohmann::json& arr) {auto duration = std::chrono::system_clock::now() - timePoint_;arr.push_back(duration.count());}};using Slot = std::shared_ptr<void>;//前置聲明
template<typename Signature>
class Signal;
template<typename Ret, typename... Args>
class Signal<Ret(Args...)>;namespace detail {//前置聲明template<typename Callback> class SlotImpl;template<typename Callback>class SignalImpl {public:using SlotList = std::unordered_map<SlotImpl<Callback> *, std::weak_ptr<SlotImpl<Callback>>>;SignalImpl(): slots_(new SlotList), mutex_() {}~SignalImpl() {}//只能在加鎖后使用void cowWithLock() {if (!slots_.unique()) {slots_.reset(new SlotList(*slots_));}}//添加槽函數void add(const std::shared_ptr<SlotImpl<Callback>> &slot) {std::lock_guard<std::mutex> lockGuard(mutex_);cowWithLock();slots_->insert({slot.get(), slot});}//供SlotImpl調用,刪除槽函數void remove(SlotImpl<Callback> *slot) {std::lock_guard<std::mutex> lockGuard(mutex_);cowWithLock();slots_->erase(slot);}std::shared_ptr<SlotList> getSlotList() {std::lock_guard<std::mutex> lockGuard(mutex_);return slots_;}private:std::mutex mutex_;//保存SlotImpl的weak_ptr//之所以不保存SlotList而是保存其shared_ptr是為了實現COWstd::shared_ptr<SlotList> slots_;};template<typename Callback>class SlotImpl {public:SlotImpl(Callback&& cb, const std::shared_ptr<SignalImpl<Callback>> &signal): cb_(cb), signal_(signal) {}~SlotImpl() {auto signal = signal_.lock();if (signal) {signal->remove(this);}}Callback cb_;private://保存SignalImpl的weak_ptrstd::weak_ptr<SignalImpl<Callback>> signal_;};
}template<typename Ret, typename... Args>
class Signal<Ret(Args...)> {
public:using Callback = std::function<Ret(Args...)>;using SignalImpl = detail::SignalImpl<Callback>;using SlotImpl = detail::SlotImpl<Callback>;Signal(): impl_(new SignalImpl) {}~Signal() {}/*!* 添加槽函數* @param cb 槽函數* @return 需要保存這個智能指針,否則會自動從槽函數列表中刪除*/template<typename Func>Slot connect(Func&& cb) {std::shared_ptr<SlotImpl> slot(new SlotImpl(std::forward<Func>(cb), impl_));impl_->add(slot);return slot;}template<typename ...ARGS>void operator() (ARGS&&... args) {auto slots = impl_->getSlotList();//使用引用避免智能指針的解引用auto &s = *slots;for (auto &&[pSlotImpl, pWkSlotImpl] : s) {auto pShrSlotImpl = pWkSlotImpl.lock();if (pShrSlotImpl) {pShrSlotImpl->cb_(std::forward<ARGS>(args)...);}}}private://保存shared_ptr的原因是需要傳遞給SlotImpl,在SlotImpl析構的時候會清除自己const std::shared_ptr<SignalImpl> impl_;
};}#endif //UTILS_H

utils.cpp

// Copyright(C), Edward-Elric233
// Author: Edward-Elric233
// Version: 1.0
// Date: 2022/6/27
// Description: 
#include "utils.h"namespace edward {std::mt19937 Random::pseudoRandNumGen(std::chrono::system_clock::now().time_since_epoch().count()); //默認使用當下時間戳初始化隨機數種子,精確到納秒//std::ofstream ofs("../test/debug.txt");}

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

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

相關文章

muduo網絡庫使用入門

muduo網絡庫介紹 muduo網絡庫是陳碩大神開發的基于主從Reactor模式的&#xff0c;事件驅動的高性能網絡庫。 網絡編程中有很多是事務性的工作&#xff0c;使用muduo網絡庫&#xff0c;用戶只需要填上關鍵的業務邏輯代碼&#xff0c;并將回調注冊到框架中&#xff0c;就可以實…

C++ map/unordered_map元素類型std::pair<const key_type, mapped_type>陷阱

在開發的過程中需要遍歷一個unordered_map然后把他的迭代器傳給另一個對象&#xff1a; class A; class B { public:void deal(const std::pair<int, A>& item); }; std::unordered_map<int, A> mp; B b; for (auto &pr : mp) {b.deal(pr); }在我的項目中…

Ubuntu install ‘Bash to dock‘

緒論 在Ubuntu環境搭建這篇博客中記錄了使用Dash To Dock來配置Ubuntu的菜單項&#xff0c;使得實現macOS一樣的效果。為了配置新電腦的環境&#xff0c;我還是想安裝這個軟件。但是如今在Ubuntu Software中已經找不到這個軟件了&#xff0c;我在網上借鑒了一些博客的經驗才得…

Leetcode第309場周賽

Date: September 4, 2022 Difficulty: medium Rate by others: ???? Time consuming: 1h30min 題目鏈接 競賽 - 力扣 (LeetCode) 題目解析 2399. 檢查相同字母間的距離 class Solution {public:bool checkDistances(string s, vector<int>& distance) {vec…

C++ 模板函數、模板類:如果沒有被使用就不會被實例化

C中如果一個模板函數沒有使用過&#xff0c;那么其局部靜態變量都不會被實例化&#xff1a; class A { public:A() {edward::print("A ctor");} };template<typename T> void test() {static A a; }int main() {test<int>(); //如果注釋掉則不會有輸出r…

C++ 條件變量的使用

緒論 并發編程紛繁復雜&#xff0c;其中用于線程同步的主要工具——條件變量&#xff0c;雖然精悍&#xff0c;但是要想正確靈活的運用卻并不容易。 對于條件變量的理解有三個難點&#xff1a; 為什么wait函數需要將解鎖和阻塞、喚醒和上鎖這兩對操作編程原子的&#xff1f;為…

C++Primer學習筆記:第1章 開始

本博客為閱讀《C Primer》&#xff08;第5版&#xff09;的讀書筆記 ps:剛開始的時候我將所有的筆記都放在一篇博客中&#xff0c;等看到第六章的時候發現實在是太多了&#xff0c;導致我自己都不想看&#xff0c;為了日后回顧&#xff08;不那么有心理壓力&#xff09;&#…

【ubuntu】ubuntu14.04上安裝搜狗輸入法

** 在ubuntu14.04.4 desktop 64amd版本上安裝sogou輸入法 ** 0.換安裝源為中國源&#xff08;可選&#xff0c;下載會快些&#xff09; 1.搭fcitx環境 2.安裝sogou for linux 詳細步驟&#xff1a; 因為sogou中文輸入法基于fcitx(Free Chinese Input Toy for X),需要先搭環境…

【ubuntu】ubuntu下用make編譯程序報錯找不到openssl/conf.h

ubuntu下用make編譯程序報錯找不到openssl/conf.h 安裝libssl-dev:i386&#xff0c;sudo apt-get install libssl-dev:i386 看好版本&#xff0c;如果不加i386默認下載的是32位&#xff0c;用ln命令連接過去也還是用不了的!libssl.dev安裝好后&#xff0c;用find / -name libs…

【ubuntu】ubuntu如何改變系統用戶名

ubuntu如何改變系統用戶名 方法1&#xff1a;修改現有用戶名 方法2&#xff1a;創建新用戶&#xff0c;刪掉舊用戶 方法1&#xff1a; * *—&#xff01;&#xff01;&#xff01;有博客說要先改密碼&#xff0c;再改用戶名&#xff0c;否則會出現無法登陸狀況&#xff01;&…

什么是signal(SIGCHLD, SIG_IGN)函數

什么是signal(SIGCHLD, SIG_IGN)函數 在進行網絡編程時候遇到這個函數的使用&#xff0c;自己學習結果如下&#xff0c;有不對請幫忙指正:) signal(SIGCHLD, SIG_IGN)打開manpage康一康~ sighandler_t signal ( int signum, sighandler_t handler );參數1 int signum: 就是…

ssh連接不上linux虛擬機

ssh連接不上linux虛擬機 1.開啟ssh服務 linux虛擬機下命令行輸入&#xff1a; start service ssh如果顯示沒有ssh&#xff0c;就下面兩個試一試哪一個ok&#xff0c;安裝一下ssh&#xff1a; sudo apt-get install openssh-server sudo apt-get install sshd2.還有人說可能是…

沒寫client,想先測試server端怎么辦?

沒寫client&#xff0c;想先測試server端怎么辦&#xff1f; 辦法&#xff1a; 1.先打開終端./server&#xff0c;運行起來server 2.再開一個終端&#xff0c; 輸入nc 127.0.0.1 8888 回車&#xff08;這里port號要和server里邊設置的一致&#xff0c;127.0.0.1是和本機的測試…

【報錯解決】linux網絡編程報錯storage size of ‘serv_addr’ isn’t known解決辦法

linux網絡編程報錯storage size of ‘serv_addr’ isn’t known解決辦法 報錯如下&#xff1a; server.c:18:21: error: storage size of ‘serv_addr’ isn’t known struct sockaddr_in serv_addr, clit_addr; ^server.c:18:32: error: storage size of ‘clit_addr’ isn’…

【c】寫頭文件要加#ifndef,#define, #endif

頭文件首位 編寫.h時&#xff0c; 最好加上如下&#xff0c;用來防止重復包含頭文件&#xff1a; 例如&#xff1a; 要編寫頭文件test.h 在頭文件開頭寫上兩行&#xff1a;#ifndef _TEST_H#define _TEST_H// 文件名的大寫#endif頭文件結尾寫上一行&#xff1a;#endif這樣做是為…

【c】【報錯解決】incompatible implicit declaration

【報錯解決】incompatible implicit declaration 背景; 1.自己封裝的函數wrap.c包含&#xff1a; #include "wrap.h"2.主函數調用如下&#xff1a; #include <stdio.h> #include <stdlib.h> ... #include <errno.h> #include "wrap.h"…

【ubuntu】vim語法高亮設置無效

如果你的.vimrc配置了語法高亮&#xff0c;但是你的vim沒實現&#xff0c;可能你的vim是vim-tiny的黑白版本&#xff0c;你需要vim-gnome這個帶GUI的彩色版本。 apt-get update apt-get upgrade apt-get install vim-gnome reboot打開vi就能看到彩色啦

__attribute__機制介紹

1. __attribute__ GNU C的一大特色&#xff08;卻不被初學者所知&#xff09;就是__attribute__機制。 __attribute__可以設置函數屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute) __attribute__前后都有兩個下劃線&#xff0c;并且后面會緊…

【git】git基本操作命令

1.建立本地倉庫 git config --global user.name "lora" git config --global user.email "xxxgmail.com"2.建立目錄 mkdir xxx3.初始化 cd xxx //進入目錄 git init //初始化4.將代碼上傳至本地緩存區 git add . //上傳全部 git add 文件名 //…

【git】解決gitlab ip更改問題

有時候因為部署gitlab虛擬機的ip發生變化&#xff0c;gitlab的clone地址沒有同時更新到新的ip&#xff0c; 這導致后續clone報錯&#xff0c;解決辦法如下&#xff1a; 進入部署gitlab的主機&#xff1a; sudo vim /opt/gitlab/embedded/service/gitlab-rails/config/gitlab.…