Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

6.1. Using vectors Instead of Arrays

Problem

You have to store things (built-in types, objects, pointers, etc.) in a sequence, you require random access to elements, and you can’t be confined to a statically sized array.

Solution

Use the standard library’s vector class template, which is defined in <vector>; don’t use arrays. vector looks and feels like an array, but it has a number of safety and convenience advantages over arrays. Example 6-1 shows a few common vector operations.

Example 6-1. Using common vector member functions

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {

   vector<int>    intVec;
   vector<string> strVec;

   // Add elements to the "back" of the vector with push_back
   intVec.push_back(3);
   intVec.push_back(9);
   intVec.push_back(6);

   string s = "Army";

   strVec.push_back(s);
   s = "Navy";
   strVec.push_back(s);
   s = "Air Force";
   strVec.push_back(s);

   // You can access them with operator[], just like an array
   for (vector<string>::size_type i = 0; i < intVec.size(); ++i) {
      cout << "intVec[" << i << "] = " << intVec[i] << '\n';
   }

   // Or you can use iterators
   for (vector<string>::iterator p = strVec.begin();
        p != strVec.end(); ++p) {
      cout << *p << '\n';
   }

   // If you need to be safe, use at() instead of operator[].  It
   // will throw out_of_range if the index you use is > size().
   try {
      intVec.at(300) = 2;
   }
   catch(out_of_range& e) {
      cerr << "out_of_range: " << e.what() << endl;
   }
}

Discussion

In general, if you need to use an array, you should use a vector ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page