我试图比较2个字符串数组,我似乎无法弄清楚问题。目标是按字母顺序排列。我试图使用冒泡排序,但我无法让它工作。不确定它是否重要但是正在从文件读入数组并且正在比较姓氏,我希望此函数将它们重新排列为字母顺序。谢谢
sortInput(accountData);
void sortInput(string theAccounts[5][7])
{
bool swap;
string temp;
do
{
swap = false;
int row = 7;
for (int count = 0; count < (row - 1); count++)
{
if (strcmp(theAccounts[count][2], theAccounts[count + 1][2]) < 0)
{
temp = theAccounts[count][2];
theAccounts[count][2] = theAccounts[count + 1][2];
theAccounts[count + 1][2] = temp;
swap = true;
}
}
} while (swap);
}
以下是从中读取的.txt文件:
bham@gnet.com Blake Ham squid62 1987 U Teacher
jdark@att.net Jim Dark gymrat32 1985 A Master
hgreen@lakes.net Hannah Green flower22 2007 U Apprentice
tsmith@dna.com Tom Smith tuna20 2000 U Teacher
jarrow@pnet.com James Arrow ahoy10 2005 U Apprentice
答案 0 :(得分:0)
如果您想使用冒泡排序,则应将int row = 5;
设为7
。如果要交换整行,则需要交换行中的所有元素,而不仅仅是按第二个索引排序的键:
const int COLUMNS_COUNT = 7;
//...
if (strcmp(theAccounts[count][2], theAccounts[count + 1][2]) < 0)
{
//Swap whole row
for ( int j = 0; j < COLUMNS_COUNT - 1; j++ )
{
temp = theAccounts[count][j];
theAccounts[count][j] = theAccounts[count + 1][j+1];
theAccounts[count + 1][j+1] = temp;
}
swap = true;
}
或者只是你可以选择另一种方式并用STL解决这个任务:
尝试使用其他容器,请考虑std::map
它是专门为了在插入元素时保持元素排序并保留其他字段的值,我们在这里得到key =&gt;值容器。您的算法很奇怪strcmp(theAccounts[count][2], theAccounts[count + 1][2]
它每行只比较2
个索引。所以我想你想要按给定输入文本中的一列来排序顺序,选择列数据并作为第一个参数传入std::pair
,就像这里map1.insert(std::make_pair("Ham", "bham@gnet.com Blake Ham squid62 1987 U Teacher"));
一样。然后,您将从输入数据中按第三个字段排序。
我的例子:
#include <iostream>
#include <string>
#include <map>
#include <string>
#include <algorithm>
int main()
{
//Input maps test data
std::map<std::string,std::string> map1;
map1.insert(std::make_pair("Ham", "bham@gnet.com Blake Ham squid62 1987 U Teacher"));
map1.insert(std::make_pair("Dark", "jdark@att.net Jim Dark gymrat32 1985 A Master"));
map1.insert(std::make_pair("Green", "hgreen@lakes.net Hannah Green flower22 2007 U Apprentice"));
map1.insert(std::make_pair("Smith", "tsmith@dna.com Tom Smith tuna20 2000 U Teacher"));
map1.insert(std::make_pair("Arrow", "jarrow@pnet.com James Arrow ahoy10 2005 U Apprentice"));
//Trace set's order as they are saved in container
std::cout << "Map1:" << std::endl;
std::for_each(map1.begin(), map1.end(), []( const std::pair<std::string, std::string>& el )
{
std::cout << el.first << ": " << el.second << std::endl;
} );
return 0;
}
结果是:
Map1:
Arrow: jarrow@pnet.com James Arrow ahoy10 2005 U Apprentice
Dark: jdark@att.net Jim Dark gymrat32 1985 A Master
Green: hgreen@lakes.net Hannah Green flower22 2007 U Apprentice
Ham: bham@gnet.com Blake Ham squid62 1987 U Teacher
Smith: tsmith@dna.com Tom Smith tuna20 2000 U Teacher
Program ended with exit code: 0
因此您不必担心排序数据,只需使用std::map
容器即可。如果要使用特定的比较算法,请使用第三个参数传递比较函数:
auto MapWithSpecificCmp = std::map<std::string, std::string, std::function<bool(const std::string&, const std::string&)>>{
[](const std::string& a, const std::string& b)
{
//Specific compare
return a < b;
}
};