Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetSizes

 

GetSizes is a matrix code snippet to obtain all std::vector sizes in a (one-dimensional) std::vector.

 

 

 

 

 

C++11STL GetSizes using a C++11 lambda expression

 

#include <algorithm>
#include <vector>

//From http://www.richelbilderbeek.nl/CppGetSizes.htm
const std::vector<std::size_t> GetSizes(const std::vector<std::vector<double> >& v)
{
  std::vector<std::size_t> w;
  std::transform(v.begin(),v.end(),std::back_inserter(w),
    [](const std::vector<double>& x) { return x.size(); }
  );
  return w;
}

 

 

 

 

 

C++98 GetSizes using a for-loop

 

Prefer algorithms over loops [1][2]

 

#include <vector>

const std::vector<std::size_t> GetSizes(const std::vector<std::vector<double> >& v)
{
  std::vector<std::size_t> w;

  const std::size_t sz = v.size();
  for (std::size_t i = 0; i!=sz; ++i)
  {
    w.push_back(v[i].size());
  }
  return w;
}

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms over loops'
  2. Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict