Home > Back-end >  How do i make a function with a variable number of parameters?
How do i make a function with a variable number of parameters?

Time:12-27

I have a function:

vector<int> prime(int num, ...) {

vector<int> mas;
va_list args;
va_start(args, num);

for (int i = 0; i < num; i  ) {
    int v = va_arg(args,int);
    if (isPrime(v)){
        mas.push_back(v);
    }
}
cout << endl;
va_end(args);
return mas;}

It should detected prime numbers. But when i call it, part of my numbers, don`t get over.

It looks something like this

Input: 5, 7, 10, 15, 20,12, 13,16,19

Numbers what cout returns in the loop: 7,7

Help pls!

CodePudding user response:

First of all Variadic arguments from C are considered a bad practice in C and should be avoided.

There are plenty of better C solutions which are able to replace this C feature.

Old fashioned std::vector:

std::vector<int> filterPrimes(std::vector<int> a) {
    auto end = std::remove_if(a.begin(), a.end(), [](auto x) {
       return !isPrime(x)
    };
    a.remove(end, a.end());
    return a;
}

Or std::initializer_list

std::vector<int> filterPrimes(std::initializer_list<int> l) {
    std::vector<int> r;
    std::copy_if(l.begin(), l.end(), std::back_inserter(r), isPrime);
    return r;
}

Or Variadic templates, or template with iterator ranges, or ... .

CodePudding user response:

If the arguments are all of the same type, then just pass them in as, say, a vector.

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


void func(const vector<int>& args)
{
    for (size_t i = 0; i < args.size(); i  )
        cout << args[i] << endl;
}


int main(void)
{
    vector<int> v = { 5, 7, 10, 15, 20, 12, 13, 16, 19 };

    func(v);

    return 0;
}
  •  Tags:  
  • c
  • Related