C++ 尝试对c+中的对象数组进行排序时出现std:bad#alloc错误+;?
代码块抛出错误:std:bad\u alloc。我正在尝试创建一个包含名称和点的对象数组,并尝试通过bubblesort对它们进行排序C++ 尝试对c+中的对象数组进行排序时出现std:bad#alloc错误+;?,c++,C++,代码块抛出错误:std:bad\u alloc。我正在尝试创建一个包含名称和点的对象数组,并尝试通过bubblesort对它们进行排序 struct Dict{ string name; int points; }; void bubbleSort(Dict arr[], int n){ int lastIndex = n-1; int swapped = 1; for(int i=0;i<=lastIndex && swapped
struct Dict{
string name;
int points;
};
void bubbleSort(Dict arr[], int n){
int lastIndex = n-1;
int swapped = 1;
for(int i=0;i<=lastIndex && swapped;i++){
swapped = 0;
for(int j=0;j<=lastIndex-i;j++){
int a=arr[j].points;
int b = arr[j+1].points;
if(a >= b){
Dict swapper = arr[j];
arr[j] = arr[j+1];
arr[j+1] = swapper;
swapped = 1;
}
}
}
for(int i=0;i<n;i++){
cout << arr[i].name << " ";
}
}
int main()
{
int n;
cin >> n;
Dict arr[n];
char storeName[20];
int storePoints;
for(int i=0;i<n;i++){
Dict a = Dict();
cin >> storeName;
a.name = storeName;
cin >> storePoints;
a.points = storePoints;
arr[i] = a;
}
for(int i=0; i<n; i++){
cout << "Store name : " << arr[i].name << " Store points" << arr[i].points << endl;
}
bubbleSort(arr,n);
return 0;
struct Dict{
字符串名;
积分;
};
void bubbleSort(Dict arr[],int n){
int lastIndex=n-1;
int-swapped=1;
对于(int i=0;i>storePoints;
a、 点数=存储点数;
arr[i]=a;
}
for(int i=0;i由于试图访问数组边界以外的对象而导致的未定义行为
int lastIndex = n-1; // n is 2, lastIndex is 1
for(int i=0;i<=lastIndex && swapped;i++){ // i is 0 or 1
for(int j=0;j<=lastIndex-i;j++){ // j is 0 or 1 when i is 0
int b = arr[j+1].points; // attempt to access arr[2] when j is 0, UB
if(a >= b){
Dict swapper = arr[j];
arr[j] = arr[j+1]; // attempt to access arr[2] when j is 0, UB
arr[j+1] = swapper; // attempt to access arr[2] when j is 0, UB
swapped = 1;
} } }
int lastIndex=n-1;//n是2,lastIndex是1
对于(int i=0;icin>>storeName;a.name=storeName;cin>>storePoints;a.points=storePoints;
为什么要使用这么多不需要的代码?为什么不直接读取cin>>a.name;cin>>a.points;
?Dict arr[n]不是标准C++。它是大多数编译器不支持的语言扩展。<代码>:ST::向量< /代码>是一种适当的方式。