0

I got a problem when I try to implementisdisjoint from Python in C++. As I understand it, isdisjoint is a way to determine the subset I think, if there is same element in both set, then return true, otherwise return false. In C++, I try to use std::vector<int> instead of a Python list. Is there any way it can do the same job?

The original Python is:

if not region_neighbor(region_list[m].isdisjoint(region_list[n])) or\
   not region_neighbor(region_list[n].isdisjoint(region_list[m])):

and the C++ I wrote is :

if ( includes(region_list[m],region_list[n],region_list[n],region_list[m]) )

Is there any way it can do this job.. If you have some more efficient way or advice or little hints..Please let me know! Thanks you in advance.

Or maybe just determine if there exist the same element in two vector in C++.

1 Answers1

0

The function std::includes will not do the job because it tests if the whole sorted range is contained in another.

If you want to write a is_disjoint function in an easy way, you can do as follows:

template<typename T>
bool is_disjoint(const std::vector<T> & a, const std::vector<T> & b)
{
    bool match_found(false);
    for(size_t i = 0; !match_found && i < a.size(); ++i)
    {
        for(size_t j = 0; !match_found && j < b.size(); ++j)
        {
            if(a[i] == b[j])
                match_found = true;
        }
    }
    return !match_found;
}

And you can use it this way (just an example):

std::vector<int> a {5, 4, 9};
std::vector<int> b {6, 3, 2, 86};

std::cout << is_disjoint(a, b) << std::endl;

Of course, I assumed here that the vectors are not sorted.

I hope it can give you some ideas.


Note: The template function allows you to make it work for any type you want but it is yours to guarantee that they provide the operator==().
Or you can also improve the function by giving a comparison function in parameter instead of using operator==().

Fareanor
  • 5,900
  • 2
  • 11
  • 37
  • 2
    `for (const auto& x : a) { for (const auto& y : b) { if (x == y) return false; }} return true;` seems even simpler. – Jarod42 Jul 12 '19 at 09:02