【STL】vector常用函数的例子
// erase功能:移除vector中部分的元素void test_vector_erase(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> vect(t, t + 7);std::cout << "vect = ";std::copy(vect.begin(), vect.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;// 重载方法1vect.erase(vect.begin() + 2, vect.begin() + 5);std::cout << "vect = ";std::copy(vect.begin(), vect.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;// 重新初始化vect.clear();vect.push_back(10);vect.push_back(11);vect.push_back(12);vect.push_back(13);vect.push_back(14);vect.push_back(15);vect.push_back(16);// 重载方法2vect.erase(vect.begin() + 2);std::cout << "vect = ";std::copy(vect.begin(), vect.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}// clean功能:移除vector中所有元素void test_vector_clear(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> vect(t, t + 7);std::cout << "vect = ";std::copy(vect.begin(), vect.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;vect.clear();assert(vect.empty());std::cout << "vect = ";std::copy(vect.begin(), vect.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}void test_vector_assign(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> v1(t, t + 7);std::vector<int> v2, v3;v2.assign(v1.begin(), v1.end());std::cout << "v2 = ";std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;v3.assign(7, 10);std::cout << "v3 = ";std::copy(v3.begin(), v3.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}void test_vector_at(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> vect(t, t + 7); int &i = vect.at(0);int &j = vect.at(3);int &k = vect.front();int &m = vect.back(); assert(i == 10);assert(j == 13);assert(k == 10);assert(m == 16);}void test_vector_pop(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> v1(t, t + 7);v1.pop_back();std::cout << "v1 = ";std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}void test_vector_swap(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> v1(t, t + 7);std::vector<int> v2(7, 10);std::cout << "v1 = ";std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;v2.swap(v1); std::cout << "v1 = ";std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));std::cout << std::endl;}// iterator,const_iterator作用:遍历容器内的元素,并访问这些元素的值。 // 区别:iterator可以改元素值,但const_iterator不可改。void test_vector_const_iterator(){int t[7] = {10, 11, 12, 13, 14, 15, 16}; std::vector<int> v1(t, t + 7);std::cout << "v1 = ";for (std::vector<int>::const_iterator cit = v1.begin(); cit != v1.end(); ++cit)std::cout << *cit << " ";std::cout << std::endl;}// 功能:为vector预分配内存空间。void test_vector_reserve(){std::vector<int> v1;v1.push_back(10);std::cout << v1.capacity() << std::endl;v1.reserve(30);std::cout << v1.capacity() << std::endl;}