C++中基于对象的编程风格的学习,非常有难度,概念很抽象,操作起来也比较费脑子,这里主要把一些知识点和习题给过一遍!
一、前言
C++中基于对象的编程风格的学习(Essential C++ 第四章)。
二、例题
-P227 练习 4.1
建立stack.h和stack.suffix,此处的suffix是你的编译器所能接受的扩展名,或是你的项目所使用的扩展名。编写main()函数,练习操作stack的所有公开接口,并加以编译执行。程序代码文件和main()都必须包含 stack.h:
#include “Stack.h”
-P229 练习 4.2
扩展stack的功能,以支持find()和count()两个操作。find()会查看某值是否存在而返回true或false。count()返回某字符串的出现次数。重新实现练习4.1的main(),让它调用这两个函数。
-
两个练习就合在一起了!
-
Stack.h
#pragma once
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Stack
{
public:
bool push(const string&);
bool pop(string &elem);
bool peek(string &elem);
bool empty() const { return _stack.empty(); };
bool full() const { return _stack.size() == _stack.max_size(); };
int size() const { return _stack.size(); };
bool find(const string& elem) const;
int count(const string& elem) const;
private:
vector<string> _stack;
};
- Stack.cpp
#include "Stack.h"
bool Stack::push(const string& elem)
{
if(full()) return false;
_stack.push_back(elem);
return true;
}
bool Stack::pop(string& elem)
{
if(empty()) return false;
// 返回尾部元素
elem = _stack.back();
_stack.pop_back();
return true;
}
// 查看功能
bool Stack::peek(string& elem)
{
if(empty()) return false;
// 返回尾部元素
elem = _stack.back();
return true;
}
// 用泛型算法
bool Stack::find(const string& elem) const
{
vector<string>::const_iterator end_it = _stack.end();
return ::find(_stack.begin(), _stack.end(), elem) != end_it;
}
int Stack::count(const string& elem) const
{
return ::count(_stack.begin(), _stack.end(), elem);
}
- 源.cpp
#include "Stack.h"
#include <iostream>
int main() {
Stack st;
string str;
// full() 函数
// 这个输入循环的退出 需要在输入完后,回车,再点击 ctrl+z ,再回车
while (cin >> str && !st.full())
{
// push() 函数
st.push(str);
}
if (st.empty())
{
cout << "No strings were read;\n";
return 0;
}
// peek() 函数
st.peek(str);
if (st.size() == 1 && str.empty())
{
cout << "No strings were read;\n";
return 0;
}
// size() 函数
cout << "\n Read in " << st.size() << " strings.\n";
// 清除 end-of-file 的设定 ????
cin.clear();
cout << "What word to search for? ";
string fstr;
cin >> fstr;
// find() count() 函数
bool found = st.find(fstr);
int count = found ? st.count(fstr) : 0;
cout << fstr << (found ? " is ":" isn\'t ") << " in the stcak. ";
if (found)
{
cout << "It occurs " << count << " times.\n";
}
cout << "\n Read in " << st.size() << " strings.\n"
<< "The strings in reverse order: \n";
// pop() 函数
while (st.size())
{
if (st.pop(str))
cout << str << ' ';
}
cout << '\n' << "There are now " << st.size() << " elements in the stack! \n";
}
- 这道题非常的赞哦,有三个非常重要的知识点:
- 1)
while (cin >> str && !st.full()) { // push() 函数 st.push(str); }
需要 这个输入循环的退出 需要在输入完后,回车,再点击 ctrl+z ,再回车,参见这个链接输入循环在什么情况下结束,while(cin>>word) 类型?,讲的很详细。
-2) stack是非常常用的一种FIFO(先进先出,First input first output)数据结构,还需要多学习体会;
-3)vector.back() 获取向量的尾部元素。
代码是在 visual studio 中编写的,该软件还是比较好用的,我安装的是2022专业版;
共勉!