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;
'''
CodePudding user response:
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;
}
CodePudding user response:
You can use for example the ordinary for loop
#include <vector>
#include <iterator>
#include <algorithm>
//...
for ( auto first = std::next( std::begin( v1 ) ), target = std::begin( v2 );
first != std::end( v1 );
first, target )
{
std::copy( std::next( std::begin( *first ) ), std::end( *first ), std::begin( *target ) );
}