4

Like this question already asked, I'd like to initialize a container using STL where the elements are hard-coded in the cleanest manner possible. In this case, the elements are a doubly nested container:

set<vector<int> > A;

And I'd like (for example) to put the following values in:

A = [[0,0,1],[0,1,0],[1,0,0],[0,0,0]];

C++0x fine, using g++ 4.4.1. STL is preferable as I don't use Boost for any other parts of the code (though I wouldn't mind an example with it!).

Community
  • 1
  • 1
Hooked
  • 84,485
  • 43
  • 192
  • 261

2 Answers2

10

This does use g++ 4.4.1, with -std=c++0x

#include <set>
#include <vector>

using namespace std;

int main()
{
    set<vector<int>> A = {{0,0,1},{0,1,0},{1,0,0},{0,0,0}};

}
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • Wow, thats amazing and quite simple! That should be _the_ answer to the question I linked to as well. Any good reason why it took so long for the standard to implement this functionality? – Hooked Apr 30 '10 at 06:08
  • @Hooked: Standards aren't exactly quick. :) (10 years in between ISO standards.) Previous standards had other things to worry about. – GManNickG Apr 30 '10 at 06:13
  • +1 : Wow, works with g++ (GCC) 4.6.0 20100421 (experimental) with -std=c++0x. – Eddy Pronk Apr 30 '10 at 06:15
  • Nice. Shouldn't c++0x allow us to write `set>` instead of `set >` ? – ereOn Apr 30 '10 at 07:29
7
#include <boost/assign/list_of.hpp> 
#include <vector>
#include <set>

using namespace std;
using namespace boost::assign;

int main()
{
    set<vector<int> > A;

    A = list_of
        (list_of(0)(0)(1))
        (list_of(0)(1)(0))
        (list_of(1)(0)(0));
        (list_of(0)(0)(0));
    return 0;
}
Eddy Pronk
  • 6,527
  • 5
  • 33
  • 57
  • Ah I see, nested use of list_of's, nice thank you! Any chance that this could be done only with a one-line += operator? – Hooked Apr 30 '10 at 06:12
  • `list_of()` is useful for quick code but is too slow and resource intensive for production. I use it extensively in unit tests but wouldn't touch it otherwise. – deft_code Apr 30 '10 at 06:41