用C++从数组中取出前n个元素

8
使用C ++,我想创建一个数组,其中仅包含另一个数组的前n个元素。在Scala中如下:val arrayTwo = arrayOne.take(n) 我知道可以使用循环并逐一复制元素,但这比必要的更复杂,它占用了不必要的空间,这使得它不易读。是否有一个简单易读的函数,可以从给定的先前数组的前n个元素创建一个新的数组?此外,我想重用某个地方的函数,而不是编写自己的函数,因为我不想不必要地污染命名空间。只要花费O(n)时间,性能无关紧要。
std :: copy_n看起来像它,但我无法使其工作,因为由于某种原因,std :: back_inserter不接受我的数组(我还尝试使用指针而不是数组,仍然无法工作)。
这是迄今为止我最好的尝试。
#include <iostream>
#include <utility>
#include <algorithm>
#include <vector>
#include <iterator>
#include <stdio.h>
#include <math.h>

using std::pair;

int main() {
  pair<double, double> fabricatedPoints[] = { { 15.3, 12.9 }, { 88.6, 56.0 },
            { 0.4, 18.0 }, { 5.0, 3.13 }, { 2.46, 86.01 } };
  pair<double, double> points[] = {};
  std::copy_n(std::begin(fabricatedPoints), 3, std::back_inserter(points));
}

这可以通过copy_n或其他方式完成,只要可读即可。如果没有在库中找到可读解决方案(不一定是标准库 - 也可以是Boost或其他广泛使用的库),那么我将接受提供有力证据证明不存在这样的解决方案的答案。


如果你看重代码可读性,有什么理由不使用 std::vector 吗? - 5gon12eder
没有,我并没有太多使用C++,也不知道数组和std::vector之间的区别。 - Velizar Hristov
4个回答

12

如果你正在使用向量(而且你应该在使用C++),你只需要这样做:

using std::vector;
vector<pair<double, double>> a{ {15.3, 12.9}, ...};
vector<pair<double, double>> b(a.begin(), a.begin() + 3);

对于数组,您将需要确保预先分配正确大小的数组:

pair<double, double> b[3];
std::copy_n(a, 3, b);

1
你无法像对待普通的C风格数组points那样进行附加操作(实际上,如果声明没有生成编译器错误,我会感到惊讶)。尝试向C风格数组附加元素将会写入超出边界的位置,导致未定义行为(在这里,当向C风格数组传递std::back_inserter时,我也感到惊讶)。
相反,使用std::vector

“我很惊讶std::back_inserter在传递一个C风格的数组时会编译”,我认为它不会:“由于某种原因,std::back_inserter不接受我的数组”。 - svick
我知道。然而,std::back_inserter要求一个数组类型;由于代码在考虑points的大小之前失败了,所以我省略了它。 - Velizar Hristov
1
@svick 哦,我错过了,对我来说现在太早了(或者太晚了)。 - Some programmer dude

1

从C++20范围(#include <ranges>

只需使用take_view

//DATA
std::pair<double, double> fabricatedPoints[] = { { 15.3, 12.9 }, { 88.6, 56.0 },
    { 0.4, 18.0 }, { 5.0, 3.13 }, { 2.46, 86.01 } };

//USE take_view
auto points = std::ranges::take_view(fabricatedPoints, 2);

//TEST THEM
for (auto p : points)
{
     std::cout << p.first << "  " << p.second << std::endl;;
}

或者使用视图适配器

//YOUR DATA
std::pair<double, double> fabricatedPoints[] = { { 15.3, 12.9 }, { 88.6, 56.0 },
        { 0.4, 18.0 }, { 5.0, 3.13 }, { 2.46, 86.01 } };

//GET FIRST TWO POINTS
auto points = std::views::all(fabricatedPoints) | std::views::take(2);

//TEST THEM
for (auto p : points)
{
    std::cout << p.first << "  " << p.second << std::endl;;
}

1
该问题明确标记了 c++11。 - Cortex0101
不,还有C++标签。 - Pavan Chandaka

0
我会使用vector来完成这个任务。
vector<int> vec1;
vector<int> vec2;
vector<int> merged;

//insert(where you want to start adding, from which index, to which index)
//in this case we are adding the first to n-th elements from vec1 to the last element of merged 
merged.insert(merged.end(), vec1.begin(), vec1.begin() + n);

//here we are adding the m-th to n-th elements of vec2 to the first element of merged
merged.insert(merged.begin(), vec2.begin() + m, vec2.begin() + n);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接