c++ - 如何在带有 X 个元素的 std::vector 中从 p 中提取 n 个元素
问题描述
我有一个包含 X 元素的向量,如何从向量中从 p(示例中为 6)中提取 n 个元素(下例中为 3)?这是我的做法。
//vector<int> a;
std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
int X = a.size();
// code to extract 3 elements of 6 until the end of the vector
for (int i=0; i< a.size(); i+=6)
{
if (i >= a.size())
{
break;
}
else
{
sub_indices.push_back(i);
}
if ( (i+1) >= a.size())
{
break;
}
else
{
sub_indices.push_back(i+1);
}
if ((i+2) >= a.size())
{
break;
}
else {
sub_indices.push_back(i+2);
}
}
显示结果将输出:
10 11 12 (drop three elements) 16 17 18 (drop three elements) 22 23 24 (drop three elements) 28 29 30 (drop three elements) 34 35
我是这样做的,但谁能告诉我一个更有效的方法?
解决方案
这是解决方案:
#include <vector>
#include <iostream>
int main () {
// Better to initilize the vector like this instead of using multiple push_back
std::vector<int> a;
for (int i=10; i<36; ++i)
a.push_back (i);
// Here is another method to initilize your vector:
// std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
// 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
// Here you loop over all elements and only select the three first elements
// of every six elements:
for (int i=0; i<a.size(); ++i)
if (i%6 < 3)
std::cout << a[i] << std::endl;
return 0;
}
% 运算符给出两个 int 值相除的余数。
推荐阅读
- google-cloud-platform - 为 pod 和服务配置 Terraform GKE 插件 IP 范围
- python - 如何确定初始猜测值并最小化以找到参数
- arrays - MongoDB:使用数组进行聚合
- ms-access - 将列表框中的选定项目与单选按钮相结合保存到新字段中
- javascript - jQuery 不在 Primefaces 视图中执行?
- java - 比较两个文本时如何找到不相似的行
- c++ - 如何访问一行 C++ 字符矩阵?
- angular - 向 Angular 材质禁用字段添加验证
- algorithm - Fence - 波兰信息学奥林匹克竞赛的任务
- websphere - IBM Edge 组件执行器在运行时出错