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

前端 未结 2 1635
长发绾君心
长发绾君心 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: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 
    #include 
    
    using namespace std;
    
    //int main() {
        vector 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.

提交回复
热议问题