过滤向量并返回第 n 个元素
Filter a vector and return the 'n'th element
我想编写一个函数,该函数可以延迟计算并返回过滤向量的第 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))
相关文章:
- lower_bound()返回最后一个元素
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 反转后不返回最后一个元素
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 第 i 个元素返回 i 的函数数组
- 将新元素添加到列表中,并返回对该元素的引用?
- C++ 将向量中出现 n 次的所有元素作为向量返回
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 返回向量元素的 l 值的正确方法是什么?
- C++函数返回两个 char 数组的相同索引元素
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 函数返回包含输入容器的特定元素的容器
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 返回纯虚拟基类的向量的元素
- 比较 C++ 中的两个数组,并根据元素的匹配或不匹配返回值
- 在位置 i 处插入元素,并根据 i 第一个元素返回信息