2

this template prints the content of an 2D vector

how would you generalize this template so it works for every STL container ?


template<class T>
void printVector(std::vector<std::vector<T>> const &matrix) {
    for (std::vector<T> row : matrix) {
        for (T val : row) {
            std::cout << val << " ";
        }
        std::cout << '\n';
    }
}

Is there maybe "print" that allows me to print anything, no matter what I put into it ? (n-dimensional containers, strings, etc ?)

  • Unrelated: `vector` of `vector` can result in poor caching behaviour because while the data in one `vector` is guaranteed to be contiguous, there is no such guarantee for the data that spans multiple `vector`s. Start with what's easiest to use, but if you run into performance problems, [consider using something more like this](https://stackoverflow.com/a/2076668/4581301). – user4581301 Apr 19 '19 at 22:34

1 Answers1

1

Just take any type and use range based loops. Your only problem is that you specified that is was a std::vector.

template<class T>
void print2Dcontainer(const T &matrix)
{
    for (const auto &row : matrix)
    {
        for (const auto &val : row) std::cout << val << ' ';
        std::cout << '\n';
    }
}

My version above has no safety for passing something that will cause a compile error (e.g. passing 7). Fancy SFINAE could be added to remove this potential issue, but I'd only do so for library code.

Cruz Jean
  • 2,761
  • 12
  • 16