How to get an Iterator to the end of Capacity.

Jan 22, 2016 at 4:18pm
Hi!
Suppose I reserve(X) for a std::vector. Is there a natural way to get an Iterator pointing to the end of its capacity? So that e.g. I can fill up all the elements with a for loop:

std::vector<int> Myvect;
std::vector<int>::iterator Iter;
Myvect.reserve(30);
for (Iter=Myvect.begin(); Iter!=/*THE ITERATOR TO THE END OF CAPACITY;Iter++)
std::cin>>*Iter



I understad that I can get Iterators for the end of the SIZE through Myvect.end(). But I cant find a solution for this problem.
Jan 22, 2016 at 4:26pm
closed account (E0p9LyTq)
You have the method to get an iterator to the beginning of a vector, simply use the method to get an iterator to the end:

http://www.cplusplus.com/reference/vector/vector/end/

for (Iter = Myvect.begin(); Iter != Myvect.end(); Iter++)


You need to push_back each element you want to add. A vector's capacity is not an indication of the actual number of stored elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>

int main()
{
   const int number_of_elements = 30;
   std::vector<int> myVector;
   
   myVector.reserve(number_of_elements);
   
   for (int i = 0; i < number_of_elements; i++)
   {
      int element;
      std::cout << "Element #" << i << ": ";
      std::cin >> element;
      
      myVector.push_back(element);
   }
}
Last edited on Jan 22, 2016 at 4:50pm
Jan 22, 2016 at 4:30pm
Your example would cause undefined behavior. You can't write to memory locations past the size() of the vector, even you already reserved that much capacity.
Jan 22, 2016 at 4:45pm
closed account (E0p9LyTq)
@helios, yeah, you're right. lack of coffee and being stupid on my part.
Jan 22, 2016 at 5:38pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

void fill_reserve(std::vector<int>& v, std::istream& in)
{
    std::copy_n(std::istream_iterator<int>(in), v.capacity() - v.size(), std::back_inserter(v));
}

int main()
{
    std::vector<int> Myvect;
    std::vector<int>::iterator Iter;
    Myvect.reserve(30);

    fill_reserve(Myvect, std::cin);
}


Of course, you might want to make sure capacity isn't already bigger than what you're reserving or this might have some unexpected results, depending on how you're using it.

From my perspective, something like the following would probably be more useful (and safe.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

void extract(std::istream& in, std::vector<int>& v, std::size_t n)
{
    v.reserve(v.size() + n);
    std::copy_n(std::istream_iterator<int>(in), n, std::back_inserter(v));
}

int main()
{
    std::vector<int> Myvect;
    std::vector<int>::iterator Iter;

    extract(std::cin, Myvect, 30);
}
Last edited on Jan 22, 2016 at 5:44pm
Topic archived. No new replies allowed.