2017-03-02 37 views
3

說我有一個這樣的數組的數組:分割在一個特定的值C++

int arr [9] = {2,1,5,8,9,4,10,15,20} 

你怎麼能在一定值閾值分割陣列?所以說int 8是我們的分割值,最終結果將是兩個單獨的數組(如果你想給出一個鏡頭,則是一個2d數組),在這個例子中將是arr1 [4] = {1,2,4,5}arr2 [5] = {8,9,10,15,20}arr1存儲arr中低於8的所有值,而arr2存儲arr中所有值爲8及以上的值。

我一直無法找到足夠的文檔或這個正在做的例子,我認爲數組操作和分割值得有例子。

+1

數組大小是編譯時常量。你不能在運行時這樣做,因爲在編譯時不可能知道結果數組的大小。這隻能使用動態分配('new int [x]'),使用動態容器(如'std :: vector '),或者如果你的數組是一個常量表達式。無論如何,你不能「收縮」一個數組。你會留下'arr',大小爲9'int's。 –

+1

棘手的數組。他們不分裂。您將不得不創建兩個正確尺寸的新陣列,並將原始文件複製到新文件中。如果你不太在乎,可以保持原始數組完整無缺,並將索引或指針傳遞給開始和結束,並簡單地將它顯示爲兩個單獨的數組。 – user4581301

+1

可能通過創建一個新數組,然後查找閾值。閾值後的所有項目都*複製到新陣列。 –

回答

3

使用std::partition,或者如果你想保持的相對順序,而不是數據std::stable_partition排序。

#include <algorithm> 
    #include <iostream> 
    #include <vector> 

    int main() 
    { 
     int pivot = 8; 
     int arr [9] = {2,1,5,8,9,4,10,15,20}; 

     // get partition point 
     int *pt = std::stable_partition(arr, std::end(arr), [&](int n) {return n < pivot;}); 

     // create two vectors consisting of left and right hand side 
     // of partition 
     std::vector<int> a1(arr, pt); 
     std::vector<int> a2(pt, std::end(arr)); 

     // output results 
     for (auto& i : a1) 
      std::cout << i << " "; 
     std::cout << '\n'; 
     for (auto& i : a2) 
      std::cout << i << " "; 
    } 

Live Example

2

如果你可以使用C++ 11,那麼這是使用標準庫的一種方式:

使用partition_point:(編輯從鏈接例子)

#include <algorithm> 
#include <array> 
#include <iostream> 
#include <iterator> 
#include <vector> 

int main() 
{ 
    std::array<int, 9> v = {2,1,5,8,9,4,10,15,20}; 

    auto is_lower_than_8 = [](int i){ return i < 8; }; 
    std::partition(v.begin(), v.end(), is_lower_than_8); 

    auto p = std::partition_point(v.begin(), v.end(), is_lower_than_8); 

    std::cout << "Before partition:\n "; 
    std::vector<int> p1(v.begin(), p); 
    std::sort(p1.begin(), p1.end()); 
    std::copy(p1.begin(), p1.end(), std::ostream_iterator<int>(std::cout, " ")); 

    std::cout << "\nAfter partition:\n "; 
    std::vector<int> p2(p, v.end()); 
    std::sort(p2.begin(), p2.end()); 
    std::copy(p2.begin(), p2.end(), std::ostream_iterator<int>(std::cout, " ")); 
} 

它打印:

Before partition: 
    1 2 4 5 
After partition: 
    8 9 10 15 20 
0

我正在用循環的解決方案。這是一個正在進行的工作。讓我知道你的想法。

void splitarr(int arr[], int length) { 
    int accu = 0; 
    int accu2 = 0; 
    int splitter = rand() % 20; 
    for (int i = 0; i < length; i++) { 
     if (i != splitter) { 
      accu++; 
     } 
    } 
    int arr1[accu]; 
    for (int i = 0; i < length; i++) { 
     if (i != splitter) { 
      arr1[i] = i; 
     } 

    } 

    for (int i = 0; i < length; i++) { 
     if (i == splitter) { 
      accu2++; 
     } 
    } 
    int arr2[accu2]; 
    for (int i = 0; i < length; i++) { 
     if (i == splitter) { 
      arr2[i] = i; 
     } 

    } 
} 
+0

這行'int arr1 [accu];'和這樣的行是無效的C++。數組必須使用常量來聲明,以表示條目的數量,而不是變量。爲什麼不使用已經提供的解決方案,即使用分區功能? – PaulMcKenzie