If I have a 2D vector like this that has 5000 elements declared.
If I have filled 2500 of these elements with Numbers, what is the best way if
I want to "emty" these elements so these elements will turn to 0 wich I beleive is the defaultvalue for all elements before I started to fill them ?

Is a for loop the best way to do it while putting all elements to zero (0).

std::vector<std::vector<int> > Numbers(5000, std::vector<int>(5000));

Hi Jennifer.

You can use the fill algorithm:

#include <algorithm>
#include <vector>

int main()
{
  std::vector<int> Numbers( 5000, 42 );  // 5,000 '42's.
  std::fill(
    Numbers.begin(),
    Numbers.end(),
    0  // Turn them '42's into '0's
    );
}

Now, if you really are using a vector of vectors (5000 * 5000 elements), you can use the transform() algorithm to better success.

#include <algorithm>
#include <vector>

std::vector<int> fill_zero( std::vector<int> v )
{
  std::fill( v.begin(), v.end(), 0 );
  return v;
}

int main()
{
  // 25,000 '42's in a square matrix
  std::vector<std::vector<int> > Numbers(5000, std::vector<int>(5000, 42));

  // Turn them all to zeros
  std::transform(
    Numbers.begin(),  // what to read
    Numbers.end(),    // when to stop reading
    Numbers.begin(),  // where to put the results
    fill_zero
    );
}

You'll notice that you can stick the results back into the same vector. You don't have to, though.

Hope this helps.

as your 2D vector is 'rectangular' ( not 'jagged' ), you could just

#include <vector>

int main()
{
  // 25,000 '42's in a square matrix
  enum { N = 5000, M = 5000, VALUE = 42 };
  using std::vector ;
  vector< vector<int> > Numbers( N, vector<int>( M, VALUE ) );

  // Turn them all to zeros
  Numbers.assign( N, vector<int>(M) ) ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.