Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use set_intersection with std::set in VC++?

I'm trying to compile VC6 project with VC10... I obtain an error C2678 with set_intersection: I wrote some example to understand. Can anybody explain how to compile this snippets ?

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

int main( )
{
    using namespace std;

    typedef set<string> MyType;

    MyType in1, in2, out;
    MyType::iterator out_iter(out.begin()); 

    set_intersection(in1.begin(),in1.end(), in2.begin(), in2.end(), out_iter);
}

The output :

c:\program files\microsoft visual\studio 10.0\vc\include\algorithm(4494): error C2678: '=' binary : no operator defined which takes a left-hand operand of type 'const std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

If I use a std::vector instead of std::set the compilation succeeded. acceptable)

like image 571
chepseskaf Avatar asked Jun 30 '10 14:06

chepseskaf


1 Answers

Try set_intersection(in1.begin(),in1.end(), in2.begin(), in2.end(), inserter(out, out.begin()) );

This is because set_intersection wants to write to the output iterator, which causes the output container to grow in size. However this couldn't be done with just an iterator alone (it could be used to overwrite existing elements but not grow in size)

Edit: fixed the typo. Use inserter for adding to a set. A back_inserter only works for vectors and such.

Edit 2: fixed another typo. STL inserter requires a second argument which is a hint iterator to the likely insert position. Thanks chepseskaf.

like image 90
rwong Avatar answered Sep 22 '22 12:09

rwong