【发布时间】:2016-12-26 19:33:18
【问题描述】:
我是 C++ 新手,我想对 std::cin 提供的动态字符串数组进行排序。
我不知道我的代码有什么问题,但数组没有排序。
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
void sort_array(string *array);
int main() {
cout << "Number of names to enter: " << endl;
int nr_names;
cin >> nr_names;
string *names = new (nothrow) string[nr_names];
if (names == nullptr) {
cout << "Memory alocation failed" << endl;
} else {
for (int i = 0; i < nr_names; i++) {
cout << "Enter a name: " << endl;
cin >> names[i];
}
cout << "Entered names are: " << endl;
for (int i = 0; i < nr_names; i++) {
cout << names[i] << endl;
}
sort_array(names);
cout << "Sorted names: " << endl;
for (int i = 0; i < nr_names; i++) {
cout << names[i] << endl;
}
delete[] names;
}
return 0;
}
void sort_array(string *array) {
const int arSize = (sizeof(*array) / sizeof(array[0]) - 1);
for (int startIndex = 0; startIndex < arSize; startIndex++) {
int smallestIndex = startIndex;
for (int currentIndex = startIndex+1; currentIndex < arSize; currentIndex++) {
if (array[currentIndex] < array[smallestIndex]) {
smallestIndex = currentIndex;
}
}
swap(array[startIndex], array[smallestIndex]);
}
}
排序方法适用于固定数组。所以我认为动态内存分配可能存在一些问题(我刚开始研究)
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
string array[5] ={"Mike", "Andrew", "Bob", "Nick", "Matthew"};
const int arSize = 5;
for (int startIndex = 0; startIndex < arSize; startIndex++) {
int smallestIndex = startIndex;
for (int currentIndex = startIndex+1; currentIndex < arSize; currentIndex++) {
if (array[currentIndex] < array[smallestIndex]) {
smallestIndex = currentIndex;
}
}
swap(array[startIndex], array[smallestIndex]);
}
//print the sorted array - works
for(int i = 0; i< arSize; i++){
cout<<array[i]<<endl;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:【如何调试小程序】(ericlippert.com/2014/03/05/how-to-de
-
const int arSize = (sizeof(*array) / sizeof(array[0]) - 1);这不是数组大小! -
我建议使用
std::vector(动态数组库类)而不是原始动态数组,除非您特别想了解动态内存管理。 -
谢谢保罗和贾斯汀。我将阅读有关调试和 std::vector 的更多信息。
标签: c++