Reputation: 195
In my practice program there is a vector, which needs to be partly reversed. So for example
vector<int> nums;
for(int i = 0; i < 10; i++) {nums.push_back(i)}
#than I would want to reverse it somewhat like this
std::reverse(nums.location(3), nums.location(5))
This should than make nums look like this: 0 1 4 3 2 5 6 7 8 9. Obviously nums.location() isn't a real method.
Upvotes: 1
Views: 138
Reputation: 4359
You can accomplish this through the use of iterators
. An iterator can be imagined as an object specialized to move around the container it came from.
std::vector::begin
returns an iterator to the first element of a vector, and will thus behave as a pointer to the first element of the vector. To access it, you dereference the iterator:
auto value_at_first_element = *(v.begin());
To move onto the next element, you increment the iterator:
auto iter_to_second_element = ++(v.begin());
auto value_at_second_element = *iter_to_second_element;
It's worth noting that not all iterators behave the same way, and can be split into categories. Most have their own functionality limited by the limitations of their container. The prime example of this is std::forward_list
, whose iterator can only move forward through a call to the ++
operator.
Study the following solution to your problem, and try to build some intuition on iterators. Iterators are very powerful and are the cornerstone of algorithms in C++.
// If you know the positions already...
std::reverse(nums.begin() + 2, nums.begin() + 5);
// If you need to _find_ the positions...
std::reverse(
std::find(nums.begin(), nums.end(), 2)
, std::find(nums.begin(), nums.end(), 5)
);
Upvotes: 2