小编joe*_*pol的帖子

如何在函数参数中强制类型并避免隐式转换?

我有一个功能

template<typename T>
static inline bool Contains(T container, const typename T::value_type& value)
{
    return std::find(container.begin(), container.end(), value) != container.end();
}
Run Code Online (Sandbox Code Playgroud)

是否有选项禁止此函数的隐式转换?

这段代码应该编译失败:

std::vector<int> vec = {1, 2, 3};
Contains(vec, -5.2);
Run Code Online (Sandbox Code Playgroud)

在这篇文章中,如何避免对非构造函数进行隐式转换?它们完全消除了某些类型的使用,但事实并非如此。

谢谢。

c++ templates implicit-conversion

4
推荐指数
1
解决办法
86
查看次数

Get the closest element to a given element in an std::set

I have a (sorted) set of unsigned int's. I need to find the closest element to a given number.

I am looking for a solution using the standard library, my first solution was to use binary search, but STL's implementation only returns if the element exists. This post, Find Closest Element in a Set, was helpful and I implemented a solution based on std::lower_bound method,

(*Assuming the set has more than 2 elements, no empty/boundary checks are …

c++ stl set

3
推荐指数
1
解决办法
91
查看次数

根据模式用数字填充 C++ 数组

我有一个要填充数组的模式:

偶数指数值 = -1

奇数指数值 = 1

我目前是这样实现的:

#include <array>
#include <algorithm>

using namespace std;
int generator(){
    static int i = 1;
    i *= -1;
    return i;
}

std::array<int ,64> arr;
std::generate(arr.begin(), arr.end(), generator);
Run Code Online (Sandbox Code Playgroud)

编辑:当前实现有一个警告 - 的返回值generator不依赖于迭代的对象索引。

有没有办法将当前索引传递给generator函数,使其输出取决于该索引?

c++ lambda c++17

3
推荐指数
1
解决办法
118
查看次数

使用 C++20 的 std::popcount 和向量优化是否等同于 popcnt 内在?

C++20 引入了许多新函数,例如std::popcount,我使用Intel Intrinsic使用相同的功能。

我编译了这两个选项 - 可以在编译器资源管理器代码中看到:

  1. 使用英特尔的 AVX2 内在
  2. 使用 std::popcount 和 GCC 编译器标志“-mavx2”

除了 std 模板中使用的类型检查之外,生成的汇编代码看起来是相同的。

就操作系统不可知代码并具有相同的优化而言 - 假设使用std::popcount和 apt 编译器向量优化标志比直接使用内在函数更好是否正确?

谢谢。

c++ intrinsics language-lawyer avx2 c++20

2
推荐指数
1
解决办法
301
查看次数

为什么“应使用 'empty' 方法来检查是否为空,而不是使用 clang-tidy 的 'size”?

执行检查时:

std::string st = "hello";
bool is_empty = st.size() > 0;
Run Code Online (Sandbox Code Playgroud)

我收到了上面提到的 Clang-Tidy 警告。

为什么最好使用该empty()方法?

c++ containers std stdvector clang-tidy

0
推荐指数
1
解决办法
334
查看次数