I am a 10th grade student have just started competitive programming. I was recently was solving this.
While trying to solve this question I encountered this error.
prog.cpp:32:43: error: invalid types ‘[int*]’ for array subscript std::swap(a[p], *std::min_element[b,b+n]); ^ I tried to find a solution but have been stuck on this problem for almost a day.
This is my code:
#include <iostream>
#include <list>
#include <algorithm>
#include <functional>
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,k,a[100005]={0},b[100005]={0};
cin>>n>>k;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cin>>b[i];
sort(a,a+n);
sort(b,b+n);
int one = 0, two = 0, p = n - 1, j = n - 1;
for ( k>=0;k--) {
if(k==0){
cout<<*std::max_element(a,a+n)+*std::min_element(b,b+n)<< "\n";
}
if (a[p]>b[j]) {
std::swap(b[j], *std::min_element[a,a+n]);
j--;
one++;
}
if (a[p]<b[j]) {
std::swap(a[p], *std::min_element[b,b+n]);
p--;
two++;
}
}
return (0);
}
I would really appreciate if som eone would tell me what I am doing wrong. Also, please point out to anyways I can make my code better.
1 Answer 1
To improve your coding style, I suggest reading the linux kernel coding style document. Although it's not meant for C++, it can still be applied here.
Concerning the code itself, it feels like your getting ahead of yourself. I've cleaned it up a bit. It compiles with g++.
#include <iostream>
#include <list>
#include <algorithm>
#include <functional>
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,k,a[100005]={0},b[100005]={0};
cin>>n>>k;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
}
sort(a,a+n);
sort(b,b+n);
int one = 0, two = 0, p = n - 1, j = n - 1;
for (;k>=0;k--) {
if(k==0){
cout<<*max_element(a,a+n)+*min_element(b,b+n)<< "\n";
}
if (a[p]>b[j]) {
swap(b[j], *min_element(a,a+n));
j--;
one++;
}
if (a[p]<b[j]) {
swap(a[p], *min_element(b,b+n));
p--;
}
}
return 0;
}
Here's an overview of the things I changed:
- Used scoping '{}' to improve readability. It makes it much more clear what code is executed within a loop or if/else statement.
- Used tabs and spaces consistently throughout your snippet of code.
- Used the statement 'using namespace std;'. This basically means that everything within the standard library can be addressed without 'std::' in front of it. Hence 'std::swap()' becomes 'swap()' and so on. Do note that this is considered bad practice. Read the following on scopes and namespaces to understand them better.
- Changed the for loop to 'for(;k>=0;k--)'.A for loop typically has three items separated by semi-colons within the parenthesis. Item 1 is the initialization, you're not using it here. Item 2 is the condition to check, here 'k>=0'. Item 3 is the increment. Read this for more information. You can leave all three items blank (creating an infinite loop), but the two semi-colons need to be there.
min_elementis a function so call it with parenthesis () not square brackets []for (k >= 0; k--)loop looks suspect too...