代码之家  ›  专栏  ›  技术社区  ›  willc2

我可以在不创建临时数组的情况下移动NSMutableArray中的对象吗?

  •  7
  • willc2  · 技术社区  · 16 年前

    我以为我和他在一起了,

    void shiftArray(NSMutableArray *mutableArray, NSUInteger shift)
    {
        for (NSUInteger i = 0; i < [mutableArray count]; i++) {
            NSUInteger newIndex = (i + shift) % [mutableArray count];
            [mutableArray exchangeObjectAtIndex:i withObjectAtIndex:newIndex];
        }
    }
    

    当我移动1时,它把0,1,2,3,4变成了0,2,3,4,1。

    我觉得我错过了一些明显的东西。。。

    更新:

    void shiftArrayRight(NSMutableArray *mutableArray, NSUInteger shift) {
        for (NSUInteger i = shift; i > 0; i--) {
            NSObject *obj = [mutableArray lastObject];
            [mutableArray insertObject:obj atIndex:0];
            [mutableArray removeLastObject];
        }
    }
    

    我不知道你可以创建一个通用的NSObject并在其中放入一些子类。都是指针,所以我想没关系,对吧?

    很难打破将这些物体视为物体的习惯 袋子 指的是物质而不是物质 指针

    2 回复  |  直到 16 年前
        1
  •  13
  •   Matthieu Cormier Adam Musch    16 年前

    试试像这样的东西

    for (NSUInteger i = shift; i > 0; i--) {
       NSObject* obj = [mutableArray lastObject];
       [mutableArray insertObject:obj atIndex:0];
       [mutableArray removeLastObject];
    }
    

    警告——我还没有测试过该代码,但这应该可以帮助您解决问题。

        2
  •  3
  •   masto    16 年前

    你需要再看看你的算法。每次通过循环时,您将一个项目与下一个项目交换(在shift=1的情况下)。

    0,1,2,3,4
    1. , ,2,3,4
    1. , 0 ,3,4
    1,2, , 0 4.
    1,2,3, 4. , 0
    0 ,2,3,4, 1.

    0,1,2,3,4
    0
    4,1,2, 0 ,
    4,1, 0 , 3.
    4. , 1. ,2,3