I am trying to create a stl vector from iterator pair and I am not sure how many elements the vector might have. It could have only one element.
#include <iostream>
#include <vector>
int main()
{
using namespace std;
vector<int> vect;
for (int nCount=0; nCount < 6; nCount++)
vect.push_back(nCount);
vector<int> second(vect.begin(), vect.begin() );
vector<int>::iterator it; // declare an read-only iterator
it = second.begin(); // assign it to the start of the vector
while (it != second.end()) // while it hasn't reach the end
{
cout << *it << " "; // print the value of the element it points to
it++; // and iterate to the next element
}
cout << endl;
}
I thought that vector 'second' would have one element pointed by vect.begin(). Is it not the case?
Thanks
vector<int> second(vect.begin(), vect.begin() + 1);
The vector constructor uses an open interval so the end is not included ie. [first, last)
As lip pointed out in his comment it's more generic to next
:
second(vect.begin(), next(vect.begin()));
No, this is not the case. The documentation is pretty clear:
template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)
4) Constructs the container with the contents of the range [first, last).
The notation "[first, last)" indicates that all the elements between first
and last
but not including last
are copied. Since first
== last
, no elements are copied.
Reading the documentation further, it would appear that you can use another constructor:
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator()); (until C++11)
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator()); (since C++11)
...in this way:
vector<int> second(1, vect.front());
No. In the constructor vector<int> second(vect.begin(), vect.begin());
the second iterator should point past the end, so you get exactly empty array.
Example: vect.end()
points exactly past the end of vector vect
, so vector<int> second(vect.begin(), vect.end());
would copy the whole vect
into second
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.