From 3d7af2820f1c00944313cbf386d2c494f64ce592 Mon Sep 17 00:00:00 2001 From: jiangtao Date: Sun, 29 Nov 2015 21:53:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dinser=5Faux=E4=B8=AD=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E7=9A=84=E5=86=85=E5=AD=98=E6=B3=84=E6=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98.=E5=A2=9E=E5=8A=A0=E6=B5=8B=E8=AF=95=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 插入点之后的元素后撤需要考虑两种情况,1. 只需要调用operator ==(在元素和元素之间)2, 需要调用constructor (在元素移动到裸内存上的时候). --- TinySTL/Detail/Vector.impl.h | 14 +++++++----- TinySTL/Test/VectorTest.cpp | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/TinySTL/Detail/Vector.impl.h b/TinySTL/Detail/Vector.impl.h index d2cb2e8..e2d26ef 100644 --- a/TinySTL/Detail/Vector.impl.h +++ b/TinySTL/Detail/Vector.impl.h @@ -144,12 +144,16 @@ namespace TinySTL{ difference_type locationNeed = distance(first, last);//last - first; if (locationLeft >= locationNeed){ - iterator tempPtr = end() - 1; - for (; tempPtr - position >= 0; --tempPtr){//move the [position, finish_) back - //*(tempPtr + locationNeed) = *tempPtr;//bug - construct(tempPtr + locationNeed, *tempPtr); + if (finish_ - position > locationNeed){ + TinySTL::uninitialized_copy(finish_ - locationNeed, finish_, finish_); + std::copy_backward(position, finish_ - locationNeed, finish_); + std::copy(first, last, position); + } + else{ + iterator temp = TinySTL::uninitialized_copy(first + (finish_ - position), last, finish_); + TinySTL::uninitialized_copy(position, finish_, temp); + std::copy(first, first + (finish_ - position), position); } - TinySTL::uninitialized_copy(first, last, position); finish_ += locationNeed; } else{ diff --git a/TinySTL/Test/VectorTest.cpp b/TinySTL/Test/VectorTest.cpp index 514b522..f478340 100644 --- a/TinySTL/Test/VectorTest.cpp +++ b/TinySTL/Test/VectorTest.cpp @@ -186,7 +186,48 @@ namespace TinySTL{ assert(!(foo == bar)); assert(foo != bar); } + + class TestItem + { + public: + TestItem() + { + ++count; + } + TestItem(const TestItem & other) + { + ++count; + } + virtual ~TestItem() + { + --count; + } + + static int getCount() + { + return count; + } + private: + static int count; + }; + int TestItem::count = 0; + + void testCase15() + { + assert(TestItem::getCount() == 0); + { + typedef TinySTL::vector TVector; + TVector t(10); + t.push_back(TestItem()); + t.push_back(TestItem()); + t.push_back(TestItem()); + t.insert(t.begin(), t.begin(), t.begin() + 1); + + } + assert(TestItem::getCount() == 0); + + } void testAllCases(){ testCase1(); @@ -203,6 +244,7 @@ namespace TinySTL{ testCase12(); testCase13(); testCase14(); + testCase15(); } } } \ No newline at end of file -- GitLab