Size of each vector in a vector of vectors, c++

Alec Jacobson

November 01, 2011

weblog/

Here's a small c++ program that demonstrates using the standard library's transform function to gather a list of sizes for each vector in a vector of vectors. This would of course work just as well for lists, etc. It also shows how to use for_each and min_/max_element on that list of sizes. Save the following in sizes.cpp
#include <vector>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <iostream>

using namespace std;

// Templated to print an element on a single line
template <typename T> void print(const T d)
{
  cout << d << endl;
}

int main(int argc, char * argv[])
{
  // Fill vector with vectors of doubles
  vector<vector<double > > V(5);
  for(int i = 0;i < 5; i++)
  {
    V[i].resize(i);
  }

  vector<size_t> S(V.size());
  // use std::transform to gather sizes, be sure to use mem_fun_ref not mem_fun
  transform(V.begin(),V.end(),S.begin(),mem_fun_ref(&vector<double>::size));
  // Print sizes for each vector in the list of vectors
  for_each(S.begin(),S.end(),print<size_t>);
  // Use other std algorithms on list of sizes: get max and min element
  // location and value
  vector<size_t>::iterator max_iter = max_element(S.begin(),S.end());
  cout<<"max element: S("<<max_iter-S.begin()<<") = "<<*max_iter<<endl;
  vector<size_t>::iterator min_iter = min_element(S.begin(),S.end());
  cout<<"min element: S("<<min_iter-S.begin()<<") = "<<*min_iter<<endl;
}
Compile with:
g++ -o sizes sizes.cpp
Running:
./sizes
should produce
0
1
2
3
4
max element: S(4) = 4
min element: S(0) = 0