Reputation: 2470
I get two variables a
and b
and want to add them directly to a list of arrays. How can I avoid to define another array, which will be pushed into the list afterwards?
I am searching for a construction similar to the line beginning with //
.
Minimal example:
#include <list>
#include <boost/array.hpp>
using namespace std;
int main()
{
cout << endl;
/* given values */
int a = 1;
int b = 2;
/* arrayList contains arrays of integers. */
list<boost::array<int, 2> > arrayList;
/* item to add values */
boost::array<int, 2> item;
item[0] = a;
item[1] = b;
arrayList.push_back(item);
// arrayList.push_back({{a, b}});
cout << arrayList.front()[0] << ", " << arrayList.front()[1] << endl;
return 0;
}
My g++ version is the following:
gcc-Version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
.
Compiling (within Eclipse) throws this warning listed as an error:
Warnung: erweiterte Initialisierungsliste nur mit -std=c++0x oder -std=gnu++0x verfügbar [standardmäßig aktiviert] main.cpp /testArrayListAndFind line 24 C/C++ Problem
which means: Extended initilization list only with ... or ... available.
Upvotes: 1
Views: 2830
Reputation: 52365
You could use boost::assign::list_of
if you don't have C++11 support:
arrayList.push_back(boost::assign::list_of(1)(2));
Upvotes: 2
Reputation: 472
You can resize the list to the size you want and mutate the array directly in the list, e.g.,
arrayList.resize(10);
for(list::iterator iter = arrayList.begin(); iter != arrayList.end(); ++iter) {
(*iter)[0] = <value_a>;
(*iter)[1] = <value_b>;
}
Note that resize() actually call the constructor of boost::array in your example, so the performance saving would be minimal.
Upvotes: 0
Reputation: 28762
The array that is pushed to the list
will have to be created, the question is what do you consider acceptable work/typing on your part.
For example, you could create a helper function:
boost::array<int, 2> make_array(int a, int b)
{
boost::array<int, 2> item;
item[0] = a;
item[1] = b;
return item;
}
then you can do
arrayList.push_back(make_array(a, b));
This assumes you will only need 2 elements in the array. If this is the case, you could just as well use std::pair<int, int>
instead of boost::array<>
. Otherwise, you could create a few overloads of make_array()
Upvotes: 2