5

I am trying to set the values of all elements in 2D vector to a particular value. As far as I am aware of, one cannot use memset for vectors like how they are used for arrays. Hence I have to use std::fill to set all elements in 2D vector to a particular value. However, I am aware of how to use fill for a 1D vector as show below.

vector<int> linearVector (1000,0);
fill(linearVector.begin(),linearVector.end(),10);

However, when I try to do something similar for a 2D vector(as shown below) it does not work.

vector<vector<int> > twoDVector (100,vector <int> (100,0));
fill(twoDVector.begin(),twoDVector.end(),10);

PS: I am aware that I can easily design a nested for loop to manually set the elements of the 2D vector to the value I want. However, It is not feasible in my program as the size of the 2D vector is quite large and there are other time consuming functions(recursive functions) happening in parallel.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mc Missile
  • 715
  • 11
  • 25
  • 4
    Hint: It's not a 2D vector. It's a vector of vectors. – eesiraed Jul 04 '18 at 05:14
  • 1
    Hint: You already filled every element of `twoDVector` (and every element of each of those elements) with the same value, when you initialised it – Caleth Jul 04 '18 at 08:05
  • *one cannot use memset for vectors like how they are used for arrays*: actually you can, `data()` method return the raw array, and on that you can use `memset`. Since C++ 11 only. – Marco Luzzara Jul 04 '18 at 15:48

3 Answers3

3

In C++17 you can do it as below:

#include <algorithm>
#include <execution>
#include <vector>

//...    

std::for_each(std::execution::par_unseq, nums.begin(), nums.end(),
    [](std::vector<int>& vec) {
    std::for_each(std::execution::par_unseq, vec.begin(), vec.end(),
    [](int& n) {n = 10;});}
);

It seems to be parallel, but not as clear as simple fill function ;)

Of course you can pass your own variable instead of hardcoded 10.

BartekPL
  • 2,290
  • 1
  • 17
  • 34
3

This should help you

std::vector<std::vector<int> > fog(
A_NUMBER,
std::vector<int>(OTHER_NUMBER)); // Defaults to zero initial value

Reference: Initializing a two dimensional std::vector

Shrikanth N
  • 652
  • 3
  • 17
2

You could use like this:

fill(twoDVector.begin(), twoDVector.end(), vector<int>(100, 10));
code707
  • 1,663
  • 1
  • 8
  • 20