Question

Hey I was just wondering is it possible in c++ to have a function in my program that as an input takes a vector or a vector. Here's an example what I want:

void PrintValues(const std::string& title, std::vector<std::vector<double>>& v)
{
    std::cout << title << std::endl;
    for(size_t line = 0; line < v.size(); ++line)
    {
        for(size_t val = 0; val < v[line].size(); ++val)
        {
            std::cout << v[line][val] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

I have two 2d vectors I want to print in this program and I want to use a call to this function to print both one is full with doubles and the other ints. Is this possible or will my ints be auto converted to doubles??

Thanks

Was it helpful?

Solution

Make your function a template

template <typename T>
void PrintValues(const std::string& title, std::vector<std::vector<T> >& v)
{
    std::cout << title << std::endl;
    for(size_t line = 0; line < v.size(); ++line)
    {
        for(size_t val = 0; val < v[line].size(); ++val)
        {
            std::cout << v[line][val] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

And the use:

std::vector<std::vector<int> > x;
std::vector<std::vector<double> > y;
PrintValues("Int",x);
PrintValues("Doubles",y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top