Insert element into std :: set using constructor

is it possible to insert a new element into std :: set, for example, in the case of std :: list:

// insert one element named "string" into the list of subscriptions mylist

std::list< std::list<string> > mylist; mylist.push_back(std::list<string>(1, "string")); 

Now mylist has one element of type std :: string in its sub-list of type std :: list.

How can you do the same if std :: set is a subset of std :: list my list ie

 std::list<std::set <string>> mylist; 

If you cannot then why not?

+4
source share
3 answers

I think this should do the trick:

 int main() { string s = "test"; set<string> mySet(&s, &s+1); cout << mySet.size() << " " << *mySet.begin(); return 0; } 

To clarify the legality and validity of processing &s as an array, see this discussion: string s; & S + 1; Legal? UB?

+6
source

std::set does not have a constructor that accepts an inserted element. The best you can do is use a range constructor:

 int a[] = {1,2,3,4,5}; std::set<int> foo(a, a+5); // insert the values 1 through 5 into foo 

This version accepts the begin and end iterator, which describes the range to be inserted into the set. You can also specify sorting criteria. This is not quite what you wanted, but it is close. Therefore, if you have your items stored in container v , you can insert a new set into your list as follows:

 list<set<string> > myList; myList.push_back(set<string>(v.begin(), v.end())); 
+2
source

Or, in C ++ 0x:

  std::list<std::set<int>> foo; foo.push_back({1,2,3}); 
0
source

Source: https://habr.com/ru/post/1303497/


All Articles