[英]starting index and ending index of elements in a array(vector) that are greater than a value
給定這樣的數組:
{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;
}
Update2 :感謝您的所有幫助。 但是基於這些問題的答案: 通過迭代器還是通過operator [] / index來快速訪問std :: vector? 以及為什么使用迭代器而不是數組索引? ,兩種形式(對於vs迭代器)的效率幾乎相同。 因此, iterator
可能不夠好。
我通常使用SIMD
例如IPP API
作為優化選項。 但是我沒有弄清楚,因為所有的find
API僅獲得指定元素的第一次出現 。
如果有一天我會更新解決方案。 :)
如果要搜索特定值,並從向量中替換符合特定條件的項目,則可以使用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中的每個項目,函數對象都將對該數字進行操作。 如果數字符合條件,則將數字轉換並返回,否則返回原始數字。
由於您並未真正弄清楚更改數字的標准,因此這種方法為您解決問題提供了更大的靈活性。 您需要做的就是填寫我在Transformer
結構中打開的兩個函數,然后一切正常。
如果您的需求更加復雜,則可以擴展功能對象Transformer以包括成員變量,或者只是簡單地將其擴展為您想要的復雜程度即可。
還請記住,如果您正在安排這些時間 ,請安排發布,優化的構建 。 不要計時“調試”或未優化的構建。
我不確定“不適當元素的開始和結束索引”是什么意思,所以我將假設您只是指索引 。
在這里使用向量將是一個好方法:
std::vector<int> the_stuff {1, 3, 11, 2, 24, 13, 5, ... };
std::vector<int>::iterator it = the_stuff.begin();
while (it != the_stuff.end()
{
if (*it > 10) { // do stuff };
etc.
}
你明白了。 使用vector ,它應該使您更輕松。 閑暇時搜索/插入/獲取索引/刪除/等等。
如果將數字存儲在std :: vector中,則可以通過迭代器在數組上進行迭代。 一旦找到滿足條件並需要刪除的元素,就可以刪除它,同時將迭代器分配給下一個元素。 這將是最有效的方法:
您的代碼如下所示:
std::vector<int> intVector;
for(auto it = intVector.begin(); it != intVector.end(); ++it)
{
if (*it > 10)
{
it = intVector.erase(it);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.