Re: std::vector : begin, end and insert - Using Objects instead of ints
On Wed, 11 Apr 2007 04:19:36 -0700, "Nobody" <Nobody@yahoo.com> wrote:
*Now, all I have to do is get by the insert problem.
CPoint pt(1,2);
m_Pts.insert(Pt, m_Pts.begin()+1, m_Pts.begin()+2);
How do I insert it?
There are several overloads of std::vector<T>::insert method.
I think the simplest form is:
// Insert a new point in 3rd position
points.insert( points.begin() + 2, Point(100, 200) );
You might want to consider the code I pasted into this post (see
main() function).
The output is following:
<OUTPUT>
*** TEST VECTOR INSERT ***
Point list:
[(1, 3), (2, 0), (3, 10), (33, 312)]
After insertion:
[(1, 3), (2, 0), (100, 200), (3, 10), (33, 312)]
</OUTPUT>
<CODE>
//
// Testing std::vector insert
// by MrAsm
//
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
// A 2D point
class Point
{
public:
Point() : X(0), Y(0) {}
Point( int x, int y ) : X(x), Y(y) {}
int X;
int Y;
std::string ToString() const
{
std::ostringstream os;
os << "(" << X << ", " << Y << ")";
return os.str();
}
};
typedef std::vector<Point> PointList;
// Print list of points
std::ostream & operator<<( std::ostream & os,
const PointList & points )
{
if ( ! points.empty() )
{
os << "[" << points.at(0).ToString();
for ( size_t i = 1; i < points.size(); i++ )
{
os << ", " << points.at(i).ToString();
}
os << "]";
}
else
{
os << "[<<empty>>]";
}
return os;
}
using std::cout;
using std::endl;
int main()
{
cout << "*** TEST VECTOR INSERT ***" << endl;
cout << endl;
PointList points;
points.push_back(Point(1, 3));
points.push_back(Point(2, 0));
points.push_back(Point(3, 10));
points.push_back(Point(33, 312));
cout << "Point list: " << endl;
cout << points << endl;
// Insert in 3rd position
points.insert( points.begin() + 2, Point(100, 200) );
cout << "After insertion:" << endl;
cout << points << endl;
system("PAUSE");
return 0;
}
</CODE>
MrAsm