Skip to content

Commit

Permalink
Implement vector constructor to support single-pass input iterator range
Browse files Browse the repository at this point in the history
  • Loading branch information
winner245 committed Oct 28, 2024
1 parent f86437e commit 126d03d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 11 additions & 1 deletion MyTinySTL/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,17 @@ class vector
{ fill_init(n, value); }

template <class Iter, typename std::enable_if<
mystl::is_input_iterator<Iter>::value, int>::type = 0>
mystl::is_exactly_input_iterator<Iter>::value, int>::type = 0>
vector(Iter first, Iter last)
{
try_init();
for (; first != last; ++first) {
emplace_back(*first);
}
}

template <class Iter, typename std::enable_if<
mystl::is_forward_iterator<Iter>::value, int>::type = 0>
vector(Iter first, Iter last)
{
MYSTL_DEBUG(!(last < first));
Expand Down
10 changes: 8 additions & 2 deletions Test/vector_test.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@

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

#include <vector>
#include <vector>

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

namespace mystl
{
Expand All @@ -32,7 +33,6 @@ void vector_test()
v8 = v3;
v9 = std::move(v3);
v10 = { 1,2,3,4,5,6,7,8,9 };

FUN_AFTER(v1, v1.assign(8, 8));
FUN_AFTER(v1, v1.assign(a, a + 5));
FUN_AFTER(v1, v1.emplace(v1.begin(), 0));
Expand Down Expand Up @@ -90,6 +90,12 @@ void vector_test()
FUN_AFTER(v1, v1.shrink_to_fit());
FUN_VALUE(v1.size());
FUN_VALUE(v1.capacity());

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");
mystl::istream_iterator<int> beg{is}, end;
mystl::vector<int> v11{beg, end};
COUT(v11);

PASSED;
#if PERFORMANCE_TEST_ON
std::cout << "[--------------------- Performance Testing ---------------------]\n";
Expand Down

0 comments on commit 126d03d

Please sign in to comment.