我是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;
}
}
在 void sort_array(string *array)
中,数组未得到排序,因为 const int arSize = (sizeof(*array) / sizeof(array[0]) - 1);
不是数组大小。是... 0。
应该是const int arSize = sizeof(array) / sizeof(array[0])
,但仅当array
是数组而不是元素的指针时才有效。
因此您的循环永远不会执行(因此您必须将大小传递)
正如贾斯汀(Justin)评论的那样,由于您使用的是C 和高级swap
东西,因此std::vector
是通过其大小的数组的方法。