In the C++11 standard, Section 23.3.6.2 [vector.cons], the following is said:
template <class InputIterator>
vector(InputIterator first, InputIterator last,
const Allocator& = Allocator());
9 Effects: Constructs a vector equal to the range
[first,last)
, using the specified allocator.
10 Complexity: Makes only N calls to the copy constructor of T (where N is the distance betweenfirst
andlast
) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order log(N) reallocations if they are just input iterators.
(this text exists in the older standard as well). On one hand, it does not require that dereferencing an InputIterator
should result in a value of the same type that is stored in the vector. On the other hand, it tells about using copy constructors, which sort of implies the same type.
My question is: is it valid to use a sequence of elements of different type with this constructor, provided that conversion between types is possible? References to the standard are desirable.
For example, the following code works fine at ideone. Is it guaranteed by the standard, or does just GCC happen to allow it?
#include <vector>
#include <iostream>
struct A {
int n;
A(int n_) : n(n_) {}
};
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9,10};
std::vector<int> int_vec(arr, arr+10);
std::vector<A> A_vec(int_vec.begin(), int_vec.end());
for( std::vector<A>::iterator it=A_vec.begin(); it!=A_vec.end(); ++it )
std::cout<< it->n <<" ";
std::cout<<std::endl;
}
See Question&Answers more detail:os