-1

I need to ask question regarding std::set_intersection. I have used it for lists and is working well if I am using

std::set_intersection(list1.begin(),list1.end(),list2.begin(),list2.end(), std::back_inserter(Get_intersect));

But I have never used it with arrays. what about if I'll take array here? I have taken array in argument and want to perform intersection.

std::set_intersection(a[].begin(),a[].end(),list2.begin(),list2.end(), std::back_inserter(Get_intersect));

Getting this error: syntax error : ']'. If I'll remove this [] from a[] then I am unable to begin and end my array.

noman
  • 65
  • 1
  • 1
  • 6
  • Clearly this has nothing to do with `set_intersection`. You just need to find out how to get begin and end iterators from an array. – juanchopanza Aug 25 '16 at 08:54
  • @juanchopanza yeah I know there is not any issue with set_intersection because same function is working well with lists as I have mentioned. Only the issue is with array. – noman Aug 25 '16 at 08:58
  • So why is your title and question focused on `set_intersection`? – juanchopanza Aug 25 '16 at 08:59

2 Answers2

0

You would use std::begin and std::end.

std::set_intersection(
    std::begin(a), std::end(a),
    list2.begin(), list2.end(),
    std::back_inserter(Get_intersect)
);

Note that since a is not a set, you need to take care yourself that it is sorted (which is a prerequisite for std::set_intersection to work, see the set_intersection documentation.

Full example:

#include <algorithm>
#include <iostream>
#include <iterator> // for std::begin and std::end
#include <set>
#include <vector>

void printVector(std::vector<int> vec)
{
    for (std::vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i)
    {
        std::cout << *i << ' ';
    }
    std::cout << std::endl;
}

int main(int argc, char ** argv)
{
    int a[5] = { 1, 2, 3, 4, 5 };
    std::vector<int> list2;
    list2.push_back(2);
    list2.push_back(4);
    std::vector<int> intersection;
    std::set_intersection(
        std::begin(a), std::end(a),
        list2.begin(), list2.end(),
        std::back_inserter(intersection)
    );
    printVector(intersection);
}
codeling
  • 11,056
  • 4
  • 42
  • 71
0

If you have an actual array (and not a pointer) then you can use std::begin and std::end to get "iterators" for the array.

What those basically does is giving you pointers to the beginning and the end (plus one). And you can actually pass pointers yourself, if you have the size:

int* pointer_to_array = ...;
size_t num_elements = ...;

some_function_taking_iterators(
    pointer_to_array,    // This is the begin "iterator"
    pointer_to_array + num_elements  // This is the end "iterator"
);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621