又遇到问题了 一直在线 马上给分

zyb_debug 2008-04-21 06:23:53
int *Values =new int [10];

Values[0]=0;
.......
Values[9]=9;

我现在要改便Values的大小
让Values有11个空间
Values[10]=10;
前面的数字不变
怎么实现

也就是我想知道vector 是怎么实现push_back的
...全文
53 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zyb_debug 2008-04-21
  • 打赏
  • 举报
回复
那个叫做过儿的 我怎么就给不了你分呢????????
zyb_debug 2008-04-21
  • 打赏
  • 举报
回复
强大 我怎么就像不到呢。!!!!!!!!!!!!!!!!!
太感谢了
baihacker 2008-04-21
  • 打赏
  • 举报
回复
	void push_back(const _Ty& _Val)
{ // insert element at end
if (size() < capacity())

#if _HAS_ITERATOR_DEBUGGING
{ // room at end, construct it there
_Orphan_range(_Mylast, _Mylast);
_Mylast = _Ufill(_Mylast, 1, _Val);
}

#else /* _HAS_ITERATOR_DEBUGGING */
_Mylast = _Ufill(_Mylast, 1, _Val);
#endif /* _HAS_ITERATOR_DEBUGGING */

else
insert(end(), _Val);
}
独孤过儿 2008-04-21
  • 打赏
  • 举报
回复
vector会动态的管理它的大小,它有一个capacity()的成员函数,能显示出它当前可用的存储能力:

size_type capacity () const;

Return size of allocated storage capacity

Returns the size of the allocated storage space for the elements of the vector container.

Notice that, in vectors, the capacity is not necessarily equal to the number of elements that conform the underlying vector content (this can be obtained with member vector::size), but the capacity of the actual allocated space, which is either equal or greater than the content size.

Notice also that this capacity does not suppose a limit to the size of the vector. If more space is required to accomodate new elements in the vector, the capacity is automatically expanded, or can even be explicitly modified by calling member vector::reserve.

The real limit on the size a vector object can reach is returned by member vector::max_size.


Parameters
none

Return Value
The size of the currently allocated storage capacity in the vector, measured in the number elements it could hold.
Member type size_type is an unsigned integral type.


Example
// comparing size, capacity and max_size
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
vector<int> myvector;

// set some content in the vector:
for (int i=0; i<100; i++) myvector.push_back(i);

cout << "size: " << (int) myvector.size() << "\n";
cout << "capacity: " << (int) myvector.capacity() << "\n";
cout << "max_size: " << (int) myvector.max_size() << "\n";
return 0;
}


A possible output for this program could be:
size: 100
capacity: 141
max_size: 1073741823


baihacker 2008-04-21
  • 打赏
  • 举报
回复
int* temp = new int[11];
memcpy(temp, Values, sizeof(int) * 10);
temp[10] = 10;
delete[] Values;
Values = temp;
temp = 0;

64,632

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧