獲取一塊臨時記憶體,在C ++ STL庫中,有一個函式get_temporary_buffer,該函式主要用于獲取臨時塊,
該函式的大小為n,并回傳最大大小為n的可用緩沖區,該緩沖區可以裝入物理記憶體,
此函式用于獲取臨時性質的記憶體,該記憶體主要用于演算法的操作,因為某些演算法需要額外的空間才能正確執行,
一旦不再需要分配的存盤塊,則應通過呼叫return_temporary_buffer將其釋放,

?
句法:
pair(int*, ptrdiff_t) p = get_temporary_buffer(int)(required size)
引數:
n:為其分配了臨時記憶體的T型元素的數量,
ptrdiff_t:它是整數型別,
回傳值:該函式回傳第一對和第二對物件,分配記憶體后,第一個包含指向塊中第一個元素的指標,第二個包含指向大小的指標,如果未分配記憶體塊,則第一對包含空指標,第二對包含零,
示例1:
要計算陣列中的偶數總數并使用get_temporary_buffer列印排序后的陣列

// CPP code to demonstrate the get_temporary_buffer // to sort an array #include <iostream> #include <algorithm> #include <memory> using namespace std; void sorting(int b[], int n) { int i, c = 0; for (i = 0; i < n; i++) { if (b[i] % 2 == 0) { c++; } } cout << "The total even numbers are: " << c << endl; cout << "original array :" << " "; cout << "\n"; for (i = 0; i < 10; i++) { cout << b[i] << " "; } cout << "\n"; pair<int*, ptrdiff_t> p = get_temporary_buffer<int>(10); // copy the contents in temporary buffer with pair uninitialized_copy(b, b + p.second, p.first); sort(p.first, p.first + p.second); cout << "sorted array :" << endl; for (i = 0; i < p.second; i++) { cout << p.first[i] << " "; } } // driver program to test above function int main() { int b[] = { 8, 9, 2, 1, 10, 14, 37, 18, 17, 5 }; int n = sizeof(b) / sizeof(b[0]); sorting(b, n); return 0; }
輸出:
偶數總數為:5個
原始陣列:8 9 2 1 10 14 37 18 17 5
排序陣列:1 2 5 8 9 10 14 17 18 37
示例2:
使用get_temporary_buffer和return_temporary_buffer按字母順序對字串進行排序
// CPP code to sort the characters // alphabetically using std::get_temporary_buffer #include <iostream> #include <algorithm> #include <memory> #include <string.h> using namespace std; void sorting(char b[], int n) { int i; pair<char*, ptrdiff_t> p = get_temporary_buffer<char>(n); // copy the contents in temporary buffer with pair uninitialized_copy(b, b + p.second, p.first); // sort char array sort(p.first, p.first + p.second); cout << "sorted characters are :" << endl; for (i = 0; i < p.second; i++) { cout << p.first[i] << " "; } // to release the temporary buffer return_temporary_buffer(p.first); } // driver program to test above function int main() { char str[] = { 'b', 'g', 'y', 'v', 'p' }; int c; c = strlen(str); sorting(str, c); return 0; }
輸出:
排序的字符是:bgpvy
應用:演算法通常需要臨時空間才能正確執行,它具有非常特殊的用途,STL在內部使用這些演算法來處理諸如stable_partition,stable_sort和inplace_merge之類的演算法,它們使用額外的臨時記憶體來存盤中間結果,并且如果有額外的記憶體可用,它們的運行時復雜性會更好,
每天學點小知識,希望對你有幫助~
另外如果你想更好的提升你的編程能力,學好C語言C++編程!彎道超車,快人一步!筆者這里或許可以幫到你~
C語言C++編程學習交流圈子【點擊進入】微信公眾號:C語言編程學習基地
分享(原始碼、專案實戰視頻、專案筆記,基礎入門教程)
歡迎轉行和學習編程的伙伴,利用更多的資料學習成長比自己琢磨更快哦!
編程學習視頻分享:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/273105.html
標籤:C++
上一篇:題目:從鍵盤輸入五個整數,把這五個數放在一個陣列中,輸入最小值和最大值以及他們的下標。
下一篇:C語言記憶體管理
