Respond to both discussion posts about vector containers discussing how to manipulate data stored in a vector container.

Describe your rights and remedies for the damages caused by the government’s delay.
August 5, 2017
Create a communication plan for disseminating your action plan to all of the stakeholders.
August 5, 2017
Show all

Respond to both discussion posts about vector containers discussing how to manipulate data stored in a vector container.

Respond to both discussion posts about vector containers discussing how to manipulate data stored in a vector container.

From John:

Vectors from the C++ STL are much like arrays, but much more convenient. Unlike arrays, you don’t have to specify the size of the array before hand. There are many methods to manipulate the data in a vector:

  • push_back: appends an item to the end of the vector
  • pop_back: removes and returns the item at the end of the vector
  • at, []: returns the item at the specified index
  • begin: returns an iterator to the beginning of the vector
  • end: returns an iterator to the end of the vector
  • rbegin: returns a reverse iterator to the end of the vector (reverse beginning)
  • rend: returns a reverse iterator to the beginning of the vector (reverse end)
  • size: returns the size of the vector
  • clear: empty the vector

You can iterate through a vector using a standard for loop (with an indexor). For example:

for (int i = 0; i < myVector.size(); i++) {

auto item = myVector.at(i);

}

Or, I prefer to iterate over vectors using begin and end:

for (auto i = myVector.begin(); i != myVector.end(); i++) {

auto item = (*i);

}

Using the iterator methods is particularly useful for iterating through the vector in reverse:

for (auto i = myVector.rbegin(); i != myVector.rend(); i++) {

auto item = (*i);

}

And, using std::sort we can easily sort the items of a vector:

vector<RomanType> myVector;

myVector.push_back(RomanType(“MCM”)); &nbsp; &nbsp; // 1900

myVector.push_back(RomanType(“CCCLIX”)); &nbsp;// &nbsp;359

myVector.push_back(RomanType(“MDCLXVI”)); // 1666

sort(myVector.begin(), myVector.end(), [](RomanType a, RomanType b) {

return a.toInt() < b.toInt();

});

for (auto i = myVector.begin(); i != myVector.end(); i++) {

cout << (*i).toString() << endl;

}

Leave a Reply

Your email address will not be published. Required fields are marked *