c++ - 二维字符串数组冒泡排序
问题描述
我想弄清楚如何对二维字符串数组进行冒泡排序。我目前正试图弄清楚为什么我的程序没有对字符串进行排序。我怀疑 void swap 可能有问题。我觉得需要将二维数组放入其中。我不太确定我刚刚学会了如何创建冒泡排序算法。
#包括
using namespace std;
const int SIZE = 2;
const int ROWS = 2;
void bubbleSort(string values[][SIZE]);
void swap(int &, int &);
int main ()
{
string values[ROWS][SIZE] = {{"A23", "A12"}, {"name1", "name2"}};
cout << "Unsorted Values: " << endl;
for(auto element : values)
cout << element << " ";
cout << endl;
cout << "Sorted Values" << endl;
bubbleSort(values);
for (auto element:values)
cout << element << " ";
return 0;
}
void bubbleSort(string values[][SIZE])
{
int maxElement;
int index;
for (maxElement = SIZE - 1; maxElement > 0; maxElement--)
{
for( index = 0; index < maxElement; index++)
{
if (values[0][index] > values[0][index + 1])
{
swap(values[0][index], values[0][index + 1]);
}
}
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
解决方案
您的程序会打印出地址,因为您的打印循环会迭代字符串二维数组的每个条目。因此,每个条目都是一个数组。所以arr
保存指向数组第一个元素的指针。您只需要一个嵌套循环来打印出单个元素的值:
for (auto row : values)
for (int i = 0; i < SIZE; i++)
std::cout << row[i] << " ";
此外,不需要实现自己的交换功能。只需使用std::swap(T&,T&)
但我假设您想要实现多数组排序。然后你应该使用一个简单的结构来表示一个实体而不是多个数组,并实现一个运算符来比较两个实体。我建议也使用基于范围的容器。然后,您可以利用标准的排序功能。
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Entry
{
string id;
string name;
bool operator<(const Entry& comp)
{
return id < comp.id;
}
};
int main()
{
auto print = [](const vector<Entry>& vec)
{
for (auto& el : vec)
{
cout << el.id << "->" << el.name << "\t";
}
};
vector<Entry> values { {"A23","name1" }, {"A12", "name2"} };
cout << "Unsorted Values: " << endl;
print(values);
cout << endl;
std::sort(values.begin(), values.end());
cout << "Sorted Values" << endl;
print(values);
return 0;
}
打印出来:
Unsorted Values:
A23->name1 A12->name2
Sorted Values:
A12->name2 A23->name1
推荐阅读
- c++ - CRTP如何使派生类具有基类的容器
- javascript - 从 ajax(香草版)发送的数据不会存储在 PHP 中的 $_POST 中
- java - 有没有更干净的方法来写这个?
- php - 如何检查字符串中是否只有制表符(\ t char)
- date - 使用 Dask map_partitions 将日期和时间从两列转换为单个日期时间列
- ios - 删除数据后应用程序大小不断增加
- r - 在 R、data.frame() 或 write.csv2() 函数中,更改编码
- couchdb - rdbms 表到 couchdb 数据库表
- python - For 循环 - 在列表中创建最多三个项目的列表
- c - 谁能解释为什么我们需要 if (prime[2]!=1) 将值分配给数组,而数组的所有值最初都设置为零?