我是一名 10 年级的学生,刚刚开始竞争性编程。我最近正在解决 this .
在尝试解决这个问题时我遇到了这个错误。
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.
这是我的代码:
#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);
}
如果有人能告诉我我做错了什么,我将不胜感激。另外,请指出无论如何我可以改进我的代码。
最佳答案
为了改进您的编码风格,我建议阅读 linux kernel coding style document .虽然它不是针对 C++ 的,但它仍然可以在这里应用。
就代码本身而言,感觉像是在超前。我已经清理了一下。它使用 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;
}
以下是我所做更改的概述:
- 使用范围“{}”来提高可读性。它使循环或 if/else 语句中执行的代码更加清晰。
- 在整个代码片段中始终如一地使用制表符和空格。
- 使用了语句“using namespace std;”。这基本上意味着标准库中的所有内容都可以在前面没有'std::'的情况下被寻址。因此 'std::swap()' 变成 'swap()' 等等。请注意,这被认为是 bad practice .在 scopes and namespaces 上阅读以下内容更好地理解它们。
- 将 for 循环更改为“for(;k>=0;k--)”。for 循环通常包含在括号内用分号分隔的三个项目。第 1 项是初始化,您不会在此处使用它。第 2 项是要检查的条件,此处为 'k>=0'。第 3 项是增量。阅读this了解更多信息。您可以将所有三个项目留空(创建一个无限循环),但两个分号必须存在。
关于c++ - 数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268172/