您好,登錄后才能下訂單哦!
本篇文章為大家展示了利用c++怎么實現一個前后自增的操作,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
class Integer { public: // ++i first +1,then return new value Integer &operator++() { value_ += 1; return *this; } // i++ first save old value,then +1,last return old value Integer operator++(int) { Integer old = *this; value_ += 1; return old; } private: int value_; };
#include <iostream> #include <vector> #include <windows.h> int main() { const int sizeInt = 0x00fffffe; const int sizeVec = 0x000ffffe; LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); { int* testValue = new int[sizeInt]; LARGE_INTEGER start; LARGE_INTEGER stop; QueryPerformanceCounter(&start); for (int i = 0; i < sizeInt; ++i) { testValue[i]++; } QueryPerformanceCounter(&stop); const auto interval = static_cast<double>(stop.QuadPart - start.QuadPart); const auto timeSpan = interval / frequency.QuadPart * 1000.0; //ms std::cout << "i++ " << sizeInt << " times takes " << timeSpan << "ms." << std::endl; delete[] testValue; } { int* testValue = new int[sizeInt]; LARGE_INTEGER start; LARGE_INTEGER stop; QueryPerformanceCounter(&start); for (int i = 0; i < sizeInt; ++i) { ++testValue[i]; } QueryPerformanceCounter(&stop); const auto interval = static_cast<double>(stop.QuadPart - start.QuadPart); const auto timeSpan = interval / frequency.QuadPart * 1000.0; //ms std::cout << "++i " << sizeInt << " times takes " << timeSpan << "ms." << std::endl; delete[] testValue; } { const std::vector<int> testVec(sizeVec); LARGE_INTEGER start; LARGE_INTEGER stop; QueryPerformanceCounter(&start); for (auto iter = testVec.cbegin(); iter != testVec.cend(); iter++) { } QueryPerformanceCounter(&stop); const auto interval = static_cast<double>(stop.QuadPart - start.QuadPart); const auto timeSpan = interval / frequency.QuadPart * 1000.0; //ms std::cout << "iterator++ " << sizeVec << " times takes " << timeSpan << "ms." << std::endl; } { const std::vector<int> testVec(sizeVec); LARGE_INTEGER start; LARGE_INTEGER stop; QueryPerformanceCounter(&start); for (auto iter = testVec.cbegin(); iter != testVec.cend(); ++iter) { } QueryPerformanceCounter(&stop); const auto interval = static_cast<double>(stop.QuadPart - start.QuadPart); const auto timeSpan = interval / frequency.QuadPart * 1000.0; //ms std::cout << "++iterator " << sizeVec << " times takes " << timeSpan << "ms." << std::endl; } return 0; }
從上面的執行結果可以看出來,對int類型的測試中前自增和后自增耗費時間基本不變;而對std::vector中iterator的測試顯示,前自增所耗費的時間幾乎是后自增的一半。這是因為,在后自增的操作中,會首先生成原始對象的一個副本,然后將副本中的值加1后返回給調用者,這樣一來每執行一次后自增操作,就會增加一個對象副本,效率自然降低了。
因此可以得出結論:對于C++內置類型的自增而言,前自增、后自增的效率相差不大;對于自定義類型(類、結構體)的自增操作而言,前自增的效率幾乎比后自增大一倍。
上述內容就是利用c++怎么實現一個前后自增的操作,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。