[英]How can ı sort string and its corresponding integer in c++?
你好,我有一個字符串向量(favseries),其中包括演員名。 並且我創建了三個向量來存儲計數(向量計數),存儲演員(向量演員),存儲演員(向量唯一演員)從高到低計數,如果計數相同,則從“A”到“Z”排序字符串。
我的字符串向量包括:
WENTWORTH MILLER FREYA ALLAN YASEN ATOUR BASIL EIDENBENZ ANYA CHALOTRA
BRYAN CRANSTON RAINN WILSON WENTWORTH MILLER LESLIE DAVID BAKER BRYAN CRANSTON ANYA CHALOTRA YASEN ATOUR
這是 output 必須是:
ANYA CHALOTRA: 2
BRYAN CRANSTON: 2
WENTWORTH MILLER: 2
YASEN ATOUR: 2
BASIL EIDENBENZ: 1
FREYA ALLAN: 1
LESLIE DAVID BAKER: 1
RAINN WILSON: 1
我的 output 是排序部分中稱為向量超出范圍的錯誤。 還有我的 output 沒有給出任何錯誤時,它會根據第 0 個索引打印沒有排序的字符串,並且一個演員被打印兩次,計數為 1。例如:
ANYA CHALOTRA: 1
BRYAN CRANSTON: 1
WENTWORTH MILLER: 1
YASEN ATOUR: 1
BASIL EIDENBENZ: 1
YASEN ATOUR: 1
ANYA CHALOTRA: 1
BRYAN CRANSTON: 1
WENTWORTH MILLER: 1
FREYA ALLAN: 1
LESLIE DAVID BAKER: 1
RAINN WILSON: 1
這是代碼:
vector <string> actors;
vector <int> counts;
vector <string> uniqueactors;
int count;
for ( int i = 0; i < favSeries.size(); i++) {
for ( int j = 0; j < favSeries[i].actorNames.size(); j++) {
count = 1;
counts.push_back(count);
actors.push_back(favSeries[i].actorNames[j]);
}
}
uniqueactors.push_back(actors[0]);
for ( int i = 0; i < actors.size(); i++ ) {
bool check = true;
for ( int j = 0; j < uniqueactors.size(); j++ ) {
if ( uniqueactors[j] == actors[i] ) {
counts[j] += 1;
check = false;
}
}
if (check) {
uniqueactors.push_back(actors[i]);
}
}
for ( int i = 0; i < uniqueactors.size() - 1; i++) {
int minindex = i;
for (int j = i + 1; j < uniqueactors.size(); j++) {
if (actors[minindex].at(0) > uniqueactors[j].at(0)) {
minindex = j;
}
}
string temp = uniqueactors[i];
uniqueactors[i] = uniqueactors[minindex];
uniqueactors[minindex] = temp;
int temp1 = counts[i];
counts[i] = counts[minindex];
counts[minindex] = temp1;
}
for ( int i = 0; i < counts.size() - 1; i++) {
int minindex = i;
for (int j = i + 1; j < counts.size(); j++) {
if( counts[minindex] > counts[j] ) {
minindex = j;
}
}
int temp1 = counts[i];
counts[i] = counts[minindex];
counts[minindex] = temp1;
string temp = uniqueactors[i];
uniqueactors[i] = uniqueactors[minindex];
uniqueactors[minindex] = temp;
}
for ( int i = 0; i < uniqueactors.size(); i++ ) {
cout << uniqueactors[i] << ":" << count << endl;
}
}
或者你能重新排列矢量和排序嗎? 謝謝你...
您可以使用 stl 中algorithm
的sort()
。
vector<int> v;
sort(v.begin(), v.end(), [](int a, int b){
return a < b;
})
與此類似,您可以輕松地為不同的 arrays 實現此功能。 閱讀有關sort()的更多信息。
我還建議您使用 struct 或 a pair
。
將字符串和計數存儲成對后,代碼如下:
vector<pair<string, int>> v;
sort(v.begin(), v.end(), [](auto a, auto b){
if(a.second > b.second){
return a.second > b.second;
} else {
return a.first > b.first;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.