4.3. Storing Strings in a Sequence
Problem
You want to store a set of strings in a sequence that looks and feels like an array.
Solution
Use a vector for array-like storage of
your strings. Example 4-6 offers a
simple example.
Example 4-6. Store strings in a vector
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<string> v;
string s = "one";
v.push_back(s);
s = "two";
v.push_back(s);
s = "three";
v.push_back(s);
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << '\n';
}
}vectors follow array semantics for random access
(they also do a lot more), so they are easy and familiar to use. vectors are just one of many sequences in the standard library, however; read
on for more of this broad subject.
Discussion
A vector is a dynamically sized sequence of objects
that provides array-style operator[] random access. The
member function push_back copies its argument via copy
constructor, adds that copy as the last item in the vector, and increments its size by
one. pop_back does the exact opposite, by removing the
last element. Inserting or deleting items from the end of a vector takes amortized
constant time, and inserting or deleting from any other location takes linear time. These
are the basics of vectors. There is a lot more to them.
In most cases, a vector should be your first choice over a C-style array. First of all, they are dynamically sized, which means they can grow as needed. You don’t have to do all sorts of research to figure out ...