清除后如何将元素推入向量?
How to push elements to vector after it is cleared?
我得到了一个 n
元素的数组,并给出了一个整数 K
。我必须以相反的顺序打印 子数组 of 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
时会发生什么?这意味着如果 my_nums
不为空,则需要在 for 循环之后再次打印 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 << " ";
}
}
另外,请注意以下几点:
- Why aren't variable-length arrays part of the C++ standard?
- Why is "using namespace std;" considered bad practice?
尝试在外循环的末尾设置"count = 0"。
我得到了一个 n
元素的数组,并给出了一个整数 K
。我必须以相反的顺序打印 子数组 of 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
时会发生什么?这意味着如果 my_nums
不为空,则需要在 for 循环之后再次打印 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 << " ";
}
}
另外,请注意以下几点:
- Why aren't variable-length arrays part of the C++ standard?
- Why is "using namespace std;" considered bad practice?
尝试在外循环的末尾设置"count = 0"。