私はペアの最初の値でペアのベクトルをソートしようとしています。私は既に投稿されているこれに関する他の質問への回答の助言に従おうとしましたが、何らかの理由でベクトルを並べ替えるのに問題があります。私はstd :: sortとstd :: stable_sortを無駄に使用しようとしました。コードは正常にコンパイルされ、不満なく実行されますが、配列はソートされません。私のサンプルコードは以下の通りです:ペアのベクトルを最初の要素で並べ替えるにはどうすればいいですか?
#include <iostream>
#include <vector>
#include <algorithm>
bool compare(const std::pair<int, int>&i, const std::pair<int, int>&j){
return i.first < j.first;
}
int main(){
std::vector<std::pair<int, char>> vec;
vec.reserve(10); // reserve space for 10 elements
int i;
std::string letters = "abcdefghij";
int randNum;
for(i=0; i<10; i++){
randNum = std::rand()%(10-0 + 1); // generate random numbers between 0 and 10
vec[i].first = randNum; // assign random integer to first element of pair
vec[i].second = letters[i]; // assign letter to second element of pair
}
for(i=0; i<10; i++){ // print out unsorted array
std::cout << vec[i].first << " " << vec[i].second << "\n";
}
std::cout << "\n";
std::sort(vec.begin(), vec.end(), compare);
for(i=0; i<10; i++){ // print out sorted array
std::cout << vec[i].first << " " << vec[i].second << "\n";
}
return 1;
}
結果の出力はそうのようになります。
10 a
1 b
0 c
6 d
8 e
3 f
2 g
0 h
9 i
4 j
10 a
1 b
0 c
6 d
8 e
3 f
2 g
0 h
9 i
4 j
コードは未定義の動作を示します。ベクトルのサイズは、ソート前、ソート中、ソート後に0です。バッファの最後を過ぎて要素にアクセスしています。 'vec.reserve(10);を' vec.resize(10);に置き換えてください –
ありがとう、それは私の問題を解決しました! – SomeRandomPhysicist