Skip to content

Commit 126d03d

Browse files
committed
Implement vector constructor to support single-pass input iterator range
1 parent f86437e commit 126d03d

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

MyTinySTL/vector.h

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,17 @@ class vector
8080
{ fill_init(n, value); }
8181

8282
template <class Iter, typename std::enable_if<
83-
mystl::is_input_iterator<Iter>::value, int>::type = 0>
83+
mystl::is_exactly_input_iterator<Iter>::value, int>::type = 0>
84+
vector(Iter first, Iter last)
85+
{
86+
try_init();
87+
for (; first != last; ++first) {
88+
emplace_back(*first);
89+
}
90+
}
91+
92+
template <class Iter, typename std::enable_if<
93+
mystl::is_forward_iterator<Iter>::value, int>::type = 0>
8494
vector(Iter first, Iter last)
8595
{
8696
MYSTL_DEBUG(!(last < first));

Test/vector_test.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44
// vector test : 测试 vector 的接口与 push_back 的性能
55

6-
#include <vector>
6+
#include <vector>
77

88
#include "../MyTinySTL/vector.h"
99
#include "test.h"
10+
#include "stream_iterator.h" // 用于测试 input_iterator 迭代器版构造函数
1011

1112
namespace mystl
1213
{
@@ -32,7 +33,6 @@ void vector_test()
3233
v8 = v3;
3334
v9 = std::move(v3);
3435
v10 = { 1,2,3,4,5,6,7,8,9 };
35-
3636
FUN_AFTER(v1, v1.assign(8, 8));
3737
FUN_AFTER(v1, v1.assign(a, a + 5));
3838
FUN_AFTER(v1, v1.emplace(v1.begin(), 0));
@@ -90,6 +90,12 @@ void vector_test()
9090
FUN_AFTER(v1, v1.shrink_to_fit());
9191
FUN_VALUE(v1.size());
9292
FUN_VALUE(v1.capacity());
93+
94+
std::istringstream is("1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9");
95+
mystl::istream_iterator<int> beg{is}, end;
96+
mystl::vector<int> v11{beg, end};
97+
COUT(v11);
98+
9399
PASSED;
94100
#if PERFORMANCE_TEST_ON
95101
std::cout << "[--------------------- Performance Testing ---------------------]\n";

0 commit comments

Comments
 (0)