下面是我的 .cpp 文件和 .h 文件。在从 Mike 那里得到了很多帮助之后,我终于让它工作了;但是,当我在 Visual Studio 2012 上编译它时,它在“for (int i = 0; i < s.length(); i++)” 行上给了我 2 个关于 '<' 有符号/无符号不匹配的警告。谁能告诉我我在那里做错了什么?
[code]
#include"DownwardStack.h"
#include<iostream>
#include<string>
#include<memory>
#include<cassert>
using namespace std;
unique_ptr<string> reverse_string(string const &s);
int main()
{
int count = 0;
string s;
unique_ptr<string> reverse(new string());
unique_ptr<DownwardStack<int>> ptr(new DownwardStack<int>());
cout << "Your string: ";
cin >> s;
reverse = reverse_string(s);
cout << "Your reverse string is: " << *reverse << endl;
if(ptr->IsEmpty())
cout << "ptr is empty" << endl;
else
cout << "ptr is not empty" << endl;
assert(ptr->IsEmpty());
assert(!ptr->IsFull());
ptr->Push(5);
ptr->Push(7);
ptr->Push(10);
ptr->Push(15);
ptr->Push(4);
cout << "Stack size: " << ptr->GetSize() << endl;
cout << "Top element: " << ptr->Peek() << endl;
cout << "Pop one element out." << endl;
ptr->Pop();
cout << "Top element: " << ptr->Peek() << endl;
return 0;
}
unique_ptr<string> reverse_string(string const &s)
{
DownwardStack<char> stack;
cout << s.length() << endl;
// Here it gives me a warning on the for loop
for (int i = 0; i < s.length(); i++)
{
stack.Push(s[i]);
}
unique_ptr<string> result(new string);
// Again it gives me a warning on the for loop
for(int i = 0; i < s.length(); i++)
{
*result += stack.Peek();
stack.Pop();
}
return result;
}
[/code]
这是我的头文件.h
[code]
#pragma once
#include<cassert>
#include<stack>
#include<string>
// size: number of elements inside the array
const int FIXED_ARRAYED_STACK_CAPACITY = 100;
template<class T>
class DownwardStack
{
public:
DownwardStack();
~DownwardStack();
// 1 step
// O(0)
int GetSize() const {return size;}
bool IsEmpty() const {return (size==0);}
bool IsFull() const {return (size==FIXED_ARRAYED_STACK_CAPACITY);}
T Peek();
void Pop();
void Push(T val);
void Clear();
void DisplayStack();
private:
int size;
T elements[FIXED_ARRAYED_STACK_CAPACITY];
};
// O(1)
template<class T>
DownwardStack<T>::DownwardStack()
{
size = 0;
}
template<class T>
DownwardStack<T>::~DownwardStack()
{
}
// assert = 1 step
// IsEmpty() = 1 step
// total = 2 steps
// f(n) = 2
// O(1)
template<class T>
T DownwardStack<T>::Peek()
{
assert(!IsEmpty());
return elements[FIXED_ARRAYED_STACK_CAPACITY - size];
}
// In order to take something out, it must not be empty
// assert = 1 step
// IsEmpty() = 1 step
// size-- = 1 step
// total = 3 steps
// O(1)
template<class T>
void DownwardStack<T>::Pop()
{
assert(!IsEmpty());
size--;
}
// In order to put in something, the stack must not be full
// assert = 1 step
// IsFull = 1 step
// assignment = 1 step
// size++ = 1 step
// total = 4 steps
// O(1)
template<class T>
void DownwardStack<T>::Push(T val)
{
assert(!IsFull());
elements[FIXED_ARRAYED_STACK_CAPACITY - size - 1] = val;
size++;
}
template<class T>
void DownwardStack<T>::Clear()
{
size = FIXED_ARRAYED_STACK_CAPACITY;
assert(IsEmpty());
}
[/code]