检查STL容器长度相等的变分函数

Variadic function to check equal lengths of STL containers

本文关键字:函数 STL 检查      更新时间:2023-10-16

我正在编写我的第一个可变函数模板。我得到错误error: parameter packs not expanded with ‘...’:。也许我无法理解这里的一些简单概念。我想将在iterators中传递的所有内容存储在vector中。做这件事的正确方法是什么?

template<typename... Iterator>
bool IsEqualLength(Iterator&... its)
{
    std::vector<Iterator> vec_its {its...};
    int head = vec_its.front().size();
    bool is_diff_size = std::any_of(vec_its.begin(), vec_its.end(), 
        [&head](Iterator& cur){return cur.size() != head;});
    if(is_diff_size)
    {
        return false;
    } else {
        return true;
    }
}

这无法使用(在Ubuntu上的gcc 4.8.4下)进行编译:

../proc.h: In function ‘bool IsEqualLength(Iterator& ...)’:
../proc.h:32:24: error: parameter packs not expanded with ‘...’:
  std::vector<Iterator> vec_its {its...};
                        ^
../proc.h:32:24: note:         ‘Iterator’
../proc.h:35:87: error: parameter packs not expanded with ‘...’:

您在该语句中使用了两个不同的包:

std::vector<Iterator> vec_its {its...};

its是扩展的,但Iterator不是单一的类型。。。它也是一个包,但您无法扩展它。因此出现了错误(特别指出Iterator)。

如果你只需要容器的大小,你可以对所有传入的容器(容器,而不是迭代器!)调用size(),并将其放入数组中(不需要动态分配):

template <typename... Container>
bool isEqualLength(Container&&... cs) {
    size_t sizes[] = {cs.size()...};
    return std::all_of(std::begin(sizes), std::end(sizes),
        [&sizes](size_t cur){return cur == sizes[0]; });
}