减少stl载体的能力 [英] reduce the capacity of an stl vector

查看:99
本文介绍了减少stl载体的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有减少向量容量的方法吗?



我的代码将值插入向量(不知道它们的数字),



我想我可以创建一个新的向量,做一个.reseve()与大小和副本
的项目,但我不是真的喜欢额外的复制操作。



PS:我不在乎便携式解决方案,只要它工作gcc。

解决方案

  std :: vector< T>(v).swap ); 

与另一个向量交换内容会交换容量。

  std :: vector< T>(v).swap(v); ==>相当于

std :: vector< T> tmp(v); //将元素复制到临时向量
v.swap(tmp); // swap内部向量数据

Swap()只会更改内部数据结构。

Is there a way to reduce the capacity of a vector ?

My code inserts values into a vector (not knowing their number beforehand), and when this finishes, the vectors are used only for read operations.

I guess I could create a new vector, do a .reseve() with the size and copy the items, but I don't really like the extra copy operation.

PS: I don't care for a portable solution, as long as it works for gcc.

解决方案

std::vector<T>(v).swap(v);

Swapping the contents with another vector swaps the capacity.

  std::vector<T>(v).swap(v); ==> is equivalent to 

 std::vector<T> tmp(v);    // copy elements into a temporary vector
         v.swap(tmp);              // swap internal vector data

Swap() would only change the internal data structure.

这篇关于减少stl载体的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆