anfjnlnl
anfjnlnl

Reputation: 65

slicing in 2d vector cpp

I want to create a new row in my 2d vector with the elements from index 1 to the end of the previous row. I wrote the below code but it is wrong. Can you please help me.

   vector<vector<int>> res;
   k=res.size();
   res.push_back(res[k-1].begin()+1,res[k-1].end());

Upvotes: 1

Views: 435

Answers (2)

user107511
user107511

Reputation: 812

When you use vector::push_back you append an element from value_type of the vector, and you can't push_back a range

https://www.cplusplus.com/reference/vector/vector/push_back/

You should call std::vector constructor in order to construct the new row, and push it to your vector:

res.push_back(vector(res[k-1].begin()+1,res[k-1].end()));

You can also call the constructor implicitly by using {}, but implicit constructors might make your code harder to maintain.

res.push_back({res[k-1].begin()+1,res[k-1].end()});

Upvotes: 3

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

You are only missing a {}:

#include <vector>
int main()
{
   std::vector<std::vector<int>> res{{1,2,3,4,5}};
   auto k=res.size();
   res.push_back({res[k-1].begin()+1,res[k-1].end()});
}

push_back takes an element of the container that you need to construct, and that is a std::vector<int>. Alternatively you can call emplace_back wich does work with parameters for the elements constructor:

res.emplace_back(res[k-1].begin()+1,res[k-1].end());

Upvotes: 3

Related Questions