Std :: set the difference with a self-defined type

I defined my own structure, for example

struct element { int id; float value; } 

and I use it with std::set . I want to use the set_difference algorithm (as mentioned in the previous question to determine the difference between two sets. When I try to call the code, compilation stops with the following error message:

 /usr/include/c++/4.2.1/bits/stl_algobase.h:268: error: passing 'const element' as 'this' argument of 'element& element::operator=(const element&)' discards qualifiers 

A minimal example might look like this:

 std::set<struct element> s1; std::set<struct element> s2; std::set<struct element> s3; element e1 = { 1, 11.0 }; element e2 = { 2, 22.0 }; element e3 = { 3, 33.0 }; s1.insert(e1); s1.insert(e2); s2.insert(e2); s2.insert(e3); set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), s3.begin()); 
+4
source share
1 answer
 set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(s3, s3.begin())); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

Example: http://ideone.com/B4Cc1

By s3.begin() as the output iterator, you would like you to overwrite the front area of ​​the set with the difference set. Overwriting requires that the size of the set be larger than the result, which, most likely, is not true; even if the set is not empty, you cannot use s3.begin() as output because the iterator is read-only (otherwise it will destroy the sorted order).

OTOH, std::inserter(x, cit) means that whenever this output iterator is assigned ( *it = y ), the insert ( x.insert(cit, y) ) method that you really need is called: fill set of empty.

+12
source

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


All Articles