【问题标题】:What's wrong with this c++ template function此C ++模板功能有什么问题
【发布时间】:2019-11-27 21:05:13
【问题描述】:

这段代码有什么问题。 我正在尝试通过使用 std::vector 实例化来调用 countLessThan3。

// 3. Lambdas
template<typename T>
const auto countLessThan3(const T & vec, int value)
{
    const auto count = std::count(vec.begin(), vec.end(), 
        [](int i){ return i < 3;}
    );

    return count;
}

int main(int argc, char const *argv[])
{
    // 3
    std::vector<int> vector = {1, 2, 3, 4, 5, 2, 2, 2};
    countLessThan3<std::vector<int>>(vector, 3);
    return 0;
}

在 linux 上使用 g++ -std=c++14 1.cpp -o 1 编译。

【问题讨论】:

  • 它做错了什么?
  • std::count 没有重载,它将谓词作为第三个参数。
  • 是否假定您总是与整数进行比较?如果 T 类型是非 int 的容器怎么办?您将 T& 类型命名为 vec。它总是会是一个vec吗? const auto countLessThan3(std::vector& vec, T value) 可能更有用。

标签: c++ c++11 templates lambda


【解决方案1】:

有一些问题:

  • 代码使用std::count,但是传递了一个lambda,所以应该是std::count_if
  • value 作为参数传递给函数,但未使用,并且 lambda 中有一个硬编码的 3

其他小问题在下面的 sn-p 中修复

#include <iostream>
#include <vector>
#include <algorithm>

template<typename T>
auto countLessThan(const T & vec, typename T::value_type value)
{
    return std::count_if(vec.begin(), vec.end(), 
        [value](typename T::value_type i){ return i < value;}                       
    );
}

int main()
{
    std::vector<int> vector = {1, 2, 3, 4, 5, 2, 2, 2};

    std::cout << countLessThan(vector, 3) << '\n';
    return 0;
}

【讨论】:

  • 一个小问题。当然,最好在 lambda 中通过值而不是通过引用来捕获 value。在不必要的情况下养成通过参考捕获的习惯可能是灾难性的。
猜你喜欢
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 2012-04-04
  • 2020-08-03
  • 2012-05-27
  • 1970-01-01
相关资源
最近更新 更多