从结构 C++ 中初始化二维向量
Initialise 2D vector out of a structure c++
当我按以下方式从结构中创建二维矢量时:
struct ScreenCoordinates{ //stores coordinates on screen
GLdouble x;
GLdouble y;
GLdouble z;
};
vector<vector<ScreenCoordinates>> screenPoints_of_slices;
此时出现错误:
screenPoints_of_slices[0][0].x = -1.0000;
无法到达这里:
screenPoints_of_slices[0][0].y = -1.0000;
screenPoints_of_slices[0][0].z = -1.0000;
谁能解释一下这是为什么?
显然是因为您没有在向量中放入任何东西。向量仍然是空的,因此您不能引用其中的任何元素。
问题是 vector<vector<ScreenCoordinates>> screenPoints_of_slices
有零个元素
你应该做
vector<vector<ScreenCoordinates> > screenPoints_of_slices(1, vector<ScreenCoordinates>(1));
基本上上面的步骤将 space 分配给 screenCoordinates 向量的一个元素与一个元素。
如果您在 ScreenCoordinates
定义期间不知道元素的数量,您应该 push_back
元素。下面显示了相同的片段
vector<ScreenCoordinates> temp_vec; //inner dim
ScreenCoordinates temp_cord = {0,0,0} // construct object
temp_vec.push_back(temp_cord);
temp_vec.push_back(temp_cord); // I am pushing same elem, but you can push any
temp_vec.push_back(temp_cord);
//Now push this back to the 2d vec
screenPoints_of_slices.push_back(temp_vec);
一旦您熟悉了上面的代码,请查看 std::move
(http://en.cppreference.com/w/cpp/utility/move)
试试这个:
const size_t screenWidth = 1280;
const size_t screenHeight = 720;
vector<vector<ScreenCoordinates>> screenPoints_of_slices(screenHeight,
vector<ScreenCoordinates>(screenWidth,
ScreenCoordinates{0, 0, 0}));
这将为您创建一个 screenHeight x screenWidth
矩阵并使用 {0, 0, 0}
初始化其元素(但如果您愿意,可以省略该部分)。
当我按以下方式从结构中创建二维矢量时:
struct ScreenCoordinates{ //stores coordinates on screen
GLdouble x;
GLdouble y;
GLdouble z;
};
vector<vector<ScreenCoordinates>> screenPoints_of_slices;
此时出现错误:
screenPoints_of_slices[0][0].x = -1.0000;
无法到达这里:
screenPoints_of_slices[0][0].y = -1.0000;
screenPoints_of_slices[0][0].z = -1.0000;
谁能解释一下这是为什么?
显然是因为您没有在向量中放入任何东西。向量仍然是空的,因此您不能引用其中的任何元素。
问题是 vector<vector<ScreenCoordinates>> screenPoints_of_slices
有零个元素
你应该做
vector<vector<ScreenCoordinates> > screenPoints_of_slices(1, vector<ScreenCoordinates>(1));
基本上上面的步骤将 space 分配给 screenCoordinates 向量的一个元素与一个元素。
如果您在 ScreenCoordinates
定义期间不知道元素的数量,您应该 push_back
元素。下面显示了相同的片段
vector<ScreenCoordinates> temp_vec; //inner dim
ScreenCoordinates temp_cord = {0,0,0} // construct object
temp_vec.push_back(temp_cord);
temp_vec.push_back(temp_cord); // I am pushing same elem, but you can push any
temp_vec.push_back(temp_cord);
//Now push this back to the 2d vec
screenPoints_of_slices.push_back(temp_vec);
一旦您熟悉了上面的代码,请查看 std::move
(http://en.cppreference.com/w/cpp/utility/move)
试试这个:
const size_t screenWidth = 1280;
const size_t screenHeight = 720;
vector<vector<ScreenCoordinates>> screenPoints_of_slices(screenHeight,
vector<ScreenCoordinates>(screenWidth,
ScreenCoordinates{0, 0, 0}));
这将为您创建一个 screenHeight x screenWidth
矩阵并使用 {0, 0, 0}
初始化其元素(但如果您愿意,可以省略该部分)。