1. 程式人生 > >【STL】vector的五種建構函式

【STL】vector的五種建構函式

vector的五種建構函式, 例子摘自MSDN
void test_vector_constructor()
{
	// 0. Create an empty vector v0
	std::vector<int> v0;
	assert(v0.empty());

	// 1. Create a vector v1 with 3 elements of default value 0
	std::vector<int> v1(3);

	// 2. Create a vector v2 with 5 elements of value 2
	std::vector<int> v2(5, 2);

	// 3. Create a vector v3 with 3 elements of value 1 and with the allocator of vector v2
	std::vector<int> v3(3, 1, v2.get_allocator());

	// 4. Create a copy, vector v4, of vector v2
	std::vector<int> v4(v2);

	// 5. Create a vector v5 by copying the range v4[_First, _Last)
	std::vector<int> v5(v4.begin() + 1, v4.begin() + 3);

	std::cout << "v1 = ";
	std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	std::cout << "v2 = ";
	std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	std::cout << "v3 = ";
	std::copy(v3.begin(), v3.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	std::cout << "v4 = ";
	std::copy(v4.begin(), v4.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	std::cout << "v5 = ";
	std::copy(v5.begin(), v5.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	// Move vector v2 to vector v6
	std::vector<int> v6(move(v2));

	std::cout << "v6 = ";
	std::copy(v6.begin(), v6.end(), std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;
};