Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to memset on 2d vector

So I have a 2D Vector here that I want to assign a value num, I want to see which performs better fill vs memset() as C++ noob, I am actually having problem setting the proper code syntax as I just always get Segmentation fault when I do it.

vector<vector<int>> matrix(10, vector<int>(10000000));
int main()
{
    int num;
    cin >> num;
    int i = 0;
    for (auto &i : matrix)
    {
        fill(i.begin(), i.end(), num); 
    }
    return 0;
}
like image 678
Zambodia Avatar asked Feb 28 '26 03:02

Zambodia


1 Answers

You can use memset for std::vector<int>, I don't think it's be such a good idea and it's fairly ugly with std::vector. Yes you can use std::fill the way you using it but there is a simpler way in your case, use std::vector constructor. Like this :

int main()
{
    int num;
    std::cin >> num;
    std::vector<std::vector<int>> matrix(10, std::vector<int>(10000000, num));
    return 0;
}
like image 84
HMD Avatar answered Mar 02 '26 18:03

HMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!