C ++向量边界检查

时间:2018-01-01 16:19:10

标签: c++ vector bounds

我有一个6D向量,我需要检查每个元素的邻域(每个方向2个元素)。当然,当我在矢量的边界上时,检查分段故障中的引线。我能做的就是切换大量的箱子。有没有更好的方法来解决这个问题?我也想过像try-catch这样的东西。

1 个答案:

答案 0 :(得分:1)

仍然太笨重但是有效:

#include <iostream>
#include <array>
#include <vector>

typedef std::vector<int> Vector1D;
typedef std::vector<Vector1D> Vector2D;
typedef std::vector<Vector2D> Vector3D;
typedef std::vector<Vector3D> Vector4D;
typedef std::vector<Vector4D> Vector5D;
typedef std::vector<Vector5D> Vector6D;
typedef std::array<size_t, 6> Path;

bool GetVectorPathElement(Vector6D const &vector6D, Path const &path, int &val)
{
    size_t i = 0, k = path[i];
    if (vector6D.size() > k)
    {
        Vector5D const &vector5D = vector6D[k];
        k = path[++i];
        if (vector5D.size() > k)
        {
            Vector4D const &vector4D = vector5D[k];
            k = path[++i];
            if (vector4D.size() > k)
            {
                Vector3D const &vector3D = vector4D[k];
                k = path[++i];
                if (vector3D.size() > k)
                {
                    Vector2D const &vector2D = vector3D[k];
                    k = path[++i];
                    if (vector2D.size() > k)
                    {
                        Vector1D const &vector1D = vector2D[k];
                        k = path[++i];
                        if (vector1D.size() > k)
                        {
                            val = vector1D[k];
                            return true;
                        }
                    }
                }
            }
        }
    }
    std::cout << "Invalid path " << k << " at index " << i << std::endl;
    return false;
}

int main()
{
    Vector1D vector1D = { 1,2,3,4,5,6 };
    Vector2D vector2D = { vector1D, vector1D, vector1D, vector1D, vector1D };
    Vector3D vector3D = { vector2D, vector2D, vector2D, vector2D };
    Vector4D vector4D = { vector3D, vector3D, vector3D };
    Vector5D vector5D = { vector4D, vector4D };
    Vector6D vector6D = { vector5D };

    Path path = { 0,0,2,1,4,5 };
    int element;

    if (GetVectorPathElement(vector6D, path, element))
    {
        std::cout << "Path: ";
        for (auto i : path)
            std::cout << i << " ";

        std::cout << "\nElement value at destination: " << element << std::endl;
    }

    return 0;
}

https://ideone.com/nL1zo2