Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign vector address to iterator

Tags:

c++

vector

I'd like the vector iterator to point to a vector element. I have

#include <iostream>
#include <vector>

int main() {
  std::vector<int> vec = {1,2,3,4,5};
  std::vector<int>::iterator it;

  // want "it" to point to the "3" element, so something like
  //   it = &prices[2];
  //   it = &prices.at(2);

}

but neither of these attempts work. I guess I need some vector function that returns an iterator, instead of an address(?)

like image 425
bcf Avatar asked Jan 20 '15 17:01

bcf


People also ask

How do you assign a value to iterator?

Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements). To assign the value of the element the iterator is pointing at, dereference the iterator first, then use the assign operator.

How do you access a vector element with iterator?

Use an iteratorvector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence. To access the value in the memory space to which the iterator is pointing, you must use * .

How do you assign a vector in C++?

CPP. The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.

What is iterator vector C++?

An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.


1 Answers

neither of these attempts work

Indeed, you can't create a container iterator from a pointer to a container element. You can only get them from the container itself.

I guess I need some vector function that returns an iterator

Yes, begin() returns an iterator to the first element. Increment that to refer to whichever element you want. For the third,

it = vec.begin() + 2;

or, more generally,

it = std::next(std::begin(container), 2);

which works even if the container isn't random-access.

like image 79
Mike Seymour Avatar answered Sep 17 '22 18:09

Mike Seymour