[英]Sort arrays by elements
我有三個String
數組
A: [-22, -3, 2.2, a]
B: [-22, -3, 2.2, b]
C: [-22, 0, 2.2]
排序后我想得到這個序列
C: [-22, 0, 2.2]
A: [-22, -3, 2.2, a]
B: [-22, -3, 2.2, b]
一對數組之間的比較是在數組中的第一個元素上完成的。 如果元素相同,則為第二個元素,依此類推。
必須使用什么比較器?
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct values{
vector<string> ve;
}array[100];
bool comp(values a, values b){
if(a.ve.size()<b.ve.size() || a.ve<b.ve)
return true;
return false;
}
int main(){
int number, size;
string str;
cin>>number; //Number of string arrays
for(int i=0;i<number;i++){
cin>>size; // Number of element in each array
for(int j= 0;j<size;j++){
cin>>str;
array[i].ve.push_back(str);
}
}
sort(array, array+number, comp);
for(int i=0;i<number;i++){
for(int j= 0;j<array[i].ve.size();j++){
cout<<array[i].ve[j]<<" ";
}
cout<<"\n";
}
return 0;
}
輸入:
3
4
-22 -3 2.2 a
4
-22 -3 2.2 b
3
-22 0 2.2
輸出:
-22 0 2.2
-22 -3 2.2 a
-22 -3 2.2 b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.