其他分享
首页 > 其他分享> > c – std :: includes实际上做了什么?

c – std :: includes实际上做了什么?

作者:互联网

the standard, std ::包括:

Returns: true if [first2, last2) is empty or if every element in the range [first2, last2) is contained in the range [first1, last1).
Returns false otherwise.

注意:由于这是在[alg.set.operations]下,因此必须对范围进行排序

从字面上看,如果我们让R1 = [first1,last1]和R2 = [first2,last2),这就是评估:

∀a∈R2 a∈R1

但是,这不是实际评估的内容.对于R1 = {1}且R2 = {1,1,1},std :: includes(R1,R2)返回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';
}

Live on Wandbox

这是令人惊讶的.我用libstdc和libc验证了它,但我认为这不是标准库实现中的一个错误,因为它是算法库的一部分.如果这不是std :: includes应该运行的算法,那是什么?

解决方法:

我在cpplang slack和Casey Carter responded中发布了这个:

The description of the algorithm in the standard is defective. The intent is to determine [if] every element in the needle appears in order in the haystack.

[The algorithm it actually performs is:] “Returns true if the intersection of sorted sequences R1 and R2 is equal to R2”

或者,如果我们确保我们确定subsequence的含义:

Returns: true if and only if [first2, last2) is a subsequence of [first1, last1)

link to Casey Carter’s message

标签:stl-algorithm,c,language-lawyer,c17
来源: https://codeday.me/bug/20191005/1855098.html