How to initialize a matrix in a function and return it efficiently in C++?Return a 2d array from a functionwhat is the best modern c++ approach to construct and manipulate a 2d arrayHow to initialize private static members in C++?What should main() return in C and C++?How do you declare an interface in C++?How can I profile C++ code running on Linux?Why do we need virtual functions in C++?C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Using a vector of unique pointers to an <Employee> vectorError C2280: attempting to reference a deleted function (unique_ptr)String to a unique pointer arrayMethods for getting a const view of a container of smart pointers
Linear and Integer programming materials
Are there reliable, formulaic ways to form chords on the guitar?
What allows us to use imaginary numbers?
My new Acer Aspire 7 doesn't have a Legacy Boot option, what can I do to get it?
Did they show Truman doing private things (toilet, etc) when filming him for 24 hours, 7 days a week?
What's the point of writing that I know will never be used or read?
Unsolved Problems due to Lack of Computational Power
Has there ever been a truly bilingual country prior to the contemporary period?
What does a comma signify in inorganic chemistry?
Meaning and structure of headline "Hair it is: A List of ..."
Have made several mistakes during the course of my PhD. Can't help but feel resentment. Can I get some advice about how to move forward?
How does the illumination of the sky from the sun compare to that of the moon?
Why should I pay for an SSL certificate?
Outer Class can have how many inner class(es)
Gofer work in exchange for Letter of Recommendation
What happened after the end of the Truman Show?
Would getting a natural 20 with a penalty still count as a critical hit?
Spongy green glass found on graves
Rotate List by K places
Why should P.I be willing to write strong LOR even if that means losing a undergraduate from his/her lab?
How can I train a replacement without them knowing?
My father gets angry everytime I pass Salam, that means I should stop saying Salam when he's around?
Earliest evidence of objects intended for future archaeologists?
The anatomy of an organic infrared generator
How to initialize a matrix in a function and return it efficiently in C++?
Return a 2d array from a functionwhat is the best modern c++ approach to construct and manipulate a 2d arrayHow to initialize private static members in C++?What should main() return in C and C++?How do you declare an interface in C++?How can I profile C++ code running on Linux?Why do we need virtual functions in C++?C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Using a vector of unique pointers to an <Employee> vectorError C2280: attempting to reference a deleted function (unique_ptr)String to a unique pointer arrayMethods for getting a const view of a container of smart pointers
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
My task is to generate a square matrix of zeros in a function and return it. There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency. I went for a pointer approach like in this answer, but since it requires manual cleaning memory (and also as far as I know it's better to use smart pointers), I decided to turn it into std::unique_ptr, but I can't get it to work. This is my code:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i].get()[j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix[j].get()[i]<<" ";
std::cout<<std::endl;
return 0;
What do I do wrong here? Is this approach even correct?
c++
|
show 6 more comments
My task is to generate a square matrix of zeros in a function and return it. There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency. I went for a pointer approach like in this answer, but since it requires manual cleaning memory (and also as far as I know it's better to use smart pointers), I decided to turn it into std::unique_ptr, but I can't get it to work. This is my code:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i].get()[j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix[j].get()[i]<<" ";
std::cout<<std::endl;
return 0;
What do I do wrong here? Is this approach even correct?
c++
1
std::unique_ptr<std::unique_ptr<int>[]>is not a 2D matrix. You wantstd::unique_ptr<std::unique_ptr<int[]>[]>.
– HolyBlackCat
Mar 27 at 13:51
2
std::vector<std::vector<int>>possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)
– Jarod42
Mar 27 at 13:51
2
You don't benefit from usingstd::unique_ptrin this case.
– vahancho
Mar 27 at 13:53
1
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
2
Both copy-elision and move-semantics makes it better to use a plainstd::vectorhere and return it by value.
– super
Mar 27 at 14:02
|
show 6 more comments
My task is to generate a square matrix of zeros in a function and return it. There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency. I went for a pointer approach like in this answer, but since it requires manual cleaning memory (and also as far as I know it's better to use smart pointers), I decided to turn it into std::unique_ptr, but I can't get it to work. This is my code:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i].get()[j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix[j].get()[i]<<" ";
std::cout<<std::endl;
return 0;
What do I do wrong here? Is this approach even correct?
c++
My task is to generate a square matrix of zeros in a function and return it. There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency. I went for a pointer approach like in this answer, but since it requires manual cleaning memory (and also as far as I know it's better to use smart pointers), I decided to turn it into std::unique_ptr, but I can't get it to work. This is my code:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i].get()[j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix[j].get()[i]<<" ";
std::cout<<std::endl;
return 0;
What do I do wrong here? Is this approach even correct?
c++
c++
asked Mar 27 at 13:46
ElgirhathElgirhath
868 bronze badges
868 bronze badges
1
std::unique_ptr<std::unique_ptr<int>[]>is not a 2D matrix. You wantstd::unique_ptr<std::unique_ptr<int[]>[]>.
– HolyBlackCat
Mar 27 at 13:51
2
std::vector<std::vector<int>>possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)
– Jarod42
Mar 27 at 13:51
2
You don't benefit from usingstd::unique_ptrin this case.
– vahancho
Mar 27 at 13:53
1
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
2
Both copy-elision and move-semantics makes it better to use a plainstd::vectorhere and return it by value.
– super
Mar 27 at 14:02
|
show 6 more comments
1
std::unique_ptr<std::unique_ptr<int>[]>is not a 2D matrix. You wantstd::unique_ptr<std::unique_ptr<int[]>[]>.
– HolyBlackCat
Mar 27 at 13:51
2
std::vector<std::vector<int>>possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)
– Jarod42
Mar 27 at 13:51
2
You don't benefit from usingstd::unique_ptrin this case.
– vahancho
Mar 27 at 13:53
1
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
2
Both copy-elision and move-semantics makes it better to use a plainstd::vectorhere and return it by value.
– super
Mar 27 at 14:02
1
1
std::unique_ptr<std::unique_ptr<int>[]> is not a 2D matrix. You want std::unique_ptr<std::unique_ptr<int[]>[]>.– HolyBlackCat
Mar 27 at 13:51
std::unique_ptr<std::unique_ptr<int>[]> is not a 2D matrix. You want std::unique_ptr<std::unique_ptr<int[]>[]>.– HolyBlackCat
Mar 27 at 13:51
2
2
std::vector<std::vector<int>> possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)– Jarod42
Mar 27 at 13:51
std::vector<std::vector<int>> possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)– Jarod42
Mar 27 at 13:51
2
2
You don't benefit from using
std::unique_ptr in this case.– vahancho
Mar 27 at 13:53
You don't benefit from using
std::unique_ptr in this case.– vahancho
Mar 27 at 13:53
1
1
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
2
2
Both copy-elision and move-semantics makes it better to use a plain
std::vector here and return it by value.– super
Mar 27 at 14:02
Both copy-elision and move-semantics makes it better to use a plain
std::vector here and return it by value.– super
Mar 27 at 14:02
|
show 6 more comments
4 Answers
4
active
oldest
votes
Why not just make your life easier by
vector<vector<int>> generate (int m, int n)
return vector<vector<int>>(m ,vector<int>(n));
int main()
int m = 3, n = 4;
auto matrix = generate(m, n); // a 3-by-4 matrix of zeros
return 0;
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
add a comment |
Just rely on guarenteed copy elision or return value optimization:
std::vector<int> GenerateMatrix(const int &n)
return std::vector<int>(n*n, 0);//, 0 can be omitted (as elements will then be zero-initialized)
It seems you are wrong with the order of arguments withstd::vector<int>(0, n*n).
– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
add a comment |
You might create and initialize a matrix at compile time. For example:
template<int RowCount, int ColumnCount, int DefaultValue = 0>
struct Matrix
static_assert(RowCount >= 0 && ColumnCount >=0,
"The number of rows and columns should be positive");
struct Row
int column[ColumnCount] = DefaultValue ;
;
Row row[RowCount];
;
And use it like:
Matrix<2, 2, 33> matrix;
auto val = matrix.row[0].column[0]; // val == 33
matrix.row[0].column[0] = 55;
val = matrix.row[0].column[0]; // val == 55
Beware the matrix dimensions, when refer to its elements by row and column.
Or juststd::array<std::array<T, N>, N>.
– Jarod42
Mar 28 at 2:26
Notice that your default value only is formatrix[x][0], matrix[x][1] would be0.
– Jarod42
Mar 28 at 2:27
add a comment |
You are not allocating enough memory for your matrix. Change this line:
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
Also, I would just use i*n + j for your accesses since you are really dealing with a 1D array:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix.get()[i*n+j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix.get()[i*n+j]<<" ";
std::cout<<std::endl;
return 0;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378782%2fhow-to-initialize-a-matrix-in-a-function-and-return-it-efficiently-in-c%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Why not just make your life easier by
vector<vector<int>> generate (int m, int n)
return vector<vector<int>>(m ,vector<int>(n));
int main()
int m = 3, n = 4;
auto matrix = generate(m, n); // a 3-by-4 matrix of zeros
return 0;
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
add a comment |
Why not just make your life easier by
vector<vector<int>> generate (int m, int n)
return vector<vector<int>>(m ,vector<int>(n));
int main()
int m = 3, n = 4;
auto matrix = generate(m, n); // a 3-by-4 matrix of zeros
return 0;
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
add a comment |
Why not just make your life easier by
vector<vector<int>> generate (int m, int n)
return vector<vector<int>>(m ,vector<int>(n));
int main()
int m = 3, n = 4;
auto matrix = generate(m, n); // a 3-by-4 matrix of zeros
return 0;
Why not just make your life easier by
vector<vector<int>> generate (int m, int n)
return vector<vector<int>>(m ,vector<int>(n));
int main()
int m = 3, n = 4;
auto matrix = generate(m, n); // a 3-by-4 matrix of zeros
return 0;
answered Mar 27 at 13:56
fleixfleix
5804 silver badges12 bronze badges
5804 silver badges12 bronze badges
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
add a comment |
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
The issue for perfomance with this solution is that it doesn't store the data contigously in memory.
– darune
Mar 27 at 14:00
add a comment |
Just rely on guarenteed copy elision or return value optimization:
std::vector<int> GenerateMatrix(const int &n)
return std::vector<int>(n*n, 0);//, 0 can be omitted (as elements will then be zero-initialized)
It seems you are wrong with the order of arguments withstd::vector<int>(0, n*n).
– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
add a comment |
Just rely on guarenteed copy elision or return value optimization:
std::vector<int> GenerateMatrix(const int &n)
return std::vector<int>(n*n, 0);//, 0 can be omitted (as elements will then be zero-initialized)
It seems you are wrong with the order of arguments withstd::vector<int>(0, n*n).
– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
add a comment |
Just rely on guarenteed copy elision or return value optimization:
std::vector<int> GenerateMatrix(const int &n)
return std::vector<int>(n*n, 0);//, 0 can be omitted (as elements will then be zero-initialized)
Just rely on guarenteed copy elision or return value optimization:
std::vector<int> GenerateMatrix(const int &n)
return std::vector<int>(n*n, 0);//, 0 can be omitted (as elements will then be zero-initialized)
edited Mar 27 at 14:18
answered Mar 27 at 13:58
darunedarune
3,0929 silver badges27 bronze badges
3,0929 silver badges27 bronze badges
It seems you are wrong with the order of arguments withstd::vector<int>(0, n*n).
– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
add a comment |
It seems you are wrong with the order of arguments withstd::vector<int>(0, n*n).
– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
It seems you are wrong with the order of arguments with
std::vector<int>(0, n*n).– fleix
Mar 27 at 14:05
It seems you are wrong with the order of arguments with
std::vector<int>(0, n*n).– fleix
Mar 27 at 14:05
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@fleix correct, fixed now
– darune
Mar 27 at 14:06
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
@Bob__ I have added you comment ... as a comment :)
– darune
Mar 27 at 14:20
add a comment |
You might create and initialize a matrix at compile time. For example:
template<int RowCount, int ColumnCount, int DefaultValue = 0>
struct Matrix
static_assert(RowCount >= 0 && ColumnCount >=0,
"The number of rows and columns should be positive");
struct Row
int column[ColumnCount] = DefaultValue ;
;
Row row[RowCount];
;
And use it like:
Matrix<2, 2, 33> matrix;
auto val = matrix.row[0].column[0]; // val == 33
matrix.row[0].column[0] = 55;
val = matrix.row[0].column[0]; // val == 55
Beware the matrix dimensions, when refer to its elements by row and column.
Or juststd::array<std::array<T, N>, N>.
– Jarod42
Mar 28 at 2:26
Notice that your default value only is formatrix[x][0], matrix[x][1] would be0.
– Jarod42
Mar 28 at 2:27
add a comment |
You might create and initialize a matrix at compile time. For example:
template<int RowCount, int ColumnCount, int DefaultValue = 0>
struct Matrix
static_assert(RowCount >= 0 && ColumnCount >=0,
"The number of rows and columns should be positive");
struct Row
int column[ColumnCount] = DefaultValue ;
;
Row row[RowCount];
;
And use it like:
Matrix<2, 2, 33> matrix;
auto val = matrix.row[0].column[0]; // val == 33
matrix.row[0].column[0] = 55;
val = matrix.row[0].column[0]; // val == 55
Beware the matrix dimensions, when refer to its elements by row and column.
Or juststd::array<std::array<T, N>, N>.
– Jarod42
Mar 28 at 2:26
Notice that your default value only is formatrix[x][0], matrix[x][1] would be0.
– Jarod42
Mar 28 at 2:27
add a comment |
You might create and initialize a matrix at compile time. For example:
template<int RowCount, int ColumnCount, int DefaultValue = 0>
struct Matrix
static_assert(RowCount >= 0 && ColumnCount >=0,
"The number of rows and columns should be positive");
struct Row
int column[ColumnCount] = DefaultValue ;
;
Row row[RowCount];
;
And use it like:
Matrix<2, 2, 33> matrix;
auto val = matrix.row[0].column[0]; // val == 33
matrix.row[0].column[0] = 55;
val = matrix.row[0].column[0]; // val == 55
Beware the matrix dimensions, when refer to its elements by row and column.
You might create and initialize a matrix at compile time. For example:
template<int RowCount, int ColumnCount, int DefaultValue = 0>
struct Matrix
static_assert(RowCount >= 0 && ColumnCount >=0,
"The number of rows and columns should be positive");
struct Row
int column[ColumnCount] = DefaultValue ;
;
Row row[RowCount];
;
And use it like:
Matrix<2, 2, 33> matrix;
auto val = matrix.row[0].column[0]; // val == 33
matrix.row[0].column[0] = 55;
val = matrix.row[0].column[0]; // val == 55
Beware the matrix dimensions, when refer to its elements by row and column.
answered Mar 27 at 15:09
vahanchovahancho
16.4k3 gold badges27 silver badges35 bronze badges
16.4k3 gold badges27 silver badges35 bronze badges
Or juststd::array<std::array<T, N>, N>.
– Jarod42
Mar 28 at 2:26
Notice that your default value only is formatrix[x][0], matrix[x][1] would be0.
– Jarod42
Mar 28 at 2:27
add a comment |
Or juststd::array<std::array<T, N>, N>.
– Jarod42
Mar 28 at 2:26
Notice that your default value only is formatrix[x][0], matrix[x][1] would be0.
– Jarod42
Mar 28 at 2:27
Or just
std::array<std::array<T, N>, N>.– Jarod42
Mar 28 at 2:26
Or just
std::array<std::array<T, N>, N>.– Jarod42
Mar 28 at 2:26
Notice that your default value only is for
matrix[x][0], matrix[x][1] would be 0.– Jarod42
Mar 28 at 2:27
Notice that your default value only is for
matrix[x][0], matrix[x][1] would be 0.– Jarod42
Mar 28 at 2:27
add a comment |
You are not allocating enough memory for your matrix. Change this line:
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
Also, I would just use i*n + j for your accesses since you are really dealing with a 1D array:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix.get()[i*n+j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix.get()[i*n+j]<<" ";
std::cout<<std::endl;
return 0;
add a comment |
You are not allocating enough memory for your matrix. Change this line:
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
Also, I would just use i*n + j for your accesses since you are really dealing with a 1D array:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix.get()[i*n+j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix.get()[i*n+j]<<" ";
std::cout<<std::endl;
return 0;
add a comment |
You are not allocating enough memory for your matrix. Change this line:
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
Also, I would just use i*n + j for your accesses since you are really dealing with a 1D array:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix.get()[i*n+j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix.get()[i*n+j]<<" ";
std::cout<<std::endl;
return 0;
You are not allocating enough memory for your matrix. Change this line:
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
Also, I would just use i*n + j for your accesses since you are really dealing with a 1D array:
#include <iostream>
#include <memory>
std::unique_ptr<std::unique_ptr<int>[] > GenerateMatrix(const int &n)
std::unique_ptr<std::unique_ptr<int>[] > matrix(new std::unique_ptr<int>[n*n]);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix.get()[i*n+j] = 0;
return matrix;
int main()
int n = 4;
auto matrix = GenerateMatrix(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout<<matrix.get()[i*n+j]<<" ";
std::cout<<std::endl;
return 0;
edited Mar 27 at 14:11
answered Mar 27 at 14:00
GardenerGardener
2,0191 gold badge7 silver badges17 bronze badges
2,0191 gold badge7 silver badges17 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55378782%2fhow-to-initialize-a-matrix-in-a-function-and-return-it-efficiently-in-c%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
std::unique_ptr<std::unique_ptr<int>[]>is not a 2D matrix. You wantstd::unique_ptr<std::unique_ptr<int[]>[]>.– HolyBlackCat
Mar 27 at 13:51
2
std::vector<std::vector<int>>possibly wrapped in class. (and if wrapped, flat the vector and do index computation manually for cache friendly)– Jarod42
Mar 27 at 13:51
2
You don't benefit from using
std::unique_ptrin this case.– vahancho
Mar 27 at 13:53
1
"There are plenty ways to do this, but I decided not to go with returning the matrix by value for efficiency." This assumption is wrong - please understand return value optimization and guarenteed copy elision. Morale here: premature optimization is the root of all evil
– darune
Mar 27 at 13:55
2
Both copy-elision and move-semantics makes it better to use a plain
std::vectorhere and return it by value.– super
Mar 27 at 14:02