私はC++が新しく、std :: cinで提供される動的な文字列をソートしたいと思います。C++文字列の動的配列を並べ替える - ソートが機能しません
私のコードで何が間違っているのか分かりませんが、配列はソートされません。
#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]);
}
}
ソート方法は、固定配列で機能します。だから私は(私は勉強を始めた)動的なメモリ割り当てに関するいくつかの問題const int arSize = (sizeof(*array)/sizeof(array[0]) - 1);
は、配列のサイズではないため、配列はソートされませんvoid sort_array(string *array)
で
#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;
}
}
ようこそスタックオーバーフロー!デバッガを使用してコードをステップ実行する方法を学ぶ必要があるようです。良いデバッガを使用すると、プログラムを1行ずつ実行し、どこからずれているかを確認することができます。これはプログラミングをする場合に不可欠なツールです。さらに読む:[小さなプログラムをデバッグする方法](https://ericlippert.com/2014/03/05/how-to-de –
'const int arSize =(sizeof(* array)/ sizeof(array [0])これは配列サイズではありません! –
ダイナミックメモリ管理について詳しく知りたい場合を除いて、私は、生の動的配列の代わりに 'std :: vector'(動的配列ライブラリクラス)を使用することをお勧めします。 –