Resize std :: vector without destroying elements

I use the same one all the time std::vector<int>to avoid all the time being exempt from shutdown. In a few lines, my code looks like this:

std::vector<int> myVector;
myVector.reserve(4);

for (int i = 0; i < 100; ++i) {
    fillVector(myVector);
    //use of myVector
    //....
    myVector.resize(0);
}

In each for iteration myVectorup to 4 elements are filled. To make efficient code, I want to use always myVector. However, the myVector.resize()elements in are myVectordestroyed. I understand that it myVector.clear()will have the same effect.

I think that if I could just overwrite existing elements in myVector, I could save some time. However, I think I am std::vectornot able to do this.

Is there any way to do this? Does it make sense to create a home implementation that overwrites the elements?

+3
5

std::vector . //(de) ? .

  • fillVector() "" , .
  • T *.
  • () .

Ok. :

struct upTo4ElemVectorOfInts
{
  int data[4];
  size_t elems_num;
};

fillVector(), :

void fillVector(upTo4ElemVectorOfInts& vec)
{
  //fill vec.data with values
  vec.elems_num = filled_num; //save how many values was filled in this iteration
}

:

upTo4ElemVectorOfInts myVector;

for (int i = 0; i < 100; ++i)
{
  fillVector(myVector);
  //use of myVector:
  //- myVector.data contains data (it equivalent of std::vector<>::data())
  //- myVector.elems_num will tell you how many numbers you should care about
  //nothing needs to be resized/cleared
}

:

( ), , , :

template <class T, size_t Size>
struct upToSizeElemVectorOfTs
{
  T data[Size];
  size_t elems_num;
};

fillVector(), .

, , . : ", 100 ? 1000? 10000? ? 10000- !". . , , , . , , , . , . , 1.000.000 ( Stack Overflow ).

-1

(myVector.clear() , myVector.resize(0) ).

'int destructor' .
resize(0) size 0, capacity .

+5

myVector. ( std::vector<int> myVector(4)) (, myVector[0] = 5).

, , std::array<int, 4>.

+4

0 , int, :

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{1,2,3};
    std::cout << v.capacity() << ' ';
    v.resize(0);
    std::cout << v.capacity() << '\n';
}

// Output: 3 3

; , , , , " 0" std::vector, , , if .

+3

,

for (int i = 0; i < 100; ++i) {
    myVector.reserve(4);
    //use of myVector
    //....
    myVector.resize(0);
}

.

, myVector.clear() myVector.resize(0);

4 ,

std::vector<int> myVector( 4 );

std::vector<int> myVector;
myVector.reserve(4);

, fillVector (myVector); 4 - push_back

Otherwise, use clearas suggested earlier.

0
source

All Articles