Hello

My task is to writ a function that takes in a char array & the array size as its parameters & reverses the array contents. I cannot use another array to reverse the contents.

I am using insert & erase function to reverse the array, although I dont know which library I am meant to use & the correct syntax of the commands(insert & erase)?

Libraries:

dequeue
list
map
string
set
multimap

Any Advice?

#include <iostream>

using namespace std;

void reverse (char a[], int n);

int main() {

	char x[5] = {'a', 'b', 'c', 'd', 'e'};

	reverse(x,5);

	return 0;
}

void reverse (char a[], int n) {

	for (int i=0; i<n; i++) {
		insert(a[i],a[n-i]);  // is this the correct sytax??
		erase(a[n-i]);        // or should it be a[i].insert();
	}

Dani AI

Generated

For a plain C-style char array there is no insert or erase free function. Those are member functions of containers such as std::string, std::vector, or std::deque (as noted). The simplest, cheapest way to reverse an array in place is to swap elements from the ends inward (as suggested). This is O(n) time and O(1) extra memory.

A manual in-place swap implementation:

void reverse(char a[], int n) {
    for (int i = 0, j = n - 1; i < j; ++i, --j) {
        char tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

A standard-library one-liner using <algorithm>:

#include <algorithm>

std::reverse(a, a + n);

See the standard reference for std::reverse for details: std::reverse.

Common pitfalls and clarifications drawn from the thread:

  • Arrays have indices 0..n-1. In code the expression a[n-i] should be a[n-1-i], and the loop should stop at the middle (i < j), not run all the way to n.
  • If the data is a null-terminated C-string, avoid reversing the terminating '\0' (use the length without the null).
  • Converting to std::string to use its member insert/erase is possible but unnecessary and typically slower; prefer swapping or std::reverse for this task.

Recommended Answers

All 4 Replies

What happens if you just swap the first and last elements of the array?

Um, I not quite sure what you mean, but what I am trying to do is reverse the contents in an array

eg
from this: a,b,c,d,e

to this: e,d,c,b,a

So
abcde
becomes after 1 step
ebcda

Move towards the middle, and repeat....

string have insert and replace

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.