如何在清除后将元素推送到矢量
How to push elements to vector after it is cleared?
我得到了一个n
元素的数组,并给出了一个整数K
。我必须以相反的顺序打印K
元素的子数组。
我将元素存储在向量中并增加计数。计数等于 K
后,以相反的顺序打印矢量并清除矢量的所有元素。
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t; // No of test cases
cin >> t;
while (t--)
{
// Size of array and The size of each group
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
vector <int> my_nums;
int count = 0;
for (int i = 0; i < n; i++)
{
my_nums.push_back(arr[i]);
count++;
if (count == k)
{
for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
{
cout << *it << " ";
}
//Clear all elements in vector
my_nums.clear();
}
}
cout << endl;
}
return 0;
}
ex:
I/P:
1
8 3
1 2 3 4 5 6 7 8
Expected O/P:
3 2 1 6 5 4 8 7
Actual O/P:
3 2 1
您还需要重置count
。除此之外,在打印my_nums
载体中的元素后,应清除该矢量。
count++;
if (count == k)
{
for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
{
cout << *it << " ";
}
my_nums.clear(); // moved to here
count = 0; // --> reset here
}
但是当count < k
但i >= n
时会发生什么?这意味着如果 for 循环不为空,则需要在 for 循环后再次打印my_nums
my_nums
以获得完整的结果。
for (int i = 0; i < n; i++)
{
// above code
}
if (!my_nums.empty())
{
for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
{
cout << *it << " ";
}
}
另外,请注意以下几点:
- 为什么可变长度数组不是C++标准的一部分?
- 为什么我不应该 #include ?
- 为什么"使用命名空间 std;"被认为是不好的做法?
尝试在
外部循环的末尾设置"count = 0"。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 如何在清除后将元素推送到矢量
- 插入到映射中的元素在函数执行后清除
- 在函数返回时,清除了添加到一对int和字符串向量的矢量中的元素
- 从std::list中清除元素的顺序是什么
- c++在Unix编译器上清除字符串中的Windows新行元素