Trying to reverse a C++ array and at the same time store it into a new array

前端 未结 2 1636
长发绾君心
长发绾君心 2021-01-29 05:18

I\'m trying to reverse an array and simultaneously store it in a new array with for loops. I have achieved it somewhat manually but not with loops. The first code b

相关标签:
2条回答
  • 2021-01-29 05:25

    You have two nested loops, and they are not doing what you think they are doing. You only need one:

    int y, s;
    
    s = strlen(wrd) - 1;
    
    for (y = 0; y<=s; y++)
    {
        rev[y] = wrd[s - y];
    }
    

    and don't forget to terminate:

    rev[s + 1] = 0;
    
    0 讨论(0)
  • 2021-01-29 05:32

    Since you're using C++, take advantage of the libraries it offers. Depending on whether or not you want memory-sequential access to the elements (if you're going to read it out as a string, you probably do) you could use std::vector with reverse or alternatively a list/forward_list if contiguous access isn't an issue. std::list has the benefit of directly offering a reverse method.

    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    //int main() {
        vector<char> chars;
        const char *mystr = "abcdef";
        chars.reserve(6);
        chars.assign(mystr, mystr+6); //assuming we don't want the null terminator.
        reverse(chars.begin(), chars.end());
        cout << string(&chars.front(), chars.size()) << endl;
    //}
    

    The reserve is included to maximise the performance of the copy operation.

    Additionally, if mystr was declared as a char array (or at least, pointed to writable memory) you could simply do reverse(mystr, mystr+6) too.

    0 讨论(0)
提交回复
热议问题