Is it possible to resize a vector using iterator

I want to ask if it is possible to resize on a vector itertor, in order to get such a vector resized?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>     // std::cout
#include <iterator>     // std::distance
#include <vector>         // std::vector

int main () {
  std::vector<int> myvector;
//   for (int i=0; i<10; i++) myvector.push_back (i*10);
  myvector.reserve(100);

  std::vector<int>::iterator first = myvector.begin();
  std::vector<int>::iterator last = myvector.end();
  
  std::cout << "The distance is: " << std::distance(first,last) << '\n';  // 0
  
  /// I want to do this == myvector.resize(100);
  /// THIS LINE DOESNOT WORK
  (*first).resize(100);

  return 0;
}
Last edited on
Dereferencing an iterator is like dereferencing a pointer to an element; it gives you the item in the vector (e.g. *first will get you myvector[0]).

So the short answer is no, you can't use a vector's iterator to access the vector object itself.

In addition, please note that vector.resize() can invalidate iterators.
http://www.cplusplus.com/reference/vector/vector/resize/
In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call.

If the container expands, the end iterator is invalidated and, if it has to reallocate storage, all iterators, pointers and references related to this container are also invalidated.


http://www.cplusplus.com/reference/iterator/iterator/

_________________________________________________

With questions like these... it's really more helpful to ask what you're actually trying to do accomplish.

For example, you can pass a vector by reference if you want another part of the code to be able to resize it. (Again, note that resizing a vector can invalidate iterators)

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

void froob(std::vector<int>& intvec)
{
    intvec.resize(100);
}

int main () {
  std::vector<int> vec = { 11, 22, 33, 44, 55 };
  std::cout << vec.size() << '\n';
  froob(vec);
  std::cout << vec.size() << '\n';
  return 0;
}
Last edited on
*first isnt a vector, its an int. ^^^ explicitly stating what he said in first line there.

also consider
vector<int> invec[100];
invec[97] = 99; //ok

it looks like that is what you want (a fixed size?). Its not hard-fixed (pushback etc will grow it) but if you don't do anything to make it change, it will behave mostly like int invec[100] would.
Topic archived. No new replies allowed.