I'm implementing a simple std::vector
. There are two insert
functions:
template <typename T, typename Allocator>
typename Vector<T, Allocator>::iterator
Vector<T, Allocator>::insert(const_iterator pos, size_type count, const T& value)
{
checkIterator(pos);
auto p = const_cast<iterator>(pos);
if (count == 0) {
return p;
}
for (size_type i = 0; i < count; ++i) {
p = insert(p, value);
}
return p;
}
template <typename T, typename Allocator>
template <typename InputIt>
typename Vector<T, Allocator>::iterator
Vector<T, Allocator>::insert(const_iterator pos, InputIt first, InputIt last)
{
checkIterator(pos);
auto p = const_cast<iterator>(pos);
if (first == last) {
return p;
}
for (auto iter = first; iter != last; ++iter) {
p = insert(p, *iter);
++p;
}
return p - (last-first);
}
But when I want to use first insert
function, the compiler invokes the second one:
Vector<int> vi = {1, 2, 3};
vi.insert(vi.begin(), 3, 4); // get compile error, using insert(const_iterator pos, InputIt first, InputIt last).
Why compiler chooses the second function, and how to modify my code to make it right?