2016-05-08 72 views
0

我正在閱讀這個線程Array slicing in c++,接近我正在尋找,但不完全。我想從int數組中移除前3個元素。整數陣列切片

我有什麼現在:

void shiftArray(int *arr, int size) { 
    for (int i = 0; i < size - 3; i++) { 
     arr[i] = arr[i + 3]; 
     arr[i + 3] = -1; // can't re size array so set them to -1 
    } 
} 

我想:

int* shiftArray(int *arr, int size) { // return type can stay void if possible 
    return arr[3::]; // python 
} 

是否有可能有一個非迭代的方法進行前三個元素轉移到最終用值-1並移動其餘的元素以取代它們的位置?

+1

如果你想調整陣列中使用矢量數組類,但如果你只是想轉移我可以送你這對你做這個代碼。 –

+1

改爲使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。它有'erase()'方法。 –

+0

@Bahman_Mokri如果代碼比我的代碼好,那麼請是 – JGerulskis

回答

3

您可以使用std ::旋轉和std ::填充:

std::fill(std::rotate(arr, std::begin(arr) + 3, std::end(arr)), std::end(arr), -1); 

http://coliru.stacked-crooked.com/a/b3e0557ee0481162

...但是,它不是優雅的PHP :-)

[編輯]

以上要求C++ 11與以下C++標準版本兼容:

template<typename T, size_t n> 
void left_shift(T (&arr)[n], size_t left_shift){ 
    assert(left_shift < n); 
    std::fill(std::rotate(arr, arr + left_shift, arr + n), arr + n, -1); 
} 

left_shift(arr, 3); 

http://coliru.stacked-crooked.com/a/c09c27e3ebd60952

+0

看起來不錯,唯一的問題是我得到一個錯誤,說'沒有重載函數的實例「std :: begin」與參數列表' – JGerulskis

+0

@JGerulskis匹配,也許你沒有C++ 11兼容編譯器,或者沒有啓用c + + 11支持。 – marcinj

0

使用這種功能,它只是刪除舊,並通過轉移細胞返回新的int數組的指針,我只想提東西shiftStartIndex就是要從直到陣列的上端移動這樣的新大小數組將會是(size - shiftStartIndex),這樣可以防止數組脫離索引,我希望這會很有用。

int *shiftArray(int *, int, int); 

int main() 
{ 
    int size = 6; 
    int *b = new int[size]{ 1, 2, 3, 4, 5, 6 }; 

    int shiftStartIndex = 3; 

    b = shiftArray(b, size, shiftStartIndex); 

    int newSize = size - shiftStartIndex; 

    for (int i = 0; i < newSize; i++) 
    { 
     cout << b[i] << " "; 
    } 

    cin.ignore(); 
    return 0; 
} 

int *shiftArray(int *arr, int size, int stIndex) 
{ 
    int *a = new int[size - stIndex]; 

    for (int i = 0; i < size - stIndex; i++) 
    { 
     a[i] = arr[i + stIndex]; 
    } 

    delete[] arr; 

    return a; 
} 
1

這聽起來像你想要使用可調整大小的數組就地移除前3個元素。

C++中的可調整大小的數組稱爲std::vector。構造函數std::array和C風格的數組不可調整大小。

在通用的形式的代碼可以是:

template<size_t N, typename T> 
void erase_start(std::vector<T> &arr) 
{ 
    if (arr.size() <= N) 
     arr.clear(); 
    else 
     arr.erase(arr.begin(), arr.begin() + N); 
} 

沒有一個-盆栽預向量成員函數基於計數擦除,只需要迭代器。但是你可以很容易地做出這樣的功能。

調用可能看起來像:

std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7 }; 
erase_start<3>(vec); 
+0

注意:如果您希望主要保持數組完整,但將數組的部分視圖呈現給某個函數,那麼採用與此不同的方法會更好 –