Реализация C ++ Deque с массивами символов

Итак, я пишу программу, которая принимает строку символов в выражении командной строки и разбивает слово на две или три части (2 для четного, первая половина и вторая половина, 3 для нечетного, первая «половина», средняя буква и вторая «половина», и переворачивает символы первой и второй половин и повторно объединяет символы в одну строку, выводится htat. Это становится немного страшнее, так как я должен использовать deque и использовать push и поп-функции для перемещения по символам. Так что у меня есть несколько проблем, которые я не совсем понимаю. Во-первых, целое число ABottom по какой-то причине взорвалось до невероятно больших значений, что не имеет смысла, так как предполагается, что оно остается фиксированным в 0. Во-вторых, когда я извлекаю из A, я получаю пустую строку, и когда я извлекаю из B, он чередует все остальные символы из deque.Но кажется, что циклы в файле .h, которые помещают символы в deque, работать точно так, как я ожидал. Любые предложения о ABottom, или почему попсы не работают г?

Файл 1:

// Kevin Shaffer TwoStackKAS.h

#include<iostream>
#include<string>
#include<vector>

#ifndef TWOSTACKKAS_H_
#define TWOSTACKKAS_H_

using namespace std;

class TwoStacks {
char elements[];
int Abottom, Bbottom;
int AtopSpace, BtopSpace;
int totalSize;

public:
TwoStacks(int maxAdds) {
totalSize = 2*maxAdds +1;
char elements[totalSize];
const int Bbottom = totalSize-1; //bottom for both stacks!
const int Abottom = 0;
AtopSpace= 0;
BtopSpace = totalSize-1; //top for both stacks!
cout<<"Stack Size: "<<totalSize<<endl;
}virtual bool empty() const {
return Abottom == AtopSpace && Bbottom==BtopSpace;
}

virtual bool full() const { return AtopSpace==BtopSpace;}
virtual int stackSize() {
cout<<Abottom<<" Abottom"<<endl;
return (AtopSpace - Abottom +Bbottom -BtopSpace);
}

virtual char popA() {
if (empty()){
cerr << "Attempting to pop Empty stack!"<< endl;
return ' ';    //prepare EmptyQexceptiin
} else {
cout << elements[--AtopSpace] << " testpopA"<< endl;
return elements[--AtopSpace];
}
}

virtual char popB() {
if (empty()){    //later EmptyQException
cerr <<"Attempting to pop an empty stack!" << endl;
return ' ';
} else {
//cout <<elements->at(++BtopSpace) << endl;
cout << elements[++BtopSpace] << " test"<< endl;
return elements[++BtopSpace];

}
}

virtual void pushB(char newItem){
elements[BtopSpace--] = newItem;
}

virtual void pushA(char newItem){
elements[AtopSpace++] = newItem;
}

virtual string toString() const {
string out = "";
for (int i = 0 ; i<=Bbottom; i++) {
out += elements[i];}
return out;
}
};

#endif

И файл 2:

/** Kevin Shaffer
* Given an input string, reverse each half of the string;
* pivot on the middle element if it exists.
* uses double ended stack in twoStackKAS.h*/#include<string>
#include "TwoStackKAS.h"#include<iostream>
#include<string>

using namespace std;
int main (int argc, char* argv[]){
if (argc<=1){return 0;}
string word = argv[1];
int length = word.size();                   // gets length of word
int half = length/2;
TwoStacks* sd = new TwoStacks(length/2);
//cout<<sd->stackSize()<<endl;
for(int i = 0; i < length/2; i++){
sd->pushA(word[i]);
cout << word[i] << endl;
}

for(int i = length; i >= length/2; i--){   //Second half of word
sd->pushB(word[i] );     //has been pushed
cout << word[i] << endl; //in reverse order.
}
//cout << word << endl;

//Recombine word
if(length%2==1){ word = word[length/2];}
else{ word = "";}
cout<<sd->stackSize()<<endl;
string leftHalf; string rightHalf;
string myWord; //new word (shuffled)
for(int i=0; i< half; i++) {
leftHalf +=  sd->popA();
rightHalf += sd->popB();
}
//cout<<"Stack: "<<sd->toString()<<endl;
cout << rightHalf << endl;
cout << leftHalf << endl;
myWord = leftHalf + word + rightHalf;
cout<<myWord<<endl;
return 0;
}

0

Решение

ABottom не растет … он никогда не инициализируется!
Посмотри на своего конструктора. Вы не назначаете Abottom, но вы определяете новую переменную, которая маскирует переменную-член. Вы делаете это несколько раз.

А так же VS2015 на самом деле не принимал char elements[]; : «Неполный тип не допускается», вероятно, лучше использовать std :: string вместо char *

Лучший конструктор будет что-то вроде.

class TwoStacks
{
private:
// totalSize has to be assigned before assigning dependent variables
int totalSize;
string elements;
int Abottom, Bbottom;
int AtopSpace, BtopSpace;

public:
TwoStacks(int maxAdds)
: totalSize(2 * maxAdds + 1)
, elements(totalSize, ' ')
, Abottom(0)
, Bbottom(totalSize - 1)
, AtopSpace(0)
, BtopSpace(totalSize - 1)
{
// preferably don't cout in a constructor
cout << "Stack Size: " << totalSize << endl;
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector