0

I want to have a function that takes in a template for a std::vector and prints whatever is in the vector provided it is a datatype allowed in std::cout. I believe this needs to be recursive since what about a vector of vector of a vector.... For example, given a 1d vector,

template< typename T>
void PrintVector(T vec)
{
   for (unsigned int i = 0; i < vec.size(); i++){
       std::cout << vec[i] << std::endl;
   }
}

There are a few problems I have here with this code.

1. This doesn't work if it is a multi-dimensional vector, I need it to (I guess at this statement: vec[i]) recursively go and print out that vector and do the same if there is another vector.

2. I also want it to take in a reference to the vector within the template so I don't copy a 3d vector that's like 1gb in size to print it, rather just reference so I don't allocate any memory to do so.

Any help would be appreciated!

  • regarding 2.: what is the problem? What is stopping you from taking it by reference? – bolov Mar 13 '21 at 01:08
  • @bolov I don't know how. Also the other issue is i'm not even sure if that syntax is correct. I need it to take in an `std::vector< TEMPLATE >` instead of a template anyway. –  Mar 13 '21 at 01:08
  • then it's time to start with a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – bolov Mar 13 '21 at 01:10
  • I've just noticed you edited your post to ask a completely different question. Don't do that! Ask a new question instead. – bolov Mar 13 '21 at 10:34
  • @bolov I can't. Reached my question limit –  Mar 14 '21 at 01:54

1 Answers1

1

First let's clarify some things: std::vector is a template, but std::vector<T> is a class (generated from the template, but that is irrelevant). Also the T in the std::vector<T> is a type not a template.

I also want it to take in a reference to the vector within the template

It doesn't work like that. You simply make the function parameter a reference.

Coming back to your main question. One common way to do this is with an overloaded function:

template <class T>
void print(const T& obj)
{
    std::cout << obj;
}

template <class T>
void print(const std::vector<T>& v)
{
    for (const auto& elem : v)
    {
        print(elem);
        std::cout << std::endl;
    }
}

When you call print with std::vector<std::vector<int>> the 2nd overload is chosen because it matches and is more specialized than the 1st. T is deduced to be std::vector<int>; print(elem) calls 2nd overload with T deduced as int and here print(elem) calls the 1st overload.

bolov
  • 72,283
  • 15
  • 145
  • 224
  • So its recursively printing the vector but with a different overloaded function of the same name? Also, what type would you replace `elem` with if you didn't use auto? I am just wondering if say I want to do a traditional for loop with a counter –  Mar 13 '21 at 05:42
  • `for (std::size_t i = 0; i < v.size(); ++i) { print(v[i]); }` – bolov Mar 13 '21 at 10:31