vector的成员函数resize分析

注意:如下源码的执行和实现分析仅适用Linux平台,其他平台暂未测试。

一直以为一个class的vector,当进行resize操作的时候,会调用n次构造函数。但其实不是,无论resize(n)中的n有多大或是多小,在进行resize操作的时候仅仅只会调用一次构造函数。

比如下面的例子:

源码:

/*
 *vec.cpp
 */
#include <vector>
#include <iostream>
using namespace std;

class A
{
    public:
        A(){cout<<"create."<<endl;}
        ~A(){cout<<"destory."<<endl;}
};

int main()
{
    vector<A> vecA;
    
    cout<<"resize(10)"<<endl;
    vecA.resize(10);
    
    cout<<"resize(5)"<<endl;
    vecA.resize(5);

    cout<<"end."<<endl;

    return 0;
}

输出:

resize(10)
create.
destory.
resize(5)
create.
destory.
destory.
destory.
destory.
destory.
destory.
end.
destory.
destory.
destory.
destory.
destory.


分析原因:
resize的源码如下:

      /**  
       *  @brief  Resizes the %vector to the specified number of elements.
       *  @param  new_size  Number of elements the %vector should contain.
       *  @param  x  Data with which new elements should be populated.
       *
       *  This function will %resize the %vector to the specified
       *  number of elements.  If the number is smaller than the
       *  %vector's current size the %vector is truncated, otherwise
       *  the %vector is extended and new elements are populated with
       *  given data.
       */
      void 
      resize(size_type __new_size, value_type __x = value_type())
      {    
		if (__new_size > size())
		  insert(end(), __new_size - size(), __x);
		else if (__new_size < size())
		  _M_erase_at_end(this->_M_impl._M_start + __new_size);
      }

我们发现,在resize开始的时候就会构造一个临时的class A的变量,不妨设为tmpA。
如果__new_size > size(),就会进行insert的操作,其实insert的实现是这样的(伪代码):

	bool insert(iterator _pos, int _size, A tmpA)
	{
		//申请空间
		A *listA = (A *)malloc(sizeof(A)*_size);
		
		//赋值
		for(int i=0; i<_size; i++)
		{
			memcpy(listA+i, &tmpA, sizeof(A));
		}
		
		//将listA中的各个元素链接到vector中
		...
		
	}


如果__new_size < size(),就会进行erase操作,直接调用相应的析构函数就ok啦,
最后同样不要忘了tmpA的析构。


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
vector有多个成员函数可用于操作和访问向量元素。 1. push_back(Type val):将val添加到向量尾部。 2. pop_back():删除最后一个元素。 3. begin():返回指向第一个元素的迭代器。 4. end():返回指向最后一个元素之后的迭代器。 5. clear():删除向量中的所有元素。 6. at(n):返回第n个位置的引用。 7. empty():检查向量是否为空。 8. front():返回第一个元素的引用。 9. back():返回最后一个元素的引用。 10. shrink_to_fit():将向量的capacity调整为和size相同。 11. get_allocator():获取分配器。 此外,还有一些其他的成员函数: - size():返回向量中元素的数量。 - capacity():返回当前向量的容量。 - max_size():返回向量可容纳的最大元素数量。 - resize(int n):重新设置向量的大小。 - resize(int n, Type val):重新设置向量的大小,并使用给定的值填充新添加的元素。 - emplace(const iterator iter, Type val):在指定的迭代器位置插入元素。 - data():返回指向向量中第一个元素的指针。 以上是一些vector的常用成员函数,可以用于向量的操作和访问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [STL vector成员函数详解](https://blog.csdn.net/qq_38843532/article/details/115919763)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值