vector<vector<string>> Reverse(vector<vector<string>> a){
vector<string> dd;
for(int i = 0; i < a.size()/2; i ){
dd = a[i];
a[i] = a[-1*(i) - 1];
a[-1*(i) - 1] = dd;
}
return a;
}
I want to make a Reverse function that reverses vectors in a vector but i get and error:
libc abi: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
CodePudding user response:
You are trying to access negative positions in a vector. Positions starts from 0 to vector.size(). It's very bad what you are doing.You are getting a matrix and try to transform it in a vector? You should review your code. Maybe you meant something like this?
vector<vector<string>> reverseRows(vector<vector<string>> a){
for(int i=0;i<a.size();i ){
for(int j=0;j<a[i].size()/2;i ){
string temp=a[i][j];
a[i][j]=a[i][a[i].size()-j-1];
a[i][a[i].size()-j-1]=temp;
}
}
return a;
}
vector<vector<string>> reverseMatrix(vector<vector<string>> a){
for(int i=0;i<a.size()/2;i ){
vector<string> temp=a[i][j];
a[i][j]=a[i][a[i].size()-j-1];
a[i][a[i].size()-j-1]=temp;
}
return a;
}
CodePudding user response:
Don't reinvent the wheel:
#include <vector>
#include <algorithm>
std::vector<std::vector<std::string>> reverseInner(std::vector<std::vector<std::string>> a) {
for_each(begin(a),end(a),[](auto& v) { reverse(begin(v),end(v)); });
return a;
}
std::vector<std::vector<std::string>> reverseOuter(std::vector<std::vector<std::string>> a) {
reverse(begin(a),end(a));
return a;
}