C++从数组中获取前n个元素
C++ take first n elements from array
使用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或其他什么,只要它是一个广泛使用的库),那么我会接受一个答案,它提供了令人信服的证据,证明不存在这样的解决方案。
如果你使用向量(你应该使用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);
您不能追加到像points
这样的普通C样式数组(实际上,如果声明没有生成编译器错误,我会感到惊讶)。试图附加到C样式数组会写得越界,导致未定义的行为(这里我也很惊讶std::back_inserter
在传递C样式数组时会编译)。
而是使用std::vector
。
来自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;;
}
我会将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);
相关文章:
- 对于set上的循环-获取next元素迭代器
- 在 alglib::real_1d_array 中获取元素总和的奇怪错误
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- push_back通过自行创建的对象获取最后一个元素的向量
- 从自定义类获取对象向量中的 max 元素
- 从 c++ 中的链表中获取元素
- 比较它们之间的元素并获取公共值的键
- 获取指向指针的指针元素 (c++)
- CPtrList - 如何获取元素的索引?
- 如何从一个容器中获取某些元素并将其转换插入到另一个容器中?
- 获取结构 c++ 中元素的索引
- 如何获取指针数组中的元素数量?
- 在std::集中获取与给定元素最接近的元素
- 无法获取已填充堆栈<char>的顶部元素
- 检查HTML 5视频元素是否正在获取帧
- 有没有函数可以直接获取 std::vector 元素的大小?
- 从矢量的元素获取指针
- 从 /dev/sd* 元素获取 /dev/disk/by-id 元素
- 2d查找重复元素/获取索引位置并计数重复项
- 为什么来自 rvalued-stl-container 的元素获取者返回左值