对字符数组中的单词进行排序
Sorting words in a character array
对于给定的数组,我需要编写一个函数来按字母顺序对单词进行排序:
char strings [][10] = {
"hello",
"world",
"computers",
"are",
"awesome"
};
我尝试使用插入排序来sortWords
编写函数,但我认为我的交换函数不起作用:
void swap(char *e1, char *e2) {
int tmp = *e1;
*e1 = *e2;
*e2 = tmp;
}
void sortWords( char (* words2Darray)[10], unsigned short length ) {
unsigned int i, curPos;
char curChars[10];
for(i = 1; i < length; i++) {
// Copy the current word into curChars
strncpy_s(curChars, words2Darray[i], 10);
curPos = i;
// Compare and move the word to the correct position
while(curPos > 0 && strcmp(curChars, words2Darray[i-1]) > 0) {
swap(words2Darray[curPos], words2Darray[curPos-1]);
curPos--;
}
}
}
我尝试使用本地 Windows 调试器调试我的代码,发现curChars
正在正确复制。
有人可以向我解释我做错了什么以及我应该如何解决这个问题吗?我不允许在这个问题中使用std::string
。请不要提供完整的解决方案!
你可以
只使用std::sort
:
std::sort(std::begin(strings), std::end(strings), cmp);
这需要一个比较器。我根据strcmp
鞭打了一个.
在 IdeOne 上观看直播
#include <algorithm>
#include <iostream>
#include <cstring>
int main()
{
char const* strings[] = {
"hello",
"world",
"computers",
"are",
"awesome"
};
struct {
bool operator()(char const* a, char const* b) const {
return (a && b)? 0 > strcmp(a,b) : a < b;
}
} cmp;
std::sort(std::begin(strings), std::end(strings), cmp);
for (auto& s : strings)
std::cout << s << "n";
}
请注意,我冒昧地将数组元素char*
而不是char[]
。这是出于Carl Norum指出的原因。
你不是交换字符串,而是交换字符串的第一个字符。 如果要按值传递,则需要如下内容:
void swap(char **e1, char **e2) {
char *tmp = *e1;
*e1 = *e2;
*e2 = tmp;
}
然后使用它:
swap(&words2Darray[curPos], &words2Darray[curPos-1]);
或者,您可以将swap
调用保留原样并使用引用:
void swap(char *&e1, char *&e2) {
char *tmp = e1;
e1 = e2;
e2 = tmp;
}
(我认为没错——我的C++生锈了。 我会做一个测试来确定。
相关文章:
- 文本文件中的单词链表
- 二叉排序树无法编译
- 如何在openssl-ecc中获取十六进制格式的私钥
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++:对单词而不是数字进行快速排序
- 读取每个单词的文件,并使用二叉搜索树(词典)对这些单词进行排序
- 根据输入文本对单词进行排序,具体取决于重复多少次
- 如何根据第三个单词在文本文件中排序行
- C 简单字典:排序单词列表
- 按长度(单词)c++ 对字符串数组进行排序
- 对字符数组中的单词进行排序
- 对列表中最有可能由列表顶部的人说出的积极单词和列表末尾很少说出的单词进行排序
- 按字符串的矢量对大小写单词进行排序
- 排序这些单词的排序标准
- 为什么这个单词排序程序只循环一次?
- 我找到所有的单词,有五个字母在一个向量的字符串与equal_range,它一直抛出一个错误,说它没有排序
- 在Rcpp中用(西班牙语)重音单词排序映射
- 按字符串长度对单词排序
- 在c++中如何将单词排序到结构数组中
- c++查找首尾字母相同的单词,并按字母顺序对它们进行排序