gpt4 book ai didi

c++ - 在二维数组中按字母顺序对字符串数组进行排序 (C++)

转载 作者:行者123 更新时间:2023-11-28 05:00:49 25 4
gpt4 key购买 nike

到目前为止,我已经编写了代码,但我不确定如何使用二维数组进行排序。基本上,一个函数用于对字符串数组进行排序,另一个函数用于交换两个字符串。任何帮助,将不胜感激。 (我也不允许使用 c++ 11 :/)

#include <iostream>
#include <string>
#include <algorithm>


using namespace std;

void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
int main() {

string b_list[100][2];
string name;
int choice;
int count=0;

cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list[count][1] = name;
count++;
repeat_pro(choice);
cout<<"\n \n Your Businesses are:"<<endl;
for(int j=0; j<count; j++){
cout<<b_list[j][1]<<endl;
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;


return 0;
}


void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}

void sort_names(string &name){

}

void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
if (answ == "YES" || answ == "Y" || answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}

最佳答案

从描述中我不清楚该程序真正试图解决什么问题。我假设它有点像一个双列电子表格,第二列是用户输入的名称(但是第一列中是什么?)。

假设您需要在数据进入时保持数组的排序顺序,只需进行二进制搜索(您可以对 100 个条目这样的小数据集进行线性搜索)。

// we don't have lambda before C++11
struct comparator {
bool operator () (const string (&x)[2], const string (&y)[2]) const {
return x[1] < y[1];
}
};

//... omitted

string data[100][2];
int count = 0;
while (count < 100) {
// no rvalue, move, rvo, etc. before C++11
string name;
input_name(name);
// no type deduction and lambda
string (*position)[2] =
std::lower_bound(&data[0], &data[count], name, comparator());
int index = position - &data[0];
// simulate an vector::insert operation, but for our array
for (int i = count; i > index; --i) {
// before we had move in C++, we would do swap with an empty element.
// in this case, the entry at data[count] is default constructed
std::swap(data[i][1], data[i-1][1]);
}
data[index][1] = name;
}
//... omitted

当然我们可以使用 typedef 使其更清晰,但这留给你了。

关于c++ - 在二维数组中按字母顺序对字符串数组进行排序 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com