假设我有一个这样的数组:
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
以上的所有值。
我还没有找到足够的文档或示例来说明这一点,我认为数组操作和拆分值得拥有这些示例。
发布于 2017-03-02 23:27:28
使用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 << " ";
}
发布于 2017-03-02 23:17:42
如果您可以使用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
发布于 2017-03-02 23:56:41
我正在研究一个使用循环的解决方案。这是一项正在进行的工作。让我知道你的想法。
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;
}
}
}
https://stackoverflow.com/questions/42567699
复制相似问题