set_union() is not working for a set of strings

541 Views Asked by At

I was trying to find out the union of two set containing strings, using set_union(...) function. But, it's throwing error inside of stl_algo.h ar line no 4948 -

Error : passing 'const std::__cxx11::basic_string<char>' as 'this' argument discards qualifiers [-fpermissive]

My code :

#include<bits/stdc++.h>

using namespace std;

int main()
{
    int t,k, tmp, i=1,j,l,m,n,x1,x2;
    cin>>n;
    string st,stt;
    set <string> set1,set2,set3;
    set1.insert("sdsd");
    set1.insert("sdswewd");
    set1.insert("ssd");

    set2.insert("sdsd");
    set2.insert("sdfewew");
    set2.insert("ssd");
    set_union(set1.begin(),set1.end(),set2.begin(),set2.end(),set3.begin());

    return 0;
}

2

There are 2 best solutions below

1
Kiran Thilak On BEST ANSWER

try using std::inserter

set_union( set1.begin(), set1.end(), set2.begin(), set2.end(),std::inserter( set3, set3.begin() ));

Update:

a1.begin() is simply not an output iterator. inserter(a1,a1.begin()) returns an output iterator which will invoke the set's insert function for each element... Why do we need an inserter function call when doing a set_union for a set?

Also since we are dealing with std::set a container where uniqueness is guaranteed we don't need to take a set_union because a simple set insert will also ensure it that no copies of same element is created.

//insert all element of set 1 to set 3
set3.insert(set1.begin(),set1.end());
//insert all elements of set 2 (that is not in set 1) to set 3
set3.insert(set2.begin(),set2.end());
8
Constantinos Glynos On

As mentioned in another answer, std::inserter would do the job. Alternatively, you can store the output from the set_union in a vector and if necessary, construct another set using the values from the output vector.

However, it should be noted that this approach requires that you know the size of the vector either at run-time (set by the user) or at compile time. In the latter case, you can use an std::array. If the output is not known (i.e. calculated) then the output vector might to be large enough to store the results and you're program will crash (memory leak).

#include<iostream>
#include<set>
#include<string>
#include<algorithm>
#include<vector>

int main()
{
    std::set<std::string> set1,set2;
    set1.insert("sdsd");
    set1.insert("sdswewd");
    set1.insert("ssd");

    set2.insert("sdsd");
    set2.insert("sdfewew");
    set2.insert("ssd");

    std::vector<std::string> output(4);
    std::set_union(set1.begin(),set1.end(),set2.begin(),set2.end(),output.begin());

    std::set<std::string> set3(output.begin(),output.end());
}

Online example: https://rextester.com/MUPHB45816

There is also a code example here which uses vectors.