How to make a struct accept an initializer list
Hello,
I want my mValArray to accept initializer list. But I don't know how.
|
mValArray<int> val = {1, 2, 3, 4, 5}; // Complier error
|
Could anyone help me?
Thanks.
Last edited on
Here is a little example. Maybe you can adapt it for your needs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <initializer_list>
using namespace std;
class MyClass
{
public:
MyClass (initializer_list<int> il) : v (il)
{
for (int i : il)
{
cout << i << '\t' << '\n';
}
}
void print ()
{
copy (v.begin (), v.end (), ostream_iterator<int>(cout, " "));
}
private:
vector<int> v;
};
int main()
{
MyClass mc = {1, 2, 3, 4, 5, 6, 7 };
mc.print ();
system ("pause");
return 0;
}
|
@Thomas1987
Thanks. This helps me a lot.
Topic archived. No new replies allowed.