-1
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

bigbng
  • 11
  • 1
  • Did you try debugging the code? This is not Python, `a[-1]` does not grab the last element. – Quimby May 10 '22 at 07:14
  • What is this `-1*(i) - 1`? – 273K May 10 '22 at 07:15
  • 2
    Did you consider [`std::reverse`](https://en.cppreference.com/w/cpp/algorithm/reverse)? – paolo May 10 '22 at 07:17
  • 2
    If you're assuming that C++ is like Python, get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start at the beginning without assuming that you know anything. – molbdnilo May 10 '22 at 07:18
  • The usefulness of doing this is marginalized tremendously if you consider `std::reverse(a.begin(), a.end());` at the calller-site of this makes its very existence irrelevant. Unless you have a substantial reason to do otherwise (read: grade) don't reinvent the wheel. Related, if all the caller eventually wants to do is enumerate the vector backward, and that's the reason for this reversal, you don't need *any* of this; reverse iterators will do it for you (again, free of charge). – WhozCraig May 10 '22 at 07:21

2 Answers2

1

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;
}
Bat Man
  • 53
  • 7
0

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;
}
bitmask
  • 32,434
  • 14
  • 99
  • 159