UBears
UBears

Reputation: 369

Rotate last n elements of array in C++

I'm trying to implement a function that deletes a character from a string wherever the current index is. Below is a skeleton of what I have so far. I'm trying to rotate the character I want to remove to the end of the string then replace it with a null terminator. The code I have below does not seem to actually rotate buffer because the output I'm getting is "wor" instead of the expected output "wrd".

int main() {
    char buffer[]="word";
    int currIndex=2;
    int endIndex=strlen(buffer);
    currIndex--;
    endIndex--;

    rotate(buffer+currIndex,
        buffer+1,
        buffer+strlen(buffer));
    buffer[endIndex]='\0';
    cout << buffer << endl;

    return 0;
}

Upvotes: 1

Views: 357

Answers (2)

IInspectable
IInspectable

Reputation: 51464

This doesn't attempt to answer the question being asked, but rather solve the underlying problem: Removing a single character from a string.

The solution is a simple application of the std::string::erase class member:

#include <string>
#include <iostream>

int main() {
    std::string word{ "word" };
    std::string::size_type currIndex{ 2 };
    word.erase( currIndex, 1 );
    std::cout << word << std::endl;
}

Upvotes: 4

AndyG
AndyG

Reputation: 41110

Using a std::string makes things way easier because I don't have to think about pointers:

std::string buffer="word";
rotate(buffer.begin()+1, buffer.begin()+2, buffer.end());
buffer.resize(buffer.size()-1);

Demo

Alternatively, we can stick with a c-style array:

char buffer[]="word";
rotate(buffer+1, buffer+2, buffer+4);
buffer[3] = '\0';

Demo2


std::rotate accepts 3 arguments:

template< class ForwardIt >
ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last );

first is the first element in the range you want to left rotate.

nfirst is the element you want to be at the start of the range after you've rotated (this tells the algorithm how many times to left rotate, effectively)

last is the last element in the range you want to rotate.

Your code:

char buffer[]="word";
int currIndex=2;
int endIndex=strlen(buffer);
currIndex--;
endIndex--;
rotate(buffer+currIndex,
    buffer+1,
    buffer+strlen(buffer));
buffer[endIndex]='\0';

Was actually really close. You just got the second argument wrong. It should have been

rotate(buffer+currIndex,
    buffer+2,
    buffer+strlen(buffer));
buffer[endIndex]='\0';

But the code was admittedly a bit confusing written with the increments and decrements.

Upvotes: 1

Related Questions