给定一个这样的数组:
{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, ...}
为了做到这一点,我必须知道不合适元素的开始和结束索引。
开始和结束索引应为 (2,2) 表示“11”和 (4,5) 表示“24, 13”
我试过了for loop
。但效率不高。然后我搜索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 access a std::vector by iterator vs by operator[]/index? 为什么使用迭代器而不是数组索引?,两种形式(for vs iterator)的效率几乎相同。所以iterator
可能还不够好。
我通常使用SIMD
诸如IPP API
优化选项。但我没有弄明白,因为所有find
API 只获得指定元素的第一次出现。
如果有一天我弄清楚了,我会更新解决方案。:)