Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. In the program max.cpp is a section of code which declares a list of strings.

ID: 3628675 • Letter: 1

Question

1. In the program max.cpp is a section of code which declares a list of strings. Write code that will position an iterator that starts at “Dave” and output the list elements (all the list elements) in reverse order.

#include <iostream>
#include <list>
#include <string>

using namespace std;

int main()
{

// initialize a list of strings
string str[] = { "Joe", "Glenn", "Dave", "Bret", "Bryce", "Heather"};
int strSize = sizeof(str)/sizeof(string);
list<string> strList2(str, str+strSize);

// use iterator and start to move backward in strList
list<string>::iterator iter, start;

// ADD YOUR LOGIC HERE
// position iter at the starting list element ("Dave")


// output list elements moving backward until we arrive back at start


cout << endl;

return 0;
}

Explanation / Answer

#include <iostream>

#include <string>#include <list>
using namespace std;


int main(){

// initialize a list of strings

string str[] = { "Joe", "Glenn", "Dave", "Bret", "Bryce", "Heather"};

int strSize = sizeof(str)/sizeof(string); list<string> strList(str, str+strSize);

// use iterator and start to move backward in strList

list<string>::iterator iter, start;


// position iter at the 3rd list element

iter = strList.begin();

iter++;

iter++;

// record the iterator value

start = iter;
// output list elements moving backward

// until we arrive back at start

do

{

cout << *iter << " ";


iter--;

// if we are at strList.end(), move to the back

// of the list

if (iter == strList.end())

iter--;

}

while (iter != start);

cout << endl;

system("pause");

return 0;

}