• Page:
  • 1

TOPIC: STL set_intersection with classes

STL set_intersection with classes 6 months 1 week ago #13534

Hello,

I was wondering if set_intersection can be used with classes or does it only work with C++ types

e.g. I have following code with C++ classes;

struct data {
int field1
int commonfield
};

vector<data> data1(5), data2(5), data3(5)

struct comp { // -Checked 12-2-02

bool operator()(const data& lhs, const data& rhs) const

{

return (lhs.commonfield < rhs.commonfield);

}

};
std::set_intersection(data1.begin(), data1.end(), data2.begin(),
data2.end(), data3.begin(), comp());

Does this code then find the intersection based on commonfield, or can I only use C++ types e.g. vector<int> ?

Please Log in or Create an account to join the conversation.

STL set_intersection with classes 6 months 1 week ago #13553

Hello Digby,

It should work:
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

struct data {
  int field1;
  int commonfield;
};

std::vector<data> data1 = {{100, 1}, {200, 2}, {300, 3}, {400, 4}, {500, 5}},
                  data2 = {{40 , 4}, {50, 5}, {60, 6}, {70, 7}, {80, 8}}, 
                  data3;

struct comp {
  bool operator()(const data& lhs, const data& rhs) const {
    return (lhs.commonfield < rhs.commonfield);
  }
};

int main()
{
  std::set_intersection(data1.begin(), data1.end(),
                        data2.begin(), data2.end(),
                        std::back_inserter(data3), comp());
  for (auto item: data3)
    std::cout << "field1:" << item.field1 << "\t" << "commonfield:" << item.commonfield << "\n";
}

Cheers,

Bruneau

Please Log in or Create an account to join the conversation.

  • Page:
  • 1
Moderators: April Anne