1、vector删除指定元素且不改变原有的顺序
使用erase方法,测试例子如下所示:
//测试用例
struct MyStruct
{int a;int b;
};
std::vector<MyStruct> spotInfo;
spotInfo.push_back({ 1,2 });
spotInfo.push_back({ 3,4 });
spotInfo.push_back({ 5,6 });
spotInfo.push_back({ 7,8 });
spotInfo.push_back({ 9,10 });
spotInfo.erase(spotInfo.begin() + 2);
for (int i = 0; i < spotInfo.size(); i++)
{std::cout << "#########spotInfo: " << spotInfo[i].a << "," << spotInfo[i].b << std::endl;
}
结果:
可以看到结果中已经将索引为2的元素剔除了,并且还是保持着原来的元素顺序。
2、cv::Mat删除指定元素且不改变原有的顺序
opencv没有提供删除Mat指定列或行的函数,下边给出了删除Mat指定行的函数:
int deleteOneColOfMat(cv::Mat& object, int num)
{if (num < 0 || num >= object.cols){std::cerr << "ERRROR: the column num are outside of the object matrix...." << std::endl;return -1;}if (num == object.cols - 1){object = object.t(); //求逆矩阵object.pop_back(); //弹出最后一行元素object = object.t();}else{//num 列之后的所有数据前移一列for (int i = num + 1; i < object.cols; i++){object.col(i - 1) = object.col(i) + cv::Scalar(0, 0, 0, 0);}object = object.t();object.pop_back();object = object.t();}return 0;
}
一维数据时的测试用例:
cv::Mat mat = (cv::Mat_<int>(1, 20) <<1, 2, 3,11,4, 5, 6,22,7, 8, 9,33,10, 11, 12,44,13, 14, 15,55);
deleteOneColOfMat(mat, 1);
std::cout<<"mat1:"<<mat<<std::endl;
deleteOneColOfMat(mat, 2);
std::cout << "mat2:" << mat << std::endl;
deleteOneColOfMat(mat, 0);
std::cout<<"mat3:"<<mat<<std::endl;
测试结果:
可以看到已经正确将指定位置:1、2、0的元素删除了,并且没有改变原来的位置。
二维数据时的测试用例:
cv::Mat mat = (cv::Mat_<int>(5, 4) <<1, 2, 3,11,4, 5, 6,22,7, 8, 9,33,10, 11, 12,44,13, 14, 15,55);
deleteOneColOfMat(mat, 1);
std::cout<<"mat1:" << std::endl << mat<<std::endl;
deleteOneColOfMat(mat, 2);
std::cout << "mat2:" << std::endl << mat << std::endl;
deleteOneColOfMat(mat, 0);
std::cout<<"mat3:" << std::endl << mat<<std::endl;
测试结果:
可以看到已经正确将指定列:1、2、0删除了,并且没有改变原来的位置。