Return end index of a 2D Vector

1.4k Views Asked by At

For instance I create a 2D Vector (1000x3) as:

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

A function then stores 3D points into the vector (not necessarily 1000 points but less than 1000). How should I get the index of last row in the Vector that I created?

I figured out a method called as "end" defined in vector class but don't know the syntax.

Also some may say that I can trace the index of last point stored in the vector, for example:

Vector[i][j] = value;

But I need this data in other functions, so returning this index all the time doesn't seem as good option to me.

2

There are 2 best solutions below

3
On

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).

1
On

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) { }
};