Opt
Opt

Reputation: 4804

Initializer lists in C++11

If I want to create a function with accepts a vector or an initializer list, so something like

void fun(const vector<int>& v);
void fun(initializer_list<int> v);

do I have to create 2 separate functions or is there a way I can get away with just creating one?

Edit:

What if I want

void fun(const vector<vector<int>>& v);

If I pass this function

fun({{1, 2}, {3, 4}});

I get an error.

Upvotes: 2

Views: 231

Answers (2)

galop1n
galop1n

Reputation: 8824

You should prefer the standard library way with iterators to feed a function with a sequence of value. And add wrapper for easier calls with a vector or initializer list if needed.

#include <iostream>
#include <vector>
#include <initializer_list>

template <typename it__>
void fun( it__ bgn, it__ end ) {
  while ( bgn != end )
    std::cout << " " << *bgn++;
  std::cout << std::endl;
}

void fun( std::initializer_list<int> seq ) {
  fun( begin(seq), end(seq) );
}
void fun( std::vector<int> const & seq ) {
  fun( begin(seq), end(seq) );
}

int main() {
  std::vector<int> foo { 4,5,6 };
  fun({1,2,3});
  fun(foo);
}

Upvotes: 0

Colin D Bennett
Colin D Bennett

Reputation: 12084

Yes, like this:

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

void fun(const vector<int>& v)
{
  for (auto x = v.begin(); x != v.end(); ++x) cout << " " << *x;
  cout << endl;
}

int main()
{
  std::vector<int> foo { 4,5,6 };
  fun({1,2,3});
  fun(foo);
}

Running it

$ g++ -std=c++11 test.cpp
$ ./a.out 
 1 2 3
 4 5 6

Upvotes: 4

Related Questions