在C、C++或Objective-C中等效的System.arraypy()



我正在将一个android应用程序(java)移植到ios应用程序。它的一部分是实时显示图。

我使用此代码插入值以索引0脱离数组:

public double[] points;
.....
//Clear array value at first index
System.arraycopy(points, 0, points, 1, points.length - 1);
//Add new value to first index
points[0] = sample;

对此有一些疑问,但对我的情况没有帮助。

我可以使用NSMutableArray和NSNumber来获得结果,但它需要更多的代码,然后使用CPU

在C中,一开始会做:

size_t n_points = 512;
double *points = calloc(512, sizeof(double));

那么逻辑是:

memmove(points + 1, points, n_points - 1);
*points = sample;

虽然更好的方法是使用环形缓冲区,所以与其在缓冲区周围移动值,不如移动被认为是开始的索引:

size_t n_points = 512;
double *points = calloc(512, sizeof(double));
ssize_t beginning = 0;

if (--beginning < 0) {
    beginning += n_points;
}
points[beginning] = sample;

然后在绘图代码中:

ssize_t idx, i;
for (idx = beginning, i = 0;
     i < n_points;
     i ++, idx = (idx + 1) % n_points)
{
    // i runs from 0 ... n_points - 1
    set_pixel(i, points[idx], black);
}

C++中,我很想用std::vector来代替Java数组:

#include <vector>
#include <iostream>
int main()
{
    struct point
    {
        int x, y;
        point(int x, int y): x(x), y(y) {}
    };
    std::vector<point> points;
    point sample {2, 7};
    points.insert(points.begin(), sample); // insert at beginning
    points.insert(points.begin(), {9, 3});
    points.insert(points.begin(), {4, 8});
    points.push_back(sample); // insert at end
    for(auto p: points)
        std::cout << "{" << p.x << ", " << p.y << "}" << 'n';
}

如果您进行批量,如果在开始时插入std::deque,则可能值得一看。

参考:std::矢量如何工作

在Obective-C中,您可以使用NSMutableArray方法在索引0处插入项目。

 - (void)insertObject:(id)anObject atIndex:(NSUInteger)index

从谷歌快速搜索中,它看起来像是System.arrayCopy()将源数组的子集复制到目标数组中。

听起来您希望您的新阵列是NSMutableArray,并希望使用- insertObjects:atIndexes:。该方法将NSIndexSet作为输入。可以使用NSIndexSet方法indexSetWithIndexesInRange从一系列索引中创建索引集。

最新更新