Mc Missile
Mc Missile

Reputation: 735

using std::fill on a 2D int vector

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.

Upvotes: 5

Views: 10779

Answers (3)

Shrikanth N
Shrikanth N

Reputation: 652

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

Upvotes: 3

BartekPL
BartekPL

Reputation: 2420

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.

Upvotes: 3

code707
code707

Reputation: 1701

You could use like this:

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

Upvotes: 5

Related Questions