本篇文章为大家展示了利用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。