简体   繁体   中英

Assign vector address to iterator

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(?)

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.

The main way to get an iterator is to use one of:

std::vector<int>::begin()
std::vector<int>::end()
std::vector<int>::rbegin()
std::vector<int>::rend()

In your case:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM