【问题标题】:Sort arrays by elements按元素对数组进行排序
【发布时间】:2017-02-02 15:18:01
【问题描述】:

我有三个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]

一对数组之间的比较是在数组中的第一个元素上完成的。如果元素相同,则为第二个元素,依此类推。

必须使用什么比较器?

【问题讨论】:

  • 这些数组的类型是什么? ab 是什么?
  • 您要考虑ab 的ascii 值吗?
  • ab 是什么?
  • 到khelwood字符串数组;到 WasiAhmad,我从 B (-22) 获得第一个值后,我从 A (-22) 获得第一个值,如果它们相等 -> 比较来自 A (-3) 的第二个值与来自 B(-3) 的第二个值等.
  • @Mohsen_Fatemi 都是字符串值

标签: java sorting arraylist comparator


【解决方案1】:
#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

【讨论】:

  • 为什么你用c++代码回答了一个java问题?
  • 糟糕,我没有注意到 java 标签。
猜你喜欢
  • 2016-02-01
  • 1970-01-01
  • 2014-10-19
  • 2020-10-19
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2013-12-03
相关资源
最近更新 更多