Initializing a list of sets of integers in C ++ 98

this may sound trivial, but so far I have not been able to find it on the internet, so

I want to initialize a list of sets of integers or a set of sets of integers, for example:

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 present it as an exercise in a dispatch system that does not accept C ++ 11.

I figured out how to initialize the container in the old syntax from an array of integers like

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

      

but not list< set<int> >

.

+3


source to share


2 answers


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

That being said, the shortest way to initialize is probably to repeat the initialization set

(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 check array sizes a lot, I suggest you use a macro:

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

      

This 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));

      

+1


source


I'll give you some approach I used to initialize STL static stores, but the syntax in this case is somewhat unclear:

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 the () operator to include items in the store. The advantage of this idea is that it can be used to initialize lists and sets static

, because expressions can be evaluated at compile time.

+1


source







All Articles