首页 > 应用开发 > C/C++ > 如何优雅地从 C++ 向量中提取二维矩形区域
template <class T> std::vector<T> copyRectFromVector(const std::vector<T>& vec, std::size_t startx, std::size_t starty, std::size_t endx, std::size_t endy, std::size_t fieldWidth, std::size_t fieldHeight)
{ using namespace std; vector<T> ret((endx-startx)*(endy-starty)+10); // 10: chickenfactor
// checks if the given parameters make sense:
if (vec.size() < fieldWidth*endy)
{
cerr << "Error: CopyRectFromVector: vector to small to contain rectangular region!" << std::endl; return ret;
}
// do the copying line by line:
vector<T>::const_iterator vecIt = vec.begin();
vector<T>::forward_iterator retIt = ret.end();
vecIt += startx + (starty*fieldWidth);
for(int i=starty; i < endy; ++i)
{
std::copy(vecIt, vecIt + endx - startx, retIt);
}
return ret;}
vector<pixels> my_picture;point selTopLeft(10,10), selBotRight(40, 50);int picWidth(640), picHeight(480);rectangular_selection<vector<pixels> > selection1(my_picture.begin(), my_picture.end(), picWidth, picHeight, selTopLeft, selBotRight);// Now you can use stl algorithms on your rectangular rangevector<pixels> rect_copy = std::copy(selection1.begin(), selection1.end());// or maybe you don't want to copy, you want // to modify the selection in placestd::for_each (selection1.begin(), selection1.end(), invert_color);
#include <vector>#include <algorithm>#include <iostream>#include <iterator>template <typename I, typename O>
void copyRectFromBiggerRect(
I input,
O output,
std::size_t startx,
std::size_t cols,
std::size_t starty,
std::size_t rows,
std::size_t stride
) {
std::advance(input, starty*stride + startx); while(rows--) {
std::copy(input, input+cols, output);
std::advance(input, stride);
}}template<typename T>
std::vector<T> copyRectFromVector ( const std::vector<T> &vec,
std::size_t startx,
std::size_t starty,
std::size_t endx,
std::size_t endy,
std::size_t stride
) { // parameter-checking omitted: you could also check endx > startx etc.
const std::size_t cols = endx - startx; const std::size_t rows = endy - starty;
std::vector<T> ret;
ret.reserve(rows*cols);
std::back_insert_iterator<std::vector<T> > output(ret);
typename std::vector<T>::const_iterator input = vec.begin(); copyRectFromBiggerRect(input,output,startx,cols,starty,rows,stride); return ret;}int main() { std::vector<int> v(20); for (int i = 0; i < 20; ++i) v[i] = i;
std::vector<int> v2 = copyRectFromVector(v, 0, 0, 1, 2, 4);
std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70016198/viewspace-2886077/ ,如需转载,请注明出处,否则将追究法律责任。