Why does the program display 0? The function description says Returns true if the sorted range [first1, last1) contains all the elements in the sorted range [first2, last2). http://www.cplusplus.com/reference/algorithm/includes/ . But a contains all elements from b (1 and 2)

std::vector a{1, 2}; std::vector b{1, 2, 1, 2}; std::cout << std::includes(a.begin(), a.end(), b.begin(), b.end()); 
  • sorted range requirement is clearly not met. - VTT
  • one
    @VTT that is, they ALREADY should be sorted by input algorithm? I thought it was the algorithm that did - stels
  • @VTT not, I tried for {1,1,2,2} - also does not work! - stels

2 answers 2

 std::vector<int> a{1, 2}; // тут вы забыли аргумент шаблона std::vector<int> b{1, 2, 1, 2}; 

Swap the objects and it will work.

 std::swap(a, b); std::cout << std::includes(a.begin(), a.end(), b.begin(), b.end()); 

if b is a subset of a , then get a positive result

  • The template argument in C ++ 17 is derived from the initializer. - Harry
  • I don't have such a compiler, but thanks - AR Hovsepyan
  • And still add the need for sorting ... Otherwise, if you take b{2,2,1,1} - it may not work out :) - Harry

Here, in essence, it is checked whether the range is completely in another range, and the set difference is not calculated. Therefore, the same elements are quite permissible (as in a multiset), and the range a clearly not enough to include the range b .

But on the contrary - quite: check for yourself

 std::cout << std::includes(b.begin(), b.end(), a.begin(), a.end()); 

but don't forget to sort :)

In other words, a is a subset of b , but b not a subset of a - if only because it has more elements :)

  • Nah, std :: includes does not require sorting .... - AR Hovsepyan
  • @ARHovsepyan Returns true if the sorted range [first2, last2) is a subsequence of the sorted range [first1, last1). (A subsequence need not be contiguous.) - from here: en.cppreference.com/w/cpp/algorithm/includes - Harry
  • I don’t know honestly, because according to the standard, sorting is needed, but it worked for me even without sorting (focus). We need to check what's wrong ... - AR Hovsepyan