c++ how to make a function (subroutine) argument either a vector of doubles or a vector of ints

StackOverflow https://stackoverflow.com/questions/18938041

Вопрос

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

Это было полезно?

Решение

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top