4

this might seem trivial but I wasn't able to find it on the web so far, so

I want to initialize a list of sets of integers or a set of sets of integers, like this:

list< set<int> > lsi = {{}};

or maybe like this:

set< set<int> > ssi = {{5}, {6}, {7}};

in C++98. The reason for this is that I have to submit it as an exercise in a submission system that does not accept C++11.

I have found out how to initialize a container in the old syntax from an array of integers, for example

int tmp[] = {1,2,3};
set<int> s (tmp, tmp + sizeof(tmp) / sizeof(tmp));

but not a list< set<int> >.

pantelis300
  • 439
  • 4
  • 9

2 Answers2

1

As mentioned in the comments, this is not possible without c+11 / boost.

That being said, the shortest way to initialize would probably be repeating set's initialization (which you mentioned in your question):

int set1v[] = {10, 20, 30, 40};
int set2v[] = {11, 22, 33, 44};
int set3v[] = {15, 25, 35, 45};

set<int> setV[] = {
    set<int>(set1v, set1v + sizeof(set1v) / sizeof(set1v[0])),
    set<int>(set2v, set2v + sizeof(set2v) / sizeof(set2v[0])),
    set<int>(set3v, set3v + sizeof(set3v) / sizeof(set3v[0]))
};

set< set<int> > mySet(setV, setV + sizeof(setV) / sizeof(setV[0]));

Btw, Since you're checking arrays' sizes so many times I'd suggest you use a count macro:

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

It will look a little better:

#define END_OF(x) (x + COUNT_OF(x))

int set1v[] = {10, 20, 30, 40};
int set2v[] = {11, 22, 33, 44};
int set3v[] = {15, 25, 35, 45};

set<int> setV[] = {
    set<int>(set1v, END_OF(set1v)),
    set<int>(set2v, END_OF(set2v)),
    set<int>(set3v, END_OF(set3v))
};

set< set<int> > mySet(setV, END_OF(setV));
Community
  • 1
  • 1
ArnonZ
  • 3,822
  • 4
  • 32
  • 42
1

I will give you some approach I have used to initialize static STL storages, but the syntax becomes somewhat obscure for this case:

template <typename Type>
struct SetInit : public std::set<Type> {
    SetInit<Type>& operator()(const Type& data) {
        this->insert(data);
        return *this;
    }
};

int main () {
    std::set<std::set<int> > test_set = SetInit<std::set<int> >() // Call ctor
        (SetInit<int>()(1)(2)(3))(SetInit<int>()(4)(5)(6)); // Each element in () is inserted in the set
    return 0;
}

The basic idea is to use an operator() to include elements in the storage. The advantage of this idea is that it can be used to initialize static lists and sets because the expressions can be evaluated at compile time.

Samuel Navarro Lou
  • 1,168
  • 6
  • 17