0

例如,我创建一个 2D 矢量 (1000x3) 为:

vector<vector<float>> Vector (1000, vector<float>(3))

然后一个函数将 3D 点存储到向量中(不一定是 1000 个点,但少于 1000 个)。我应该如何获取我创建的 Vector 中最后一行的索引?

我想出了一个在向量类中定义的称为“end”的方法,但不知道语法。

也有人可能会说我可以跟踪存储在向量中的最后一个点的索引,例如:

Vector[i][j] = value;

但是我在其他函数中需要这些数据,所以一直返回这个索引对我来说似乎不是一个好的选择。

4

2 回答 2

1

Since each row is a 3D point and so will definitely have 3 elements, an std::vector isn't an appropriate type. I would perhaps use a std::array<float, 3> or a struct with members x, y, and z for the inner type.

It seems that you don't actually want 1000 points in your vector. Maybe you're doing it to avoid reallocations later on? In that case, you should use Vector.reserve(1000);. This will reserve memory for the points without actually adding them. Then you can add your points using emplace_back, push_back or any other mechanism.

Then, to get an iterator to the last point in the vector, you can do either std::end(Vector) - 1 or Vector.end() - 1. If you had kept it as you had it, where there were always 1000 points in the vector, this would have given you an iterator to the 1000th point (even if you hadn't assigned any useful values to it yet).

于 2014-01-19T14:55:08.023 回答
1

You shouldn't initialize it with 1000 elements. Just leave it empty and use Vector.push(...) to add new points, the vector will grow automatically.

Then the last index is:

Vector.size() - 1

Or if you insist on doing so, you can put it in a class and add a member to store the size.

struct PointVector {
    vector<array<float, 3>> Vector;
    int size;
    PointVector() : Vector(1000, {0, 0, 0}), size(0) { }
};
于 2014-01-19T14:56:32.237 回答