/// Compile script:
/// $ g++ -std=c++11 test_vector.cc
#include <vector>
#include <iostream>
#include <string>
using std::vector;
using std::cout;
using std::endl;
using std::string;
template <typename Container>
void print_container(Container c);
int main()
{
vector<int> v1;
cout << "v1 capacity: " << v1.capacity() << endl;
cout << "v1 size: " << v1.size() << endl;
v1.assign(7, 10);
cout << "v1 capacity: " << v1.capacity() << endl;
cout << "v1 size: " << v1.size() << endl;
print_container<vector<int>>(v1);
vector<int> v2(v1);
if (!v2.empty())
print_container<vector<int>>(v2);
v1.clear();
cout << "v1 capacity: " << v1.capacity() << endl;
cout << "v1 size: " << v1.size() << endl;
vector<int> v3(7, 10); // seven 10's
vector<int> v4(7); // seven 0's
cout << "v4 capacity: " << v4.capacity() << endl;
cout << "v4 size: " << v4.size() << endl;
vector<int> v5(v4.begin(), v4.end());
print_container<vector<int>>(v5);
v5.assign(v3.begin(), v3.end());
print_container<vector<int>>(v5);
// cout << v5.at(7) << endl; // throw exception
cout << v5.at(6) << endl;
cout << v5.back() << endl;
vector<int>::iterator it = v1.begin();
cout << *it << endl;
cout << "v5 before erasing begin: ";
print_container<vector<int>>(v5);
vector<int>::iterator bit = v5.begin();
v5.erase(bit);
cout << "v5 after erasing begin: ";
print_container<vector<int>>(v5);
cout << "v5 capacity: " << v5.capacity() << ", v5 size: " << v5.size() << " before erasing all" << endl;
v5.erase(v5.begin(), v5.end());
cout << "v5 capacity: " << v5.capacity() << ", v5 size: " << v5.size() << " after erasing all" << endl;
vector<int> v6(5, 1);
vector<int> v7(3, 7);
v6.insert(v6.begin(), 100);
cout << "v6 insert at begin: ";
print_container<vector<int>>(v6);
v6.insert(v6.begin(), 4, 200);
cout << "v6 insert 4 items at begin: ";
print_container<vector<int>>(v6);
v6.insert(v6.end(), v7.begin(), v7.end());
cout << "v6 insert v7 at the end: ";
print_container<vector<int>>(v6);
cout << "max size of vector<int>: " << v7.max_size() << endl;
vector<string> vstr;
cout << "max size of vector<string>: " << vstr.max_size() << endl;
vector<int> v8(4,5);
vector<int> v9(5,3);
v8.swap(v9);
print_container<vector<int>>(v8);
print_container<vector<int>>(v9);
return 0;
}
template <typename Container>
void print_container(Container c)
{
for (typename Container::iterator it = c.begin();
it != c.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
}
STL vector基本用法示例
最新推荐文章于 2021-07-06 15:37:56 发布