why this code giving error mismatch in strcpy - c++

There is a mismatch error in strcpy() function. I'm new to the C++ language.
#include<iostream>
#include<cstring>
using namespace std;
#define max 5
class ss {
private:
char str[max][10];
public:
void get_str() {
for (int i = 0; i < max; i++)
cin >> str[i];
}
void disp() {
cout << "Entered strings are\n";
for (int i = 0; i < max; i++) {
if (strcmp(str[i], str[i + 1]) != 0)
cout << str[i] << endl;
}
}
/*
void sort()
{
char temp[max];
for (int i = 0; i < max - 1; i++)
for (int j = 0; j < (max - i - 1); j++)
{
if (strcmp(str[j], str[j + 1])>0)
{
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
disp();
}
*/
void qsort()
{
qs(str, 0, max - 1);
disp();
}
void qs(char *&str, int st, int e)
{
int pi = part(str, st, e);
qs(s, st, pi - 1);
qs(s, pi + 1, e);
}
int part(char *&s, int st, int e)
{
char pi[max], swap[max];
strcpy(pi, s[e]);
int pii = st;
int i = st;
for (i; i < e; i++) {
if ((strcmp(s[i], s[pii])) <= 0)
{
strcpy(swap, s[pii]);
strcpy(s[pii], s[i]);
strcpy(s[i], swap);
pii++;
}
}
strcpy(swap, str[e]);
strcpy(str[e], str[pii]);
strcpy(str[pii], swap);
}
};
main()
{
ss s;
cout << "Enter the strings\n";
s.get_str();
s.disp();
s.sort();
cout << "after the sort" << endl;
s.disp();
}

I found several problems with your code:
Arguments are passed to qs() and part() as char *&, not char ** or char [max][10].
s is undefined in qs() (did you mean str?).
ISO C++ forbids a definition of main() without a return value.
part() has a non-void return type and doesn't return a value.
Repaired code is shown below:
#include <iostream>
#include <cstring>
using namespace std;
#define max 5
class ss {
private:
char str[max][10];
public:
void get_str() {
for (int i = 0; i < max; i++)
cin >> str[i];
}
void disp() {
cout << "Entered strings are\n";
for (int i = 0; i < max; i++) {
if (strcmp(str[i], str[i + 1]) != 0)
cout << str[i] << endl;
}
}
void sort()
{
char temp[max];
for (int i = 0; i < max - 1; i++)
for (int j = 0; j < (max - i - 1); j++)
{
if (strcmp(str[j], str[j + 1])>0)
{
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
disp();
}
void qsort()
{
qs(reinterpret_cast<char **>(str), 0, max - 1);
disp();
}
void qs(char **str, int st, int e)
{
int pi = part(reinterpret_cast<char **>(str), st, e);
qs(str, st, pi - 1);
qs(str, pi + 1, e);
}
int part(char **s, int st, int e)
{
char pi[max], swap[max];
strcpy(pi, s[e]);
int pii = st;
int i = st;
for (; i < e; i++) {
if ((strcmp(s[i], s[pii])) <= 0)
{
strcpy(swap, s[pii]);
strcpy(s[pii], s[i]);
strcpy(s[i], swap);
pii++;
}
}
strcpy(swap, str[e]);
strcpy(str[e], str[pii]);
strcpy(str[pii], swap);
// NO RETURN VALUE?
return 0;
}
};
int main()
{
ss s;
cout << "Enter the strings\n";
s.get_str();
s.disp();
s.sort();
cout << "after the sort" << endl;
s.disp();
return 0;
}
Or, if you don't want to use reinterpret_cast<>(), you can use this:
...
void qsort()
{
qs(str, 0, max - 1);
disp();
}
void qs(char str[max][10], int st, int e)
{
int pi = part(str, st, e);
qs(str, st, pi - 1);
qs(str, pi + 1, e);
}
int part(char s[max][10], int st, int e)
...

Related

'this' cannot be used in a constant expression error

The error is on line 76 int res[mSize]; the problem is on mSize. It seems like a simple fix but I can't figure it out. If someone can figure it out or point me in the right direction that would be greatly appreciated.
Also, the deconstructor ~MyContainer(), I am not sure if I am using it right or if there is a correct place to put it.
Here is my code:
#include <iostream>
using namespace std;
class MyContainer
{
private:
int* mHead; // head of the member array
int mSize; // size of the member array
public:
MyContainer();
MyContainer(int*, int);
//~MyContainer();
void Add(int);
void Delete(int);
int GetSize();
void DisplayAll();
int FindMissing();
~MyContainer() {}
};
MyContainer::MyContainer()
{
mHead = NULL;
mSize = 0;
}
MyContainer::MyContainer(int* a, int b)
{
mHead = a;
mSize = b;
}
void MyContainer::Add(int a)
{
*(mHead + mSize) = a;
mSize++;
}
void MyContainer::Delete(int a)
{
int index;
for (int i = 0; i < mSize; i++)
{
if (*(mHead + i) == a)
{
index = i;
break;
}
}
for (int i = index; i < mSize; i++)
{
*(mHead + i) = *(mHead + i + 1);
}
mSize--;
}
int MyContainer::GetSize()
{
return mSize;
}
void MyContainer::DisplayAll()
{
cout << "\n";
for (int i = 0; i < mSize; i++)
{
cout << *(mHead + i) << " ";
}
}
int MyContainer::FindMissing()
{
int res[mSize];
int temp;
int flag = 0;
for (int i = 1; i <= mSize; i++)
{
flag = 0;
for (int j = 0; j < mSize; j++)
{
if (*(mHead + j) == i)
{
flag = 1;
break;
}
}
if (flag == 0)
{
temp = i;
break;
}
}
return temp;
}
int main()
{
const int cSize = 5;
int lArray[cSize] = { 2, 3, 7, 6, 8 };
MyContainer lContainer(lArray, cSize);
lContainer.DisplayAll();
lContainer.Delete(7);
lContainer.DisplayAll();
cout << "Size now is: " << lContainer.GetSize() << endl; lContainer.Add(-1);
lContainer.Add(-10);
lContainer.Add(15);
lContainer.DisplayAll();
cout << "Size now is: " << lContainer.GetSize() << endl;
cout << "First missing positive is: " << lContainer.FindMissing() << endl;
system("PAUSE"); return 0;
}
int res[mSize];
The size of the array mSize must be known at compile time. You cannot use a variable here. An option may be to define a macro with an largish value that will not exceeded.
static const int kLargeSize =100;
int res[kLargeSize];
Edited in response to the comments - const and constexpr are a better option than a macro.
Or even better, you can use std::vector - https://en.cppreference.com/w/cpp/container/vector

Program gives a weird runtime error

#include<iostream>
using namespace std;
class darray
{
private:
int n; // size of the array
int *a; // pointer to the 1st element
public:
darray(int size)
{
n = size;
a = new int[n];
}
~darray(){ delete[] a; }
void get_input();
int get_element(int index);
void set_element(int index, int value);
int count(){ return n; }
void print();
};
void darray::get_input()
{
for (int i = 0; i < n; i++)
{
cin >> *(a + i);
}
}
int darray::get_element(int index)
{
if (index == -1)
index = n - 1;
return a[index];
}
void darray::set_element(int index,int value)
{
a[index] = value;
}
void darray::print()
{
for (int i = 0; i < n; i++)
{
cout << a[i];
if (i < (n - 1))
cout << " ";
}
cout << endl;
}
// perform insertion sort on the array a
void insertion_sort(darray d)
{
int v = d.get_element(-1); // v is the right-most element
int e = d.count() - 1; // pos of the empty cell
// shift values greater than v to the empty cell
for (int i = (d.count() - 2); i >= 0; i--)
{
if (d.get_element(i) > v)
{
d.set_element(e,d.get_element(i));
d.print();
e = i;
}
else
{
d.set_element(e, v);
d.print();
break;
}
}
}
int main()
{
int s;
cin >> s;
darray d(s);
d.get_input();
insertion_sort(d);
system("pause");
return 0;
}
I use the darray class to make a array of size n at runtime. This class gives basic functions to handle this array.
This programs says debugging assertion failed at the end.
It gives this error after ruining the program.Other than that the program works fine. What is the reason for this error ?
You need to declare and define a copy constructor:
darray::darray(const darray& src)
{
n = src.n;
a = new int[n];
for (int i = 0; i < n; i++)
{
*(a + i) = *(src.a + i);
}
}

Why is my code in C++ so much slower than my code in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So far, I wrote my code in C (performance is of utmost importance). However, I would like to start writing my algorithms in a generic way. So, I decided to try out C++. I took a simple code in C and translated it into C++ with templates. To my disappointment, the C++ code runs 2.5 times slower. (the C code is compiled with gcc -O3; the C++ code is compiled with g++ -O3)
Am I doing something wrong in C++? Why is there such a performance hit?
Here is the C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
static int df_output = 0;
int nCalls = 0;
typedef struct {
int *pancakes;
int n;
} STATE;
STATE **solution;
void shuffle(STATE *s) {
int i;
for (i = 0; i < s->n; i++) {
int i1 = rand() % s->n;
int i2 = rand() % s->n;
int temp = s->pancakes[i1];
s->pancakes[i1] = s->pancakes[i2];
s->pancakes[i2] = temp;
}
}
STATE *copyState(STATE *s) {
STATE *res = malloc(sizeof(STATE));
res->n = s->n;
res->pancakes = (int *)malloc(res->n * sizeof(int));
memcpy(res->pancakes, s->pancakes, res->n * sizeof(int));
return res;
}
// reverse n pancakes
void makeMove(STATE *s, int n) {
int i;
for (i = 0; i < n/2; i++) {
int temp = s->pancakes[i];
s->pancakes[i] = s->pancakes[n - 1 - i];
s->pancakes[n - 1 - i]=temp;
}
}
void printState(STATE *s) {
int i;
printf("[");
for (i = 0; i < s->n; i++) {
printf("%d", s->pancakes[i]);
if (i < s->n - 1)
printf(", ");
}
printf("]");
}
int heuristic(STATE *s) {
int i, res = 0;
nCalls++;
for (i = 1; i < s->n; i++)
if (abs(s->pancakes[i]-s->pancakes[i-1])>1)
res++;
if (s->pancakes[0] != 0) res++;
return res;
}
void tabs(int g) {
int i;
for (i = 0; i < g; i++) printf("\t");
}
int df(STATE *s, int g, int left) {
int h = heuristic(s), i;
if (g == 0) printf("Thereshold: %d\n", left);
if (df_output) {
tabs(g);
printf("g=%d,left=%d ", g, left); printState(s); printf("\n");}
if (h == 0) {
assert(left == 0);
solution = (STATE **)malloc((g+1) * sizeof(STATE *));
solution[g] = copyState(s);
return 1;
}
if (left == 0)
return 0;
for (i = 2; i <= s->n; i++) {
makeMove(s, i);
if (df(s, g+1, left-1)) {
makeMove(s, i);
solution[g] = copyState(s);
return 1;
}
makeMove(s, i);
}
return 0;
}
void ida(STATE *s) {
int threshold = 0, i;
while (!df(s, 0, threshold)) threshold++;
for (i = 0; i <= threshold; i++) {
printf("%d. ", i);
printState(solution[i]);
printf("\n");
//if (i < threshold - 1) printf("->");
}
}
int main(int argc, char **argv) {
STATE *s = (STATE *)malloc(sizeof(STATE));
int i, n;
int myInstance[] = {0,5,4,7,2,6,1,3};
s->n = 8;
s->pancakes = myInstance;
printState(s); printf("\n");
ida(s);
printf("%d calls to heuristic()", nCalls);
return 0;
}
Here is the C++ code:
#include <iostream>
#include "stdlib.h"
#include "string.h"
#include "assert.h"
using namespace std;
static int df_output = 0;
int nCalls = 0;
class PancakeState {
public:
int *pancakes;
int n;
PancakeState *copyState();
void printState();
};
PancakeState *PancakeState::copyState() {
PancakeState *res = new PancakeState();
res->n = this->n;
res->pancakes = (int *)malloc(this->n * sizeof(int));
memcpy(res->pancakes, this->pancakes,
this->n * sizeof(int));
return res;
}
void PancakeState::printState() {
int i;
cout << "[";
for (i = 0; i < this->n; i++) {
cout << this->pancakes[i];
if (i < this->n - 1)
cout << ", ";
}
cout << "]";
}
class PancakeMove {
public:
PancakeMove(int n) {this->n = n;}
int n;
};
class Pancake {
public:
int heuristic (PancakeState &);
int bf(PancakeState &);
PancakeMove *getMove(int);
void makeMove(PancakeState &, PancakeMove &);
void unmakeMove(PancakeState &, PancakeMove &);
};
int Pancake::bf(PancakeState &s) {
return s.n - 1;
}
PancakeMove *Pancake::getMove(int i) {
return new PancakeMove(i + 2);
}
// reverse n pancakes
void Pancake::makeMove(PancakeState &s, PancakeMove &m) {
int i;
int n = m.n;
for (i = 0; i < n/2; i++) {
int temp = s.pancakes[i];
s.pancakes[i] = s.pancakes[n - 1 - i];
s.pancakes[n - 1 - i]=temp;
}
}
void Pancake::unmakeMove(PancakeState &state, PancakeMove &move) {
makeMove(state, move);
}
int Pancake::heuristic(PancakeState &s) {
int i, res = 0;
nCalls++;
for (i = 1; i < s.n; i++)
if (abs(s.pancakes[i]-s.pancakes[i-1])>1)
res++;
if (s.pancakes[0] != 0) res++;
return res;
}
void tabs(int g) {
int i;
for (i = 0; i < g; i++) cout << "\t";
}
template <class Domain, class State, class Move>
class Alg {
public:
State **solution;
int threshold;
bool verbose;
int df(Domain &d, State &s, int g);
void ida(Domain &d, State &s);
};
template <class Domain, class State, class Move>
int Alg<Domain, State, Move>::df(Domain &d, State &s, int g) {
int h = d.heuristic(s), i;
if (g == 0)
cout << "Thereshold:" << this->threshold << "\n";
if (this->verbose) {
tabs(g);
cout << "g=" << g;
s.printState(); cout << "\n";
}
if (h == 0) {
solution = (State **)malloc((g+1) * sizeof(State *));
solution[g] = s.copyState();
return 1;
}
if (g == this->threshold)
return 0;
for (i = 0; i < d.bf(s); i++) {
Move *move = d.getMove(i);
d.makeMove(s, *move);
if (this->df(d, s, g+1)) {
d.unmakeMove(s, *move);
solution[g] = s.copyState();
delete move;
return 1;
}
d.unmakeMove(s, *move);
delete move;
}
return 0;
}
template <class Domain, class State, class Move>
void Alg<Domain, State, Move>::ida(Domain &d, State &s) {
int i;
this->threshold = 0;
while (!this->df(d, s, 0)) threshold++;
for (i = 0; i <= threshold; i++) {
cout << i << ".";
this->solution[i]->printState();
cout << "\n";
//if (i < threshold - 1) printf("->");
}
}
int main(int argc, char **argv) {
Pancake *d = new Pancake();
PancakeState *s = new PancakeState();
int myInstance[] = {0,5,4,7,2,6,1,3};
s->pancakes = myInstance;
s->n = 8;
s->printState(); cout << "\n";
Alg<Pancake, PancakeState, PancakeMove> *alg = new Alg<Pancake, PancakeState, PancakeMove>();
//alg->verbose = true;
alg->ida(*d, *s);
cout << nCalls < "calls to heuristic()";
delete alg;
return 0;
}
You have a lot of malloc() and operator new calls in there. Stop doing that, and performance will improve. And don't use malloc() in C++, use operator new always.
For example, PancakeMove is a small, trivial struct. But you allocate instances of it dynamically, which is slow. Just pass it around by value.
Basically, you are allocating a lot of small things on the heap instead of on the stack. That's pretty "expensive", so will take extra time.
This code (which is modified from your original code) runs within 1ms of the C code:
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
using namespace std;
static int df_output = 0;
int nCalls = 0;
class PancakeState {
public:
PancakeState(int n) : n(n), pancakes(n)
{
}
PancakeState(int n, int *v) : n(n), pancakes(n)
{
for(int i = 0; i < n; i++)
pancakes[i] = v[i];
}
PancakeState(): n(0) {}
public:
vector<int> pancakes;
int n;
PancakeState *copyState();
void printState();
};
void PancakeState::printState() {
int i;
cout << "[";
for (i = 0; i < this->n; i++) {
cout << this->pancakes[i];
if (i < this->n - 1)
cout << ", ";
}
cout << "]";
}
class PancakeMove {
public:
PancakeMove(int n) : n(n) {}
int n;
};
class Pancake {
public:
int heuristic (PancakeState &);
int bf(PancakeState&);
PancakeMove getMove(int);
void makeMove(PancakeState &, PancakeMove &);
void unmakeMove(PancakeState &, PancakeMove &);
};
int Pancake::bf(PancakeState& s) {
return s.n - 1;
}
PancakeMove Pancake::getMove(int i) {
return PancakeMove(i + 2);
}
// reverse n pancakes
void Pancake::makeMove(PancakeState &s, PancakeMove &m) {
int i;
int n = m.n;
for (i = 0; i < n/2; i++) {
int temp = s.pancakes[i];
s.pancakes[i] = s.pancakes[n - 1 - i];
s.pancakes[n - 1 - i]=temp;
}
}
void Pancake::unmakeMove(PancakeState &state, PancakeMove &move) {
makeMove(state, move);
}
int Pancake::heuristic(PancakeState &s) {
int i, res = 0;
nCalls++;
for (i = 1; i < s.n; i++)
if (abs(s.pancakes[i]-s.pancakes[i-1])>1)
res++;
if (s.pancakes[0] != 0) res++;
return res;
}
void tabs(int g) {
int i;
for (i = 0; i < g; i++) cout << "\t";
}
template <class Domain, class State, class Move>
class Alg {
public:
vector<State> solution;
int threshold;
bool verbose;
int df(Domain &d, State &s, int g);
void ida(Domain &d, State &s);
};
template <class Domain, class State, class Move>
int Alg<Domain, State, Move>::df(Domain &d, State &s, int g) {
int h = d.heuristic(s), i;
if (g == 0)
cout << "Thereshold:" << threshold << "\n";
if (this->verbose) {
tabs(g);
cout << "g=" << g;
s.printState(); cout << "\n";
}
if (h == 0) {
solution.resize(g+1);
solution[g] = s;
return 1;
}
if (g == this->threshold)
return 0;
for (i = 0; i < d.bf(s); i++) {
Move move = d.getMove(i);
d.makeMove(s, move);
if (this->df(d, s, g+1)) {
d.unmakeMove(s, move);
solution[g] = s;
return 1;
}
d.unmakeMove(s, move);
}
return 0;
}
template <class Domain, class State, class Move>
void Alg<Domain, State, Move>::ida(Domain &d, State &s) {
int i;
this->threshold = 0;
while (!this->df(d, s, 0)) threshold++;
for (i = 0; i <= threshold; i++) {
cout << i << ".";
solution[i].printState();
cout << "\n";
//if (i < threshold - 1) printf("->");
}
}
int main(int argc, char **argv) {
Pancake d = Pancake();
int myInstance[] = {0,5,4,7,2,6,1,3};
PancakeState s(8, myInstance);
s.printState(); cout << "\n";
Alg<Pancake, PancakeState, PancakeMove> *alg = new Alg<Pancake, PancakeState, PancakeMove>();
//alg->verbose = true;
alg->ida(d, s);
cout << nCalls < "calls to heuristic()";
delete alg;
return 0;
}
As an extra benefit of not making so many direct allocations, it also doesn't leak 22 lumps of memory throughout the execution, which is quite a useful feature.
(If you want to see what changed, here's a diff - ignoring whitespace only changes):
--- pcake.orig.cpp 2014-04-13 15:43:24.861417827 +0100
+++ pcake.cpp 2014-04-13 15:42:25.145165372 +0100
## -1,7 +1,9 ##
#include <iostream>
-#include "stdlib.h"
-#include "string.h"
-#include "assert.h"
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <vector>
+
using namespace std;
static int df_output = 0;
## -9,21 +11,22 ##
class PancakeState {
public:
- int *pancakes;
+ PancakeState(int n) : n(n), pancakes(n)
+ {
+ }
+ PancakeState(int n, int *v) : n(n), pancakes(n)
+ {
+ for(int i = 0; i < n; i++)
+ pancakes[i] = v[i];
+ }
+ PancakeState(): n(0) {}
+public:
+ vector<int> pancakes;
int n;
PancakeState *copyState();
void printState();
};
-PancakeState *PancakeState::copyState() {
- PancakeState *res = new PancakeState();
- res->n = this->n;
- res->pancakes = (int *)malloc(this->n * sizeof(int));
- memcpy(res->pancakes, this->pancakes,
- this->n * sizeof(int));
- return res;
-}
-
void PancakeState::printState() {
int i;
cout << "[";
## -37,25 +40,25 ##
class PancakeMove {
public:
- PancakeMove(int n) {this->n = n;}
+ PancakeMove(int n) : n(n) {}
int n;
};
class Pancake {
public:
int heuristic (PancakeState &);
- int bf(PancakeState &);
- PancakeMove *getMove(int);
+ int bf(PancakeState&);
+ PancakeMove getMove(int);
void makeMove(PancakeState &, PancakeMove &);
void unmakeMove(PancakeState &, PancakeMove &);
};
-int Pancake::bf(PancakeState &s) {
+int Pancake::bf(PancakeState& s) {
return s.n - 1;
}
-PancakeMove *Pancake::getMove(int i) {
- return new PancakeMove(i + 2);
+PancakeMove Pancake::getMove(int i) {
+ return PancakeMove(i + 2);
}
// reverse n pancakes
## -91,7 +94,7 ##
template <class Domain, class State, class Move>
class Alg {
public:
- State **solution;
+ vector<State> solution;
int threshold;
bool verbose;
int df(Domain &d, State &s, int g);
## -102,30 +105,28 ##
int Alg<Domain, State, Move>::df(Domain &d, State &s, int g) {
int h = d.heuristic(s), i;
if (g == 0)
- cout << "Thereshold:" << this->threshold << "\n";
+ cout << "Thereshold:" << threshold << "\n";
if (this->verbose) {
tabs(g);
cout << "g=" << g;
s.printState(); cout << "\n";
}
if (h == 0) {
- solution = (State **)malloc((g+1) * sizeof(State *));
- solution[g] = s.copyState();
+ solution.resize(g+1);
+ solution[g] = s;
return 1;
}
if (g == this->threshold)
return 0;
for (i = 0; i < d.bf(s); i++) {
- Move *move = d.getMove(i);
- d.makeMove(s, *move);
+ Move move = d.getMove(i);
+ d.makeMove(s, move);
if (this->df(d, s, g+1)) {
- d.unmakeMove(s, *move);
- solution[g] = s.copyState();
- delete move;
+ d.unmakeMove(s, move);
+ solution[g] = s;
return 1;
}
- d.unmakeMove(s, *move);
- delete move;
+ d.unmakeMove(s, move);
}
return 0;
}
## -138,23 +139,22 ##
for (i = 0; i <= threshold; i++) {
cout << i << ".";
- this->solution[i]->printState();
+ solution[i].printState();
cout << "\n";
//if (i < threshold - 1) printf("->");
}
}
int main(int argc, char **argv) {
- Pancake *d = new Pancake();
- PancakeState *s = new PancakeState();
+ Pancake d = Pancake();
int myInstance[] = {0,5,4,7,2,6,1,3};
- s->pancakes = myInstance;
- s->n = 8;
- s->printState(); cout << "\n";
+ PancakeState s(8, myInstance);
+ s.printState(); cout << "\n";
Alg<Pancake, PancakeState, PancakeMove> *alg = new Alg<Pancake, PancakeState, PancakeMove>();
//alg->verbose = true;
- alg->ida(*d, *s);
+ alg->ida(d, s);
cout << nCalls < "calls to heuristic()";
delete alg;
return 0;
}
+

Quicksort for string array

After looking through articles, tutorials and solutions everywhere, i haven't come across anything that explains how to use quicksort for string arrays. All examples I found are of either "int" or "char".
This is my edited code.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int count;
template <class T>
void printArray(T ar[], int sz);
template <class T>
void bubbleSort(T ar[], int sz);
void quickSortMain(string items[], int ct);
void quickSort(string items[], int left, int right);
//////////////////////////////////////////////////////////////////////////
// Main Function Implementation
//////////////////////////////////////////////////////////////////////////
int main() {
int numOfData = 50000;
string line, temp;
ofstream resultFile;
ofstream tableFile;
double data[100][2];
string patient[numOfData];
ifstream dataFile("shufflePatient.txt");
int i;
int SIZE = 0;
cout << "Program to shuffle data" << endl << endl;
cout << "This program will calculate swapping processes and running time.";
/*Storing data*/
cout << "Reading data in process.." << endl;
if (dataFile.is_open()) {
i=-1;
while (dataFile.good()) {
getline (dataFile, line);
if (i>=0) patient[i] = line;
i++;
}
dataFile.close();
}
SIZE = 5;
quickSortMain(patient, 5);
/*Writing to file*/
cout << "Writing to file.." << endl;
resultFile.open ("test.txt");
for (int i=0 ; i<numOfData ; i++) {
resultFile << patient[i] << "\n";
}
resultFile.close();
system("pause");
return 0;
}
void quickSortMain(string items[], int ct)
{
quickSort(items, 0, ct-1);
}
void quickSort(string items[], int left, int right)
{
int i, j;
char *x;
string temp[10];
i = left;
j = right;
x = items[(left+right)/2];
do {
while((strcmp(items[i],x) < 0) && (i < right)) {
i++;
}
while((strcmp(items[j],x) > 0) && (j > left)) {
j--;
}
if(i <= j) {
strcpy(temp, items[i]);
strcpy(items[i], items[j]);
strcpy(items[j], temp);
i++;
j--;
}
} while(i <= j);
if(left < j) {
quickSort(items, left, j);
}
if(i < right) {
quickSort(items, i, right);
}
}
//----------------------------------------------------------------------------
// prints array of size size
//----------------------------------------------------------------------------
template <class T>
void printArray(T patient[], int size)
{
for(int i = 0; i < size; i++)
cout << patient[i] << " ";
cout << endl;
}
//----------------------------------------------------------------------------
// sorts array of size size by Bubble Sort method
//----------------------------------------------------------------------------
template <class T>
void bubbleSort(T patient[], int size) //returning an int
{
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return ;
}
}
The error i got was in this line:
x = items[(left+right)/2];
I changed
char x*; to string x;
I don't know if that was correct. Now the error im getting is that strcmp and strcpy are not declared. Any help on what i should do next?
string patient[numOfData];
vs.
template <class T>
void quickSortMain(char items[][10], int ct)
vs.
quickSortMain(patient, 5);
quickSortMain expects an array of char[10], not string[]. Not only this, but it also depends on a template parameter. Drop the template <class T> and replace char[][10] with string[].

quicksort string array help c++

This is my code. I don't know how to get the code to run. Im having problems with quicksorting for string.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int count;
template <class T>
void printArray(T ar[], int sz);
template <class T>
void bubbleSort(T ar[], int sz);
void quickSortMain(string items[], int ct);
void quickSort(string items[], int left, int right);
//////////////////////////////////////////////////////////////////////////
// Main Function Implementation
//////////////////////////////////////////////////////////////////////////
int main() {
int numOfData = 50000;
string line, temp;
ofstream resultFile;
ofstream tableFile;
double data[100][2];
string patient[numOfData];
ifstream dataFile("shufflePatient.txt");
int i;
int SIZE = 0;
cout << "Program to shuffle data" << endl << endl;
cout << "This program will calculate swapping processes and running time.";
/*Storing data*/
cout << "Reading data in process.." << endl;
if (dataFile.is_open()) {
i=-1;
while (dataFile.good()) {
getline (dataFile, line);
if (i>=0) patient[i] = line;
i++;
}
dataFile.close();
}
SIZE = 5;
quickSortMain(patient, 5);
/*Writing to file*/
cout << "Writing to file.." << endl;
resultFile.open ("test.txt");
for (int i=0 ; i<numOfData ; i++) {
resultFile << patient[i] << "\n";
}
resultFile.close();
system("pause");
return 0;
}
void quickSortMain(string items[], int ct)
{
quickSort(items, 0, ct-1);
}
void quickSort(string items[], int left, int right)
{
int i, j;
char *x;
string temp[10];
i = left;
j = right;
x = items[(left+right)/2];
do {
while((strcmp(items[i],x) < 0) && (i < right)) {
i++;
}
while((strcmp(items[j],x) > 0) && (j > left)) {
j--;
}
if(i <= j) {
strcpy(temp, items[i]);
strcpy(items[i], items[j]);
strcpy(items[j], temp);
i++;
j--;
}
} while(i <= j);
if(left < j) {
quickSort(items, left, j);
}
if(i < right) {
quickSort(items, i, right);
}
}
//----------------------------------------------------------------------------
// prints array of size size
//----------------------------------------------------------------------------
template <class T>
void printArray(T patient[], int size)
{
for(int i = 0; i < size; i++)
cout << patient[i] << " ";
cout << endl;
}
//----------------------------------------------------------------------------
// sorts array of size size by Bubble Sort method
//----------------------------------------------------------------------------
template <class T>
void bubbleSort(T patient[], int size) //returning an int
{
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return ;
}
}
The error i got was in this line:
x = items[(left+right)/2];
I changed
char x*; to string x;
I don't know if that was correct. Now the error im getting is that strcmp and strcpy are not declared. Any help on what i should do next?
That's correct, now change
strcmp(items[i],x) < 0
to
items[i] < x
and
strcmp(items[j],x) > 0
to
items[j] > x
and
strcpy(temp, items[i]);
to
temp = items[i];
etc.
But really this is a case of RTFM. If you're competent enough to write a quicksort routine you should be competent enough to look up how std::string works. Being able to access reference information is a very important skill for a programmer.