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

11.1. Computing the Number of Elements in a Container

Problem

You want to find the number of elements in a container.

Solution

You can compute the number of elements in a container by using the size member function or the distance function from the <algorithm> header as in Example 11-1.

Example 11-1. Computing the Number of Elements in a Container

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std; 

int main() {
  vector<int> v; 
  v.push_back(0); 
  v.push_back(1);
  v.push_back(2);
  cout << v.size() << endl; 
  cout << distance(v.begin(), v.end()) << endl; 
}

The program in Example 11-1 produces the following output:

3
3

Discussion

The size member function, which returns the number of elements in a standard container, is the best solution in cases where the container object is accessible. I also demonstrated distance in Example 11-1, because when writing generic code it is common to work with only a pair of iterators. When working with iterators, you often don’t have access to the type of the container or to its member functions.

The distance function, like most STL algorithms, is actually a template function. Since the type of the template argument can be deduced automatically by the compiler from the function arguments, you don’t have to explicitly pass it as a template parameter. You can, of course, write out the template parameter explicitly if you want to, as follows:

  cout << distance<vector<int>::iterator>(v.begin(), v.end()) << endl;

The distance function performance ...

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