How to take a vector of points and grab only 'y' of those points
Unfortunately my math abilities and objective-c/c/c++ isn't developed enough to understand how to do this.
I have a vector set up like this: [2,2,3,3,4,4,5,5,6,6] <-- i think thats how vectors are set up correct?
Th开发者_Python百科is is sort of what i think it should be set up:
vector<CGPoint>::iterator i;
vector<CGPoint>* dp = xGraph.GraphPoints;
for(i = dp->begin(); i != dp->end(); ++i){
/* grab y points only code here*/
}
Now I want to write some kind of for
statement that takes xGraph.GraphPoints
and only grabs the y coords.
and... i guess puts it into another vector of only y coords, which looks like [2,3,4,5,6] after the code is finished
Can someone help me out here?
Cheers
Ok, my interpretation of your question is that you have a vector that contains CGPoint
objects and you want to extract only the y
coordinate from all of the points. In that case you want something like (using C++11 lambdas):
std::vector<CGFloat> ycoord;
std::transform( dp->begin(), dp->end(), std::back_inserter( ycoord ),
[]( CGPoint const & p ){ return p.y; } );
If the compiler does not support lambdas, you can write a simple function to perform the extraction:
CGFloat extractY( CGPoint const & p ) {
return p.y;
}
std::transform( dp->begin(), dp->end(), std::back_inserter( ycoord ),
&extractY );
Or functor:
struct extractYfunctor {
CGFloat operator()( CGPoint const & p ) const {
return p.y;
}
};
std::transform( dp->begin(), dp->end(), std::back_inserter( ycoord ),
extractYfuctor() );
If you can use the boost libraries:
std::transform( dp->begin(), dp->end(), std::back_inserter( ycoord ),
boost::bind( &CGPoint::y, _1 ) );
Or with a plain loop:
for ( std::vector< CGPoint >::const_iterator it = dp->begin(); it != dp->end(); ++it ) {
ycoord.push_back( it->y );
}
Your vector is not set up like [2,2,3,3,4,4,5,5,6,6]. It's set up like this: [(2,2),(3,3),(4,4),(5,5),(6,6)]. That is, it's a list of pairs of numbers, not just a list of numbers. To get the y
component of each element in the vector, you can write a loop like this:
vector<CGPoint>* dp = xGraph.GraphPoints;
for(i = dp->begin(); i != dp->end(); ++i){
/* grab y points only code here*/
CGFloat current_y = i->y;
}
vector<CGPoint>::iterator i;
vector<CGPoint>* dp = xGraph.GraphPoints;
vector<CGFloat> dp = yPoints;
for(i = dp->begin(); i != dp->end(); ++i){
yPoints.push_back(i->y);
}
vectors are indeed laid out like that in memory, but not logically. Don't overthink things. It's still a vector of CGFloat
objects.
精彩评论