From the standard, std::includes
:
Returns:
true
if[first2, last2)
is empty or if every element in the range[first2, last2)
is contained in the range[first1, last1)
. Returnsfalse
otherwise.
Note: as this is under [alg.set.operations], the ranges must be sorted
Taking this literally, if we let R1=[first1, last1)
and R2=[first2, last2)
, this is evaluating:
∀a∈R2 a∈R1
However, this is not what is actually being evaluated. For R1={1}
and R2={1,1,1}
, std::includes(R1, R2)
returns false:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
std::vector<int> a({1});
std::vector<int> b({1,1,1});
// Outputs 'false'
std::cout << std::boolalpha
<< std::includes(a.begin(), a.end(), b.begin(), b.end()) << '\n';
}
This is surprising. I verified it with both libstdc++ and libc++, but it seems unlikely to me that this would be a bug in the standard library implementation, considering it's part of the algorithms library. If this isn't the algorithm that std::includes
is supposed to run, what is?
I believe you're trying to check if
a
includesb
in your example,a
doesn't includeb
butb
does includea
. If you swapb
anda
it will return true, sincea
is included inb
.I hope I'm not missing something obvious.
What I've understood by playing around with algorithm is, when you type
includes(R2, R1)
it checks ifR2
ownsR1
as a subgroup, if yes returnstrue
if not returnsfalse
. Also if it's not ordered throws an error:sequence not ordered
.I posted this in the cpplang slack, and Casey Carter responded:
Or, if we ensure we are certain of the meaning of subsequence:
link to Casey Carter's message
As always when reading the standard, you must read the unwritten words.
Focus on the intent not just the letter. (The wording of the standard was often found to be vague, incomplete, self-referential, or contradictory.)
Read the introduction of section "28.7.6 Set operations on sorted structures [alg.set.operations]" :
So it's perfectly clear that the words in the description of
includes
:must be ignored. You need to know a priori what multiset operations are, what "includes" means for two multisets, ignore the description and rebuild in your head what was the obvious intent.
Multiset inclusion:
A is included in B iff A union B = B.
This is true for sets or multisets.