std::vector 中查找某个元素是否存在

std::vector 中不存在直接查找某个元素是否存在的方法,一般是通过 <algorithm> 中的 std::find, std::find_if, std::count, std::count_if 等方法的返回值来判断对应元素是否存在。

如当vector中存储的元素为 double 类型时,需要设定其精度,判断代码如下

#include <vector>
#include <algorithm>

double targetVal = 0.01;
vector<double> vec = { 0, 0.005, 0.01, 0.01, 0.015, 0.02, 0.02, 0.025, 0.03, 0.035 };

// 根据默认的精度进行判断
int res2 = std::count(vec.begin(), vec.end(), targetVal);
// 使用Lambda表达式,来根据一定的条件进行判断
int res3 = std::count_if(vec.begin(), vec.end(), [ & ](double val)
{
    return fabs(targetVal - val) < 1e-7;
});

// 根据默认精度进行判断
auto it = std::find(vec.begin(), vec.end(), targetVal);
// 使用Lambda表达式,根据是否符合指定条件来进行判断
auto itIf = std::find_if(vec.begin(), vec.end(), [&](double val)
{
    return fabs(targetVal - val) < 1e-7;
});

if(it != vec.end()) // 迭代器不等于 vec.end() 时,表示容器中存在该值
{
    size_t index = std::distance(vec.begin(), it);
    double val = vec[index];
}

posted @ 2024-07-08 11:11  Jeffxue  阅读(73)  评论(0编辑  收藏  举报