64,660
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class test
{
friend ostream &operator << (ostream &output, const test &obj)
{
output << obj.value << endl;
}
public:
test(int a) : value(a) { cout << "construct " << value << endl;};
~test() {cout << "destruct " << value << endl;};
private:
int value;
};
int main(int argc, char *argv[])
{
test t1(1),t2(2), t3(3), t4(4);
ostream_iterator<test> output(cout, " ");
vector<test> vt;
vt.push_back(t1);
vt.push_back(t2);
vt.push_back(t3);
vt.push_back(t4);
copy(vt.begin(), vt.end(), output1);
cout << "erase first elemant: " << endl;
vt.erase(vt.begin());
copy(vt.begin(), vt.end(), output);
}
:!./a.out
construct 1
construct 2
construct 3
construct 4
destruct 1
destruct 1
destruct 2
1
2
3
4
erase first elemant:
destruct 4
2
3
4
construct 1
construct 2
construct 3
construct 4
destruct 1
destruct 1
destruct 2
destruct 1
destruct 2
destruct 3
1 2 3 4
erase first elemant:
destruct 4
2 3 4
destruct 2
destruct 3
destruct 4
destruct 4
destruct 3
destruct 2
destruct 1
源代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class test
{
friend ostream &operator << (ostream &output, const test &obj)
{
output << obj.value;
}
public:
test(int a) : value(a) { cout << "construct " << value << endl;};
~test() {cout << "destruct " << value << endl;};
private:
int value;
};
int main(int argc, char *argv[])
{
test t1(1),t2(2), t3(3), t4(4);
ostream_iterator<test> output(cout, " ");
vector<test> vt;
vt.push_back(t1);
vt.push_back(t2);
vt.push_back(t3);
vt.push_back(t4);
copy(vt.begin(), vt.end(), output);
cout << endl;
cout << "erase first elemant: " << endl;
vt.erase(vt.begin());
copy(vt.begin(), vt.end(), output);
cout << endl;
return 0;
}
输出:
:!g++ b.cpp
:!./a.out
construct 1
construct 2
construct 3
construct 4
destruct 1
destruct 1
destruct 2
1 2 3 4
erase first elemant:
destruct 4
2 3 4
destruct 2
destruct 3
destruct 4
destruct 4
destruct 3
destruct 2
destruct 1