There is std::reverse(), you know...
#include <algorithm>
std::reverse(reverse.constBegin(), reverse.constEnd());
#include <algorithm>
QByteArray reverse = seq;
std::reverse(reverse.constBegin(), reverse.constEnd());
To copy to clipboard, switch view to plain text mode
You can also use reverse_copy:
std::reverse_copy(seq.constBegin(), seq.constEnd(), reverse.begin());
QByteArray reverse;
std::reverse_copy(seq.constBegin(), seq.constEnd(), reverse.begin());
To copy to clipboard, switch view to plain text mode
Complexity is O(n).
There is also the trivial approach:
reverse.reserve(ba.size());
for(int i=ba.size(); i>=0; --i) reverse.append(ba.at(i));
return reverse;
}
QByteArray reverse(const QByteArray &ba) {
QByteArray reverse;
reverse.reserve(ba.size());
for(int i=ba.size(); i>=0; --i) reverse.append(ba.at(i));
return reverse;
}
To copy to clipboard, switch view to plain text mode
I can also imagine parallelizing the algorithm by dividing the array into chunks and reversing each chunk in a separate thread.
Added after 21 minutes:
Here is a complete implementation:
#include <QByteArray>
#include <QtConcurrentMap>
struct Chunk {
char *ba;
int size;
int from;
int cnt;
};
void swapChunk(const Chunk &ch) {
const int size = ch.size;
char *baRef = ch.ba;
for(int i=0;i<ch.cnt;++i) {
int i1 = ch.from+i;
int i2 = size-1-ch.from-i;
qSwap(baRef[i1], baRef[i2]);
}
}
char *dat = ba.data();
int threads
= QThread::idealThreadCount();
int bytesPerThread = ba.size()/2/threads; // if size not even, the middle doesn't change anyway
// prepare work
QList<Chunk> chunks;
for(int i=0;i<threads;++i) {
Chunk ch;
ch.ba = dat;
ch.size = ba.size();
ch.from = bytesPerThread*i;
ch.cnt = bytesPerThread;
chunks << ch;
}
// execute
QtConcurrent::blockingMap(chunks, swapChunk);
return ba;
}
int main() {
for(int i=0;i<10;++i) {
ba += "0123456789";
}
qDebug() << reverseInParallel(ba);
return 0;
}
#include <QByteArray>
#include <QtConcurrentMap>
struct Chunk {
char *ba;
int size;
int from;
int cnt;
};
void swapChunk(const Chunk &ch) {
const int size = ch.size;
char *baRef = ch.ba;
for(int i=0;i<ch.cnt;++i) {
int i1 = ch.from+i;
int i2 = size-1-ch.from-i;
qSwap(baRef[i1], baRef[i2]);
}
}
QByteArray reverseInParallel(QByteArray ba) {
char *dat = ba.data();
int threads = QThread::idealThreadCount();
int bytesPerThread = ba.size()/2/threads; // if size not even, the middle doesn't change anyway
// prepare work
QList<Chunk> chunks;
for(int i=0;i<threads;++i) {
Chunk ch;
ch.ba = dat;
ch.size = ba.size();
ch.from = bytesPerThread*i;
ch.cnt = bytesPerThread;
chunks << ch;
}
// execute
QtConcurrent::blockingMap(chunks, swapChunk);
return ba;
}
int main() {
QByteArray ba;
for(int i=0;i<10;++i) {
ba += "0123456789";
}
qDebug() << reverseInParallel(ba);
return 0;
}
To copy to clipboard, switch view to plain text mode
Bookmarks