Answer the question
In order to leave comments, you need to log in
How to pass an array correctly?
Hello!
How can I pass an array of creations to a function without explicitly declaring a variable, can I do it in javascript as I can functionCall([0,1,2,3])
do it in c++?
I did this functionCall(&(int {0,1,2,3}[]))
but I get errors, how should I beat?
Answer the question
In order to leave comments, you need to log in
On C(90)/C++(98) - no way,
on C++11 - using a function template with a variable number of arguments
template<typename F, typename ...T> void f(F f,T...arr)
{
std::array<F,1+sizeof...(T)> a{f,...arr};
//........
}
#include <iostream>
#include <array>
using namespace std;
void f(const std::array<int,3> &arr)
{
for(const auto &v: arr)
cout << v << " ";
}
int main()
{
f({1,2,3,4,5});
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
void f(const std::vector<int> &arr)
{
for(const auto &v: arr)
cout << v << " ";
}
int main()
{
f({1,2,3,4,5});
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question