Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) CoutVector

 

std::vector code snippet to write every element in a std::vector to std::cout. There is also a more general solution for every container: CoutContainer. To be also able to read the std::vector, go to write and read a std::vector to/from a std::stream.

 

Instead of using a for-loop (See question 15 of Exercise #9: No for-loops), the algorithm std::copy can be used to copy the contents of a std::vector to std::cout using the std::ostream_iterator. Prefer algorithms over loops [1][2].

 

#include <vector>
#include <iterator>
#include <iostream>
#include <ostream>

//From http://www.richelbilderbeek.nl/CppCoutVector.htm
template <class T>
void CoutVector(const std::vector<T>& v)
{
  std::copy(v.begin(),v.end(),std::ostream_iterator<T>(std::cout,"\n"));
}

 

 

 

 

 

CoutVector test

 

#include <vector>
#include <iterator>
#include <iostream>
#include <ostream>

//From http://www.richelbilderbeek.nl/CppCoutVector.htm
template <class T>
void CoutVector(const std::vector<T>& v)
{
  std::copy(v.begin(),v.end(),std::ostream_iterator<T>(std::cout,"\n"));
}

int main()
{
  //Create a vector
  std::vector<int> v;
  v.push_back(1);
  v.push_back(4);
  v.push_back(9);
  v.push_back(16);
  v.push_back(25);

  //Show it on screen using CoutVector
  CoutVector(v);
}

 

 

 

 

 

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