0

How can I get a vector with wanted size?

/*Hello, I need your help? Task: There is int vector and I try to make it shorter by deleting max element in it. Do this steps until dont get vector with proper length. d-original length of vector n1-wanted length of vector*/ #include <iostream> #include <vector> using namespace std; int main(int argc, char *argv[]) { vector<int> v; v={-10, -9, -9, 2, -10, -5, 7, -9, 7, -10, -5, -4, 2, 10, 9, 1, -4, 9, -5, -7, 0, 1, 6, -4}; int d=v.size(), n, n1=22, d2=d; cout<<d<<endl; for(int i=0; i<d; i++) { cout<<v[i]<<" "; } cout<<endl; while(d2 > n1) { n=v[0]; for(int i1=d-1; i1>0; i1--) { if(v[i1]>n) n=v[i1]; } cout<<"n: "<<n<<" d: "<<d<<endl; for(int i=d; i>0; i--) if(v[i]==n) for(int j=i; j<d-1; j++) { v[j]=v[j+1]; i--; } d--; d2--; } cout<<v.size()<<" "<<d<<endl; for(unsigned i=0; i<v.size(); i++)

29th Dec 2023, 3:14 PM
TeaserCode
2 Answers
+ 3
TeaserCode Literally the sentence you described the task, can be expressed by these 4 lines of code: size_t max_size = 10; while (v.size() > max_size) { auto max = max_element(v.begin(), v.end()); v.erase(max); } https://sololearn.com/compiler-playground/cGlLvmH08W3j/?ref=app
30th Dec 2023, 12:04 AM
Tibor Santa
Tibor Santa - avatar
0
No true, because you have to find max element in every iteration, and when you find it cut the size of vector for one element until you reach wanted length.
29th Dec 2023, 8:19 PM
TeaserCode