Here is some examples of how to use std::vector with string for most of the common operations that can be performed on std::vector.
The following example assume the following has been declared
std::vector<std::string> vec;
Adding Items
vec.push_back("Item 1");
vec.push_back("Item 2");
vec.push_back("Item 3");
vec.push_back("Item 4");
vec.push_back("Item 5");
Adding Items to front
vec.insert(vec.begin(), "Front 2");
vec.insert(vec.begin(), "Front 1");
Remove Last Item
vec.pop_back();
Remove Last Item
vec.erase(vec.end());
Remove First Item
vec.erase(vec.begin());
Process All Items
for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
printf("%s\n", it->c_str());
}
Process All Items
for(size_t i = 0; i < vec.size(); i++)
{
printf("%s\n", vec[i].c_str());
}
Reverse The Order - Note you can also just run the above backwards instead.
for(size_t i = 0; i < vec.size() / 2; i++)
{
std::string tmp = vec[i];
vec[i] = vec[vec.size() - i - 1];
vec[vec.size() - i - 1] = tmp;
}
Sorting
std::sort(vec.begin(), vec.end());
Find and Remove an item
for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); it++)
{
if (*it == "Item 2")
{
vec.erase(it);
break; //it is now invalud must break!
}
}
Clear All Items
vec.clear();