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