如何在不丢失现有数据的情况下调整std

如何在不丢失现有数据的情况下调整std

本文介绍了如何在不丢失现有数据的情况下调整std :: vector的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个算法,需要我从一个向量中删除和添加相同的元素每个循环的迭代。



示例:



迭代1:| 1 2 3 4 | (size 4)



迭代2:| 1 3 | 2 4(尺寸2,元素'2'和'4'仍然在内存中,但不在向量的大小中计算)



迭代3:| 1 2 3 | 4(尺寸3,元素'4'仍然存在)



基本上,我想能够更改size()函数返回的值,因为性能原因。



我知道我可以使用我的向量之外的另一个变量来跟踪它的大小,但我想知道是否可能直接内部

解决方案


减少 size()报告的值的唯一方法是调整大小。当调整大小减小大小时,新大小以外的元素不再存在,就程序而言。任何访问它们的方法(或在你的情况下重新访问它们)都会产生未定义的行为。



如果你想跟踪数组的元素数量,你使用一个向量的两个元素与五个元素),然后创建一个额外的变量来跟踪。为了说明(希望)明显的,该变量将需要与向量的大小保持一致(例如,以避免跟踪在具有五个元素的向量中使用十个元素)。



如果你想保持变量的向量,使 struct / 类型。该类可以提供成员函数或操作来管理向量和正在使用的元素数量,以确保一致性。


I was implementing an algorithm that needs me to remove and add the same elements from a vector each iteration of a loop.

Example:

iteration 1 : |1 2 3 4| (size 4)

iteration 2 : |1 3| 2 4 (size 2 with the elements '2' and '4' still there in memory but not accounted for in the size of the vector)

iteration 3 : |1 2 3| 4 (size 3 with the element '4' still there)

Basically, I want to be able to change the value returned by the size() function without affecting the vector for performance reasons.

I know I could use another variable outside of my vector to keep track of its size, but I wanted to know if it could be possible directly internally in the std::vector container.

Thanks for any help.

解决方案

You can't do that.

The only way to reduce the value reported by size() is to resize. When resizing reduces the size, the elements outside the new size no longer exist as far as the program is concerned. Any means of accessing them (or reaccessing them, in your case) yields undefined behaviour.

If you want to track the number of elements of an array in use (say, that you are using two elements of a vector with five elements) then create an extra variable to keep track of that. To state the (hopefully) obvious, that variable will need to be kept consistent with the size of the vector (e.g. to avoid tracking that ten elements are being used in a vector with five elements).

If you want to keep the variable with the vector, make both members of a struct/class type. That class can provide member functions or operations that manage both the vector and the number of elements "in use", to ensure consistency.

这篇关于如何在不丢失现有数据的情况下调整std :: vector的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:56