user3260563
user3260563

Reputation: 9

Use templates to read vector

I'm trying to read a vector from file but I might have different datatype there and I use templates

template <class T>
vector<T> readd(int n)
{
    vector<T> V;
    for(int i=0;i<n;i++)
    {
        T k;
        fin>>k;
        V.push_back(k);
    }
    return V;
}

int main()
{
    vector<int> V;
    int n;
    fin>>n;
    V = readd(n);
}

But I've got compile error

error: no matching function for call to readd(int&)

Can someone help me...

Upvotes: 0

Views: 114

Answers (2)

CinCout
CinCout

Reputation: 9619

You are trying to return V which is nothing but vector<T>.

Do this:

template <class T>
vector<T> readd(int n)
{
    vector<T> V;
    for(int i=0;i<n;i++)
    {
        T k;
        fin>>k;
        V.push_back(k);
    }
    return V;
}

int main()
{
    vector<int> V;
    int n;
    fin>>n;
    //you need to tell the compiler the actual type of T since it is not auto deducible!
    V = readd<int>(n); 
}

Upvotes: 0

D Drmmr
D Drmmr

Reputation: 1243

You are trying to use template argument deduction, but in order for that to work the compiler needs to be able to deduce every template argument from the types of the arguments you pass to the function. U does not appear in your argument list, so the compiler cannot deduce its type.

That said, it doesn't make any sense to pass a vector by value to this function since you immediately clear it. The canonical way to write your function would be

template <class T>
std::vector<T> readd(int n)
{
    std::vector<T> v;
    v.reserve(k); // prevent unnecessary reallocation
    for (int i = 0; i < n; ++i)
    {
        T k;
        fin >> k;
        v.push_back(k);
    }
    return v;
}

and then call it like

std::vector<int> v = readd<int>(10);

You need to specify the template argument, because it cannot be deduced by the compiler.

Also, in case fin is a global variable, it would be better to make it non-global and pass it to the read function.

Upvotes: 3

Related Questions