c++ - 从数组中查找元素

标签 c++ arrays

我有一个跨度如下的数组。所以要理解的例子是考虑一个有 6 个面的 block 。该数组包含此数组中的索引,特定颜色的面将从该索引开始。

array[0] 0
array[1] 2
array[2] 4
array[3] 5

所以这意味着颜色 0 用于面 0 和 1,颜色 1 用于面 2 和 3, 颜色 2 仅适用于面 4

但数组并不总是这个样子。如果有一个只有一种颜色的 block ,则数组看起来像

array[0] 0
array[1] 1 

这意味着面 0 的颜色为 0,面 1,2,3,4,5 的颜色为 1

我会得到一个输入作为面号,需要找到相应的颜色

我用for循环试过了

for (int index = 0; index < array.size(); ++index) 
{ 
    if (array[index] == input) 
    { 
        return index; 
    } 
    if (array[index] < input) 
    { 
        return index - 1; 
    } 
}

但答案并不总是正确的。这可以用 while 来完成吗?请帮忙

最佳答案

据我了解,您想找到小于或等于给定输入的数组的最大索引。

然后您可以将以下内容与二进制搜索一起使用。

std::size_t getIndexFor(const std::vector<int>& v, int input)
{
    auto it = std::lower_bound(v.begin(), v.end(), input);
    if (it != v.begin() && (it == v.end() || *it != input)) {
        --it;
    }
    return std::distance(v.begin(), it);
}

Demo

更简单(和线性)的方式:

std::size_t getIndexFor(const std::vector<int>& v, int input)
{
    auto it = std::find_if(v.begin(), v.end(), [&](int e){ return e > input;});
    if (it == v.begin()) {
        throw std::runtime_error("input not handled");
    }
    --it;
    return std::distance(v.begin(), it);
}

Demo

关于c++ - 从数组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537198/

相关文章:

c - 二维数组,其中每行都有不同类型的结构指针

javascript - 当 ng-repeat 上的复选框具有 required 属性时,Angular ng-model 更改为未定义

python - 使用现有 C 对象初始化 Cython 对象

c - 为什么在 C 中声明一个只包含数组的结构?

c++ - 为什么我的调试器有时会崩溃并做出与我的代码不一致的事情?

c++ - 将运算符转换为瘦包装器派生类中的基类

javascript - 当从方法体中执行对数组的推送时,数据是否不会保留在方法体范围之外?

php - 为什么一个简单的 PHP 数组查找这么慢?我在这里做错了什么吗?

c++ - 在 C++ 中对 typedef struct 数组使用什么

c++ - 您将如何编写可能优化为一条 SSE 指令的无符号加法代码?