Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

copy 2d vector without first row and column

Just like in topic. I would like to copy one vector to another without first row and column.

”’

std::vector<std::vector<int>> v2(v1.size()-1,std::vector<int>(v1.size()-1));

std::copy((v1.begin()+1)->begin()+1,v1.end()->end(),v2.begin()->begin());

return v2;

”’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using C++ and views it is easy to drop items while enumerating.
So you can avoid using raw or iterator loops.
Live demo here : https://godbolt.org/z/8xz91Y8cK

#include <ranges>
#include <iostream>
#include <vector>

auto reduce_copy(const std::vector<std::vector<int>> values)
{
    std::vector<std::vector<int>> retval{};

    // drop first row
    for (const auto& row : values | std::views::drop(1))
    {
        // add a new row to retval
        auto& new_row = retval.emplace_back();

        // drop first column
        for (const auto& col : row | std::views::drop(1))
        {
            new_row.emplace_back(col);
        }
    }

    return retval;
}


int main()
{

    std::vector<std::vector<int>> values{ {1,2,3}, {4,5,6}, {7,8,9} };
    auto result = reduce_copy(values);

    for (const auto& row : result)
    {
        for (const auto& value : row)
        {
            std::cout << value << " ";
        }
        std::cout << "\n";
    }
    
    
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading