从数组

时间:2018-03-28 14:27:55

标签: c++ arrays

我有一个跨越如下的数组。因此,要理解的示例是考虑具有6个面的块。该数组包含此数组中的索引,特定颜色的面将从该索引开始。

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

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

但阵列并不总是这样。如果只有一个颜色的块,则该数组看起来像

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完成此操作。请帮忙

5 个答案:

答案 0 :(得分:1)

你会做同样的事情,循环遍历数组来搜索你想要的术语。当然,如果它是一个排序的数组,那么速度会更快,所以类似于prehaps:

for(int i = 0; i < arraySize; i++){
 if(array[i] == itemToFind){
     break;
 }
}

答案 1 :(得分:1)

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

然后您可以使用以下二分搜索。

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

答案 2 :(得分:0)

您非常接近正确的解决方案,只需将array[index] < input更改为array[index] > input

#include <iostream>
#include <vector>
std::vector<int> array = {0, 2, 4, 5};
int subs(int input)
{
    for (int index = 0; index < array.size(); ++index) 
    { 
        if (array[index] == input) 
        { 
            return index; 
        } 
        if (array[index] > input) 
        { 
            return index - 1; 
        } 
    }
    return -1;
}
int main(int argc, const char *argv[])
{
    for (int i = 0; i <= 5; i++) {
        std::cout<<"input: "<<i<<" "<<"color: "<<subs(i)<<std::endl;
    }
    return 0;
}

这给出了:

input: 0 color: 0
input: 1 color: 0
input: 2 color: 1
input: 3 color: 1
input: 4 color: 2
input: 5 color: 3

答案 3 :(得分:0)

我也使用了for循环,但是如果条件检查输入是否等于数组中的任何元素,则使用break。

{{ form_row(form._token) }}

答案 4 :(得分:0)

另一种可能更简单的解决方案:

int findIndex( const std::vector<int>& vec, int input )
{
    int count = vec.size()-1;
    for ( auto it = vec.rbegin(); it != vec.rend(); it++)
    {
        if ( *it<=input )
        {
            return count;
        }
        count--;
    }

    return -1; // if nothing found
}

int main()
{
    std::vector<int> vec { 0,2,4,5 };

    for ( int input=0; input <=5; input++)
    {
        std::cout <<  findIndex( vec, input ) << " " << input << std::endl;
    }
}

输出:

0 0
0 1
1 2
1 3
2 4
3 5