Variable type of return

Asked

Viewed 131 times

3

I want to do functions with variant input type, like this:

int count(vector<auto> base, auto val)
{
    int sum= 0;

    for (auto it : base)
    {
        if (it == val)
        {
            sum++;
        }
    }

    return sum;
}

or this:

string str(auto a)
{
    stringstream x;
    x << a;
    return x.str();
}

But of course, it didn’t work. I received the following error:

error: invalid use of 'auto'

How can I do that?

  • 2

    You need to explain better what you want, there’s a guy who wants to use one template, but the question says nothing.

  • I have no idea what a template

  • So explain what you want to do so we can help you..

  • @bigown, I realized how stupid my question was. Post updated.

  • @Felipenascimento, there are stupid questions, and there are questions like that. It may be trivial for those who know, but for those who are starting out in the field, even the most trivial can be new

1 answer

3


I think you want to use one function template, thus:

#include <iostream>
#include <vector>
using namespace std;

template<typename T> 
vector<T> filter(vector<T> base, T val) {
    vector<T> temp;
    for (auto it : base) if (it == val) temp.push_back(it);
    return temp;
}

int main() {
    vector<int> v = {7, 5, 16, 8, 5, 12, 1};
    for (auto it : filter(v, 5)) cout << it << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that there are generic algorithms ready in C++ to do this, for example copy_if() or the remove_if(). It’s not the same thing, but they might be more useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.