过滤向量并返回第 n 个元素

Filter a vector and return the 'n'th element

本文关键字:元素 返回 向量 过滤      更新时间:2023-10-16

我想编写一个函数,该函数可以延迟计算并返回过滤向量的第 n 个元素。大多数时候,我对向量中的第一个或第二个元素感兴趣。所以我不想过滤整个列表,然后找到第 n 个元素。

我正在学习使用Boost,如果有一个简单的解决方案使用Boost,那将是非常有启发性的。

int main() {
    double x[] = {10, 12.5, 12.9, 13.7, 50.07};
    size_t length = sizeof(x)/sizeof(x[0]);
    std::vector<double> vx(x, x+length);
    // Need a function to filter out elements less than 11 and return the 2nd
    // element greater than 11 (here 12.9) and return without evaluating 13.7 and 50.07

    return 0;
}

如果您对第一个元素之一感兴趣,我会天真地建议这样的东西:

std::vector<double>::iterator element(size_t n, const std::vector<double>& vec) {
    std::vector<double>::iterator it = vec.begin();
    size_t found = 0;
    while (found != n && it != vec.end()) {
        if (*(it++) >= 11) ++found;
    }
    return it;
}

我有一个线性复杂性,但一旦找到所需的匹配项就会退出。

使用std::partition

float n=11.f;
auto it =std::partition(vx.begin(), vx.end(), 
                       [n](const double & p){ return p <n;});
 it++; //Second element
 if( it!= vx.end())
    std::cout<<"Element :"<<*it<<std::endl;

这里

我不知道

如何使用boost,但这是我会使用的:

int binarySearch(int whatToSearch){
    //recursive binary search 
    if value is found 
        return index
    else //not found
        return -index-1; //-index+1 will give you the place to insert that element    
}

然后,如果存在,我将在返回索引后获得第二个元素。

这是我使用的二叉搜索代码

int mybinary_search(string array[],int first,int last, string search_key){
    int index;
    if (first > last)
        index = -first-1;
    else{
        int mid = (first + last)/2;
        if (search_key == array[mid])
            return mid;
        else if (search_key < array[mid])
        index = mybinary_search(array,first, mid-1, search_key);
        else
            index = mybinary_search(array, mid+1, last, search_key);
    } // end if
    return index;
}
double findAskedValue(int value){
    double x[] = {10, 12.5, 12.9, 13.7, 50.07};
    size_t length = sizeof(x)/sizeof(x[0]);
    int index = mybinarySearch(x,0,length, 11);
    if(index >= 0)
         cout << "value I'm searching for " << x[index+2] << endl;
    else
         cout << "value I'm searching for " << x[(-index-1)+2] << endl;
     //instead of cout's you can do what ever you want using that index
}

一个小解释:你要调用findAskedValue(val),它会给你一个值。如果值> 0,则元素存在于列表中,index+2 是您要搜索的值的位置,否则 (-index-1) 是插入该元素的位置。 -index-1 + 2 将为您提供第二个更大的元素。

其复杂性O(log(n))