0

I want to print this array [1,2,3,4] as a 2D array [[1,2],[3,4]]. This is the code. I am not getting these line

vector<int> aux(&original[i], &original[i+n]);
ans.push_back(aux);

how the syntax of 2D vector is working? Here is the function code?

class Solution {
public:
    vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
        vector<vector<int>> ans;
        int p = original.size();
        if(m*n != p)
            return ans;
    for(int i=0;i<p;i+=n){
            vector<int> aux(&original[i], &original[i+n]);
            ans.push_back(aux);
        }
        return ans;
    }
};
  • [Constructor (5)](https://en.cppreference.com/w/cpp/container/vector/vector) – PaulMcKenzie Feb 26 '23 at 09:43
  • 1
    Are you using leetcode to learn C++? If so don't (you may ask me why) – Pepijn Kramer Feb 26 '23 at 09:45
  • Good sources to learn cpp from are : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date since C++ evolves and better techniques are added each release. – Pepijn Kramer Feb 26 '23 at 09:45
  • xaviour1504 did the answer clear things up or do you want me to explain anything in more detail? – Ted Lyngmo Feb 26 '23 at 14:15
  • yes I got it thanks for help. – xaviour1504 Feb 27 '23 at 05:53

1 Answers1

0
vector<int> aux(&original[i], &original[i+n]);

is using the vector constructor that takes two iterators:

template< class InputIt >
constexpr vector( InputIt first, InputIt last,
                  const Allocator& alloc = Allocator() );

and populates the new vector as-if by doing something similar to this:

int* first = &original[i];
int* last = &original[i+n];
for(; first != last; ++first) aux.emplace_back(*first);

Note that ans.push_back(aux); should have been ans.push_back(std::move(aux)); to not copy the whole vector but instead move it into ans.

Also note that creating the aux container is totally unnecessary. You can create it in-place directly in ans instead which saves the time of copying/moving aux into ans.

ans.emplace_back(&original[i], &original[i+n]);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108