The topic is not difficult, and the basic knowledge of arrays is examined. Therefore, I fell into the pit, and the basic knowledge is not solid.
Various problems arose with my various solutions:
1 Multiple groups of input problems
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
int m;
int r;
int i=0;
vector<int>v;
cin>>n>>m;
while(n--)
{
cin>>r;
v.push_back(r);
}
sort(v.begin(),v.end());
while(m--)
{
cout<<v[i]<<" ";
i++;
}
return 0;
}
Because I am not used to this cin double input problem, it is always easy to write it as a single input problem;
2 Local variables and global variables
int main()
{
int n;
int m;
int r;
int i=0;
vector<int>v;
while(cin>>n>>m)
{
for(int i=0;i<n;i++)
{
cin>>r;
v.push_back(r);
}
sort(v.begin(),v.end());
while(m--)
{
cout<<v[i]<<" ";
i++;
}
}
return 0;
}
This problem also occurs in 1. When printing, the i in the output v[i] should be set as a local variable, otherwise multiple sets of input will be wrong.
3 Array insertion problem
int main()
{
int n;
int m;
while (cin >> n >> m)
{
vector<int>v;
for (int i = 0; i < n; i++)
{
cin>>v.at(i);//cin>>v[i];
}
sort(v.begin(), v.end());
int j=0;
while(m--)
{
cout <<v[j]<<" ";
j++;
}
cout << endl;
}
return 0;
}
The answer prompts access to out-of-bounds overflow and other issues. After debugging, the problem appears that v is not given a certain space size when it is defined, so an error is reported.
Change it to:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
int m;
while (cin >> n >> m)
{
vector<int>v(n);
for (int i = 0; i < n; i++)
{
cin>>v.at(i);
}
sort(v.begin(), v.end());
int j=0;
while(m--)
{
cout <<v[j]<<" ";
j++;
}
cout << endl;
}
return 0;
}
Summarize:
1. Pay attention to the problem of global variables;
2. You can use v.push_back() for container insertion. When using v[i]/v.at(i), you need to define the size of the array to prevent out of bounds!
In short, pay attention to the details! ! ! !