Question

C++ Write a function template for a function named rotate, with 2 args: an array of...

C++

Write a function template for a function named rotate, with 2

args: an array of some type, and an unsigned that is the number

of elements in the array. Assume without checking that the

number of elements is > 1.

rotate's job is to rearrange the array elements so that

every value is moved to the adjacent element with index one

larger than it had originally, except the value in the last

element is moved to the first position.

For example, the array {"This", "That", "The", "Other"} (with 5 elements) would be changed to {"Other", "This", "That", "The"}.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
#include <string>
using namespace std;

template <class T>
void rotate(T arr[], unsigned int size) {
    T temp = arr[size-1];
    for(int i = size-1; i > 0; --i) {
        arr[i] = arr[i-1];
    }
    arr[0] = temp;
}

template <class T>
void output(T arr[], unsigned int size) {
    for(int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
}


int main() {
    string strings[] = {"This", "That", "The", "Other"};
    cout << "Original: ";
    output(strings, 4);
    rotate(strings, 4);
    cout << "Rotated: ";
    output(strings, 4);

    int numbers[] = {2, 9, 1, 5, 3};
    cout << "Original: ";
    output(numbers, 5);
    rotate(numbers, 5);
    cout << "Rotated: ";
    output(numbers, 5);
    return 0;
}
Add a comment
Know the answer?
Add Answer to:
C++ Write a function template for a function named rotate, with 2 args: an array of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT