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(?)
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.
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 * .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With