Lab #1 Using
a vector of strings to store a source code program
Refresh your memory by reading
the related sections in C++ Primer and the online MSDN document on the member functions of STL
vector class. Create a C++
project and in the main function to work on the vector class to do things as
described in the following.
Task #1: Manually store 3 lines of source code in a vector of strings
- Declare a vector of strings and name it myVect. Use
the push_back
method of the vector class to store the following three strings into myVect:
- "radius=2; ",
- "area=3.14*radius*radius;" and
- "display area;"
.
Task #2: Assess the elements by their indices
- Write a loop to display all the elements myVect[i] in myVect one
by one.
Task #3: Assess the elements using an iterator
- Write a loop using a vector<string>::iterator iterator to iterate through the vector myVect and to
display all the elements in myVect one by one.
Task #4: Use an iterator to delete some contents
- Call the erase method to delete the second element in myVect. (i.e. delete myVect[1] from the vector)
- Check the new contents: Write a loop using a vector<string>::iterator
iterator to iterate through the vector myVect and to
display all the elements in myVect one by one.
Task #5: Use an iterator to insert new contents
- Call the insert
method of the vector class to insert a new string "display
radius;" right before the element currently holding "display
area;" in myVect.
- Check the new contents: Write a loop using a vector<string>::iterator
iterator to iterate through the vector myVect and to
display all the elements in myVect one by one.
Task #6: Clear the contents of the entire vector
- Call the clear method
to clear the vector myVect into an empty vetor.
- Check the new contents: Write a loop using a vector<string>::iterator
iterator to iterate through the vector myVect and to
display all the elements in myVect one by one.
Task #7: Use getline to read an arbitrary number of lines of source code into a vector of strings
- Declare a string object s and then write a loop which on each iteration (i) calls
getline(cin, s) to read in a line into s,
(ii) if the contents of s is neither an empty string nor the
special string ".", calls the push_back method to store it in the end of
the vector myVect,and
(iii) the loop will terminate if
the contents of s is special
string "."
- Check the new contents: Write a loop using a vector<string>::iterator
iterator to iterate through the vector myVect and to
display all the elements in myVect one by one.