给定一个这样的数组:
{1, 3, 11, 2, 24, 13, 5....}
数组长度可能大于 1,000。
如果元素的值不合适,比如大于10,需要替换为合适的值。在这种情况下,通过线性插值计算出合适的值。
例如:
Arr = {1, 3, 11, 2, 24, 13, 5....};
新数组应该是:
NewArr = {1, 3, 3+(2-3)/2, 2, 2+(5-2)/3, 2+2*(5-2)/3, 5, ...}
为此,我必须知道不当元素的开始和结束索引。
The starting and ending index shall be (2,2) indicating the "11" and (4,5) indicating the "24, 13"
我试过 for 循环
。但效率不高。
然后我搜索了IPP API
,没有得到结果。 :(
有更好的主意吗?
感谢您的帮助,:)。
顺便说一句:IPP API
将是更好的选择。
更新:
示例代码:
int arr[] = {1, 3, 11, 2, 24, 13, 5....};
/// find the starting index and ending index of inappropriate values
/// (2,2) (4,5).
int i = 0;
std::map<int,int> Segments;
if(arr[i] > Threshold)
{
int b = i;
while(arr[i] > Threshold )
i ++;
int e = i;
Segments.insert(std::map<int,int>::value_type(b,e));
}
/// linear interpolation
for(std::map<int,int>::iterator i = 0; i != Segments.end(); i ++) /// len means the number of inappropriate segments
{
//// linear interpolation of each segments
int b = i->first;
int e = i->second;
int num = e - b + 1;
float step = (arr[e+1]-arr[b-1]) / num; // For short. The case that b=0 or e=len-1 is not considered.
for(int j = b; j <= e; j ++)
arr[j] = arr[j-1] + step;
}
更新 2:
感谢你的帮助。但基于这些问题的答案:Speed accessing a std::vector by iterator vs by operator[]/index?和 Why use iterators instead of array indices? ,两种形式(for vs iterator)的效率几乎相同。所以 iterator
可能不够好。
我通常使用 SIMD
作为优化选项,例如 IPP API
。但我没有弄清楚,因为所有的 find
API 都只获取指定元素的第一次出现。
如果有一天我想通了,我会更新解决方案。 :)
最佳答案
如果您想搜索特定值,并替换 vector 中符合特定条件的项目,则可以使用 transform() 在一行中完成。
也可以使用replace_if(),但鉴于你的问题描述模糊,我不知道替换值是否需要根据原始值而变化(replace_if 需要一个恒定的替换值)。因此,让我们暂时使用 std::transform()。
#include <algorithm>
#include <vector>
struct Transformer
{
bool ThisNumberNeedsTransformation(int num) {
// you fill this in. Return true if number needs to be changed, false otherwise
}
int TransformNumber(int num) {
// you fill this in. Return the changed number, given the original number.
}
int operator()(int num)
{
if ( ThisNumberNeedsTransformation(num) )
return TransformNumber(num);
return num;
}
};
int main()
{
std::vector<int> intVector;
//...
std::transform(intVector.begin(), intVector.end(), intVector.begin(), Transformer());
}
基本上,该结构用作函数对象。对于 intVector 中的每个项目,函数对象将对该数字进行操作。如果数字符合条件,则转换并返回数字,否则返回原始数字。
由于您没有真正阐明更改数字的标准,因此这种方法为您的问题的解决方案提供了更大的灵 active 。您需要做的就是填写我在 Transformer
结构中打开的两个函数,然后事情就会正常进行。
如果您的需求更复杂,可以扩展函数对象 Transformer 以包含成员变量,或者简单地说,可以根据您的意愿进行复杂化。
另请记住,如果您正在为这些事情计时,请为发布、优化构建计时。不要计时“调试”或未优化的构建。
关于c++ - 数组( vector )中大于某个值的元素的起始索引和结束索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137206/