• C++ std::vector 基本用法2


    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    int main() 
    {
    	int ar[10] = { 1,2,3,4,5,6,7,8,9,0 };
    	std::vector<int> vec5(ar, ar + 10);
    
    	// reverse
    	size_t cap1 = vec5.capacity();	// = 10
    	vec5.reserve(20);				// = Request a change in capacity
    	size_t cap2 = vec5.capacity();	// = 20
    
    	// data()
    	int * pInt = vec5.data();
    	for (size_t i=0; i<vec5.size(); ++i)
    	{
    		cout << pInt[i];
    	}
    	cout << endl; // 1234567890
    
    	// begin end
    	for (auto it=vec5.begin(); it != vec5.end(); ++it)
    	{
    		cout << *it;
    	}
    	cout << endl; // 1234567890
    
    	// cbegin cend 常量,保证不改变 vector 中的元素
    	for (auto it = vec5.cbegin(); it != vec5.cend(); ++it)
    	{
    		cout << *it;
    	}
    	cout << endl; // 1234567890
    
    	// rbegin rend 注意偏移是 ++ 操作
    	for (auto it = vec5.rbegin(); it != vec5.rend(); ++it)
    	{
    		cout << *it;
    	}
    	cout << endl; // 0987654321
    
    	// iterator erase (const_iterator position);
    	vec5.erase(vec5.begin()); // delete 1; size = 9
    
    	// iterator erase (const_iterator first, const_iterator last);
    	vec5.erase(vec5.begin(), vec5.begin()+2); // delete 2, 3; size = 7
    
    	// max_size; Returns the maximum number of elements that the vector can hold.
    	// 系统或者库的设计上线。并非机器所能申请的最大大小。	
    	size_t maxSize = vec5.max_size();
    
    	std::vector<int> vec6(2);
    	vec5.swap(vec6);					// 两者交换
    	///vec5.swap(std::vector<int>());	// 2015支持,2017不支持
    
    	// iterator insert( iterator pos, const T& value );
    	auto it = vec5.begin();
    	vec5.insert(it, 101);
    
    	it = vec5.begin(); // it 已经失效
    	vec5.insert(it +1, 102);
    		
    	// iterator insert(const_iterator pos, const T& value);
    	const std::vector<int>::iterator cit = vec5.begin();
    	vec5.insert(cit, 103); 
    
    	// void insert( iterator pos, size_type count, const T& value );
    
    	// iterator insert( const_iterator pos, size_type count, const T& value );
    	vec5.insert(vec5.begin(), 2, 104); // insert 2 个 104
    
    	// template< class InputIt >
    	// void insert(iterator pos, InputIt first, InputIt last);
    	vec5.insert(vec5.begin(), vec6.begin(), vec6.end()); // insert vec6
    
    	// iterator insert( const_iterator pos, std::initializer_list<T> ilist );
    	vec5.insert(vec5.begin(), {105,106,107});
    
    
    }
    

      

  • 相关阅读:
    第三次作业——《原型设计》
    第二次作业《熟悉使用工具》
    跟着《构建之法》学习软件工程(第一次作业)
    纯js代码实现手风琴特效
    HTML5
    为什么做前端要做好SEO
    让div盒子相对父盒子垂直居中的几种方法
    模板artTemplate
    bootstrap兼容问题
    移动常用的类库
  • 原文地址:https://www.cnblogs.com/alexYuin/p/12032231.html
Copyright © 2020-2023  润新知