(C++) CoutVector
January 25, 2018 · View on GitHub
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 <iterator>
#include <iostream>
#include <ostream>
#include <vector>
template <class T>
void CoutVector(const std::vector<T>& v)
{
std::copy(std::begin(v), std::end(v), std::ostream_iterator<T>(std::cout,"\n"));
}
int main()
{
//Create a vector
const std::vector<int> v = {1, 4, 9, 16, 25};
//Show it on screen using CoutVector
CoutVector(v);
}
References
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
- 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.'