Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Summary

I've barely scratched the surface of what you can do with vectors and container classes. For example, you can create a vector that holds something other than integers. The type vector<string> would hold strings. You can also insert an item into a vector. To do so, you create an iterator, point the iterator to the position where you want to insert the item, and then call insert. Here's a quick example you can try; add this to the preceding example after the last push_back call:

vector<int>::iterator pos = storage.begin() + 2;
storage.insert(pos, 5);

But you can use more than just vectors. One handy container is the map container. A map is like a vector except that the indexes don't have to be integers. They can be some type that you specify when you create the map. Here's a quick example you can try. First, add this line to your includes:

#include <map>

And then try this:

map<string, int> mymap;
mymap["Jeff"] = 35;
mymap["Amy"] = 31;
cout << mymap["Amy"] << endl;

This creates a map that uses strings for its indexes, and it holds integers.

Once you get the swing of containers, you'll find that anytime you need any kind of storage, you'll automatically think of them and skip the lower-level containers such as arrays altogether. Have fun!

  • + Share This
  • 🔖 Save To Your Account