2017-03-02 82 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