V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
spencerqiu
V2EX  ›  C

两个数组,其中每个变量(如 a[1]和 b[1] 、 a[i] 和 b[i] 等等)是同一个东西的两种性质,对其中一个数组排序之后,如何继续保持这种联系?

  •  
  •   spencerqiu · 2015-07-27 19:36:24 +08:00 · 743 次点击
    这是一个创建于 3205 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在能想到的办法就是在排序交换 a 数组的时候,同时把 b 数组也交换了...但是因为 STL 的 sort ...都多少年没有写过排序了...写个快排也真不轻松= =

    所以还有别的办法么?依稀记得 struct 可能可以解决...有没有大神能给个示范?(先对a排序,然后让 a
    和 b 一一对应)
    7 条回复    2015-07-28 15:00:21 +08:00
    bazingaterry
        1
    bazingaterry  
       2015-07-27 19:41:17 +08:00
    依稀记得 sort() 可以有第二个参数的,你写一个比较函数就可以了。
    zoudm
        2
    zoudm  
       2015-07-27 19:47:22 +08:00   ❤️ 1
    放在一个struct S里面,比如是一个int i和char c。然后你有一个S s[100];
    然后两种办法:
    1重载这个这个struct的小于号,bool operator < (const S & c) const { return i < c.i; }。然后使用sort来对其排序
    2定义一个函数bool comp(S &a, S &b) { return a.i < b.i; } 然后在sort的时候使用sort(s, s+100, comp),作为第三个参数传comp这个函数进去。
    bazingaterry
        3
    bazingaterry  
       2015-07-27 19:58:23 +08:00
    @bazingaterry 不好意思,是第三个参数。
    二楼正解!
    publicID001
        4
    publicID001  
       2015-07-27 20:50:17 +08:00
    pair自带比较,可直接sort
    towser
        5
    towser  
       2015-07-28 13:24:00 +08:00
    与你头像相映成趣
    morefreeze
        6
    morefreeze  
       2015-07-28 14:03:44 +08:00
    struct node{ int a,b; };
    node arr[100];
    bool cmp(const node& lhs, const node& rhs){
    return lhs.a < rhs.a;
    }
    sort(arr, arr+sizeof(arr)/sizeof(arr[0]), cmp);
    canautumn
        7
    canautumn  
       2015-07-28 15:00:21 +08:00
    4楼正解,不需要函数指针和结构体,做成pair就行了

    还有一种更通用的办法(超过2组数据,不需要额外的数据结构)就是取得数组a排序的index,然后任意数组按b[indexes[i]]来访问就行了:

    double a[10]= {...};
    double b[10]= {...};
    int indexes[10];

    std::iota(std::begin(indexes), std::end(indexes), 0);
    std::sort(std::begin(indexes), std::end(indexes), [&a] (int i, int j) { return a[i] < a[j]; });
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1184 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:51 · PVG 07:51 · LAX 16:51 · JFK 19:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.