noman noman - 3 months ago 15
C++ Question

std::set_intersection for array and list

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.

Answer

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);
}