I have this vector of names:
vector <string> names;
names.push_back("William");
names.push_back("Maria");
names.push_back("Petterson");
names.push_back("McCarthy");
names.push_back("Jose");
names.push_back("Pedro");
names.push_back("Hang");
I need to display this vector IN ORDER using a reverse iterator.
This is my attempt:
//Define a reverse iterator for the vector object
vector<string>::reverse_iterator itR = names.rend();
itR = itR - 1;
//Use the reverse iterator to display each element in the vector
cout << "\tNames:\n";
while (itR != names.rbegin())
{
cout << *itR << endl;
itR--;
}
This will display all names in correct order BUT it cuts off "Hang" at the end, any tips?
CodePudding user response:
If you go from the end of a range to the beginning, you should check the equality first and then decrement inside the loop body. Otherwise there either is no iteration for the last element or the iterator gets decremented past the end resulting in undefined behaviour. You could use the following loop:
// print elements in original (= non-reversed) order
for (auto pos = names.rend(); pos != names.rbegin();)
{
--pos;
std::cout << *pos << std::endl;
}
CodePudding user response:
The condition of the while statement
while (itR != names.rbegin())
prevents to output the element of the vector pointed to by the iterator names.rbegin()
.
Consider for example a vector that contains only one element. In this case after this statement
itR = itR - 1;
the iterator itR
will be equal to names.rbegin()
and the loop will be skipped.
Also it is unclear why you are starting to output the vector starting from the iterator names.rend() - 1
using the reverse iterator.
Either use original iterators or if you want to output the vector in the reverse order then write
//Use the reverse iterator to display each element in the vector
cout << "\tNames:\n";
for ( auto first = names.rbegin(), last = names.rend(); first != last; first )
{
cout << *first << endl;
}
Otherwise at least change your code like
//Define a reverse iterator for the vector object
vector<string>::reverse_iterator itR = names.rend();
//Use the reverse iterator to display each element in the vector
cout << "\tNames:\n";
while (itR != names.rbegin())
{
cout << *--itR << endl;
}