【发布时间】:2014-04-17 15:27:57
【问题描述】:
给定一个这样的数组:
{1, 3, 11, 2, 24, 13, 5....}
数组长度可能大于 1000。
如果元素的值不合适,比如大于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 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 都只获得指定元素的第一次出现。
如果有一天我弄清楚了,我会更新解决方案。 :)
【问题讨论】:
-
向我们展示一些你的代码怎么样?
-
您是否尝试过简单地使用例如
std::replace_if替换错误的值?虽然“大于 1000”可以表示从 1001 到无穷大的任何值,但在现代计算机上迭代数组中的数千个条目确实很快。 -
@JoachimPileborg,我必须通过线性插值计算新值。恐怕
std::replace_if行不通。 -
@Steve - 然后看看我作为答案给出的 std::transform 算法函数。函子会稍微复杂一点,但它应该可以工作。