I have encountered problem in copying the element of nested std::vector to another std::vector.
我在将嵌套的std :: vector元素复制到另一个std :: vector时遇到了问题。
Example 1
例1
std::vector<std::vector<int>> foo;
std::vector<int> temp;
std::vector<int> goo;
temp.push_back(12345);
foo.push_back(temp);
goo = foo[0]; //error
Example 2
例2
temp.clear();
for(int i = 0; i<foo[0].size(); i++) {temp.push_back(foo[0][i])};
goo = temp; //error
Thus, can i know where is the problem and what should i do to copy the element of a nested vector to another vector??
因此,我可以知道问题在哪里,我应该怎么做才能将嵌套矢量的元素复制到另一个矢量?
EDIT: The actual scenario would be i have nested vector of cv::Point
编辑:实际情况是我有嵌套的cv :: Point矢量
std::vector<std::vector<cv::Point>> found_contour;
and would like to copy the element inside a std::vector<cv::Point>
in a struct.
并希望在结构中复制std :: vector
struct Contours
{
std::vector<cv::Point> contour;
cv::RotatedRect minRect;
cv::RotatedRect minEllipse;
}
Code Snippet:
代码片段:
cv::findContours(result,found_contour,found_hierachy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,cv::Point(0,0));
std::vector<Contours> contour_struct;
contour_struct.reserve(found_contour.size());
for (size_t i = 0; i < found_contour.size(); i++)
{
contour_struct[i].contour = found_contour[i];
contour_struct[i].minRect = cv::minAreaRect(cv::Mat(found_contour[i]));
}
1 个解决方案
#1
2
cv::findContours(result,found_contour,found_hierachy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,cv::Point(0,0));
std::vector<Contours> contour_struct;
contour_struct.reserve(found_contour.size()); //<-----problem
for (size_t i = 0; i < found_contour.size(); i++)
{
contour_struct[i].contour = found_contour[i];
contour_struct[i].minRect = cv::minAreaRect(cv::Mat(found_contour[i]));
}
vector::reserve
only aquires space internally so that push_back
does not run out of space. It does not actually add more objects into the vector
. You can use this line instead:
vector :: reserve仅在内部获取空间,以便push_back不会耗尽空间。它实际上并没有在向量中添加更多对象。您可以使用此行代替:
contour_struct.resize(found_contour.size());
which will make sure that contour_struct
is the right size.
这将确保contour_struct的大小合适。
#1
2
cv::findContours(result,found_contour,found_hierachy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,cv::Point(0,0));
std::vector<Contours> contour_struct;
contour_struct.reserve(found_contour.size()); //<-----problem
for (size_t i = 0; i < found_contour.size(); i++)
{
contour_struct[i].contour = found_contour[i];
contour_struct[i].minRect = cv::minAreaRect(cv::Mat(found_contour[i]));
}
vector::reserve
only aquires space internally so that push_back
does not run out of space. It does not actually add more objects into the vector
. You can use this line instead:
vector :: reserve仅在内部获取空间,以便push_back不会耗尽空间。它实际上并没有在向量中添加更多对象。您可以使用此行代替:
contour_struct.resize(found_contour.size());
which will make sure that contour_struct
is the right size.
这将确保contour_struct的大小合适。