12.3 C++生成存储指针的栈的正确使用方法
12.3.1 简介
12.3.1.1 一组指针指向一组字符串
可以将指针作为模板参数传递吗?可以,但是要注意使用方式。
—正确的使用方式是 一组指针指向一组字符串
12.3.1.2 注意事项
- 1.数组指针不能直接接收键盘或文件的输入
- 2.不能对于C类字符串直接使用=实现复制
- 3.小心一直将一个地址赋给不同的指针,然后读取每个指针时读取到的都是同一地址的值。
12.3.2 代码
stacktp.h
main.h
#pragma once
#ifndef MAIN_H_
#define MAIN_H_
#include <iostream> //输入输出
#include "stacktp.h" //simple_template、pointer_template
#include <cstdlib> //pointer_template
#include <ctime> //pointer_template
using namespace std;
void pointer_template(void)
{
//类模板生成的关于指针的栈的正确使用方法---每个指针指向已经存在的字符串
//Someone has delivered a cart of folders to Plodson.
//If Plodson’s in - basket is empty, he removes the top folder from the cartand places it in his in - basket.
//If his in - basket is full, Plodson removes the top file from the basket, processes it, and places it in his out - basket.
//If the in-basket is neither empty nor full, Plodson may process the top file in the in - basket, or he may take the next
//file from the cart and put it into his in - basket.
const int Num = 10;
cout << "\npointer_template Hello*****************************************************\n";
std::srand(std::time(0)); // randomize rand()
std::cout << "Please enter stack size: ";
int stacksize;
std::cin >> stacksize;
// create an empty stack with stacksize slots
Stack<const char*> st(stacksize);
// in basket
const char* in[Num] = {//字符串常量存储在特殊区域,和变量存储区域不一样
" 1: Hank Gilgamesh", " 2: Kiki Ishtar",
" 3: Betty Rocker", " 4: Ian Flagranti",
" 5: Wolfgang Kibble", " 6: Portia Koop",
" 7: Joy Almondo", " 8: Xaverie Paprika",
" 9: Juan Moore", "10: Misha Mache"
};
// out basket
const char* out[Num];
int processed = 0;
int nextin = 0;
while (processed < Num)
{
if (st.isempty())
st.push(in[nextin++]);
else if (st.isfull())
st.pop(out[processed++]);
else if (std::rand() % 2 && nextin < Num) //如果随机数是偶数,就入栈
st.push(in[nextin++]);
else
st.pop(out[processed++]);//如果随机数是奇数,就出栈
}
for (int i = 0; i < Num; i++)//处理完成之后输出所有信件处理的数据
std::cout << out[i] << std::endl;
std::cout << "pointer_template Bye*****************************************************\n";
}
#endif
main.cpp
/*
Project name : _12template
Last modified Date: 2022年5月6日11点33分
Last Version: V1.0
Descriptions: 类模板生成的关于指针的栈的正确使用方法
*/
#include "main.h"
int main()
{
cout << "类模板生成的关于指针的栈的正确使用方法***************************************" << endl;
pointer_template();
return 0;
}
12.3.3 运行结果
类模板生成的关于指针的栈的正确使用方法***************************************
pointer_template Hello*****************************************************
Please enter stack size: 4
2: Kiki Ishtar
1: Hank Gilgamesh
3: Betty Rocker
6: Portia Koop
7: Joy Almondo
5: Wolfgang Kibble
4: Ian Flagranti
8: Xaverie Paprika
10: Misha Mache
9: Juan Moore
pointer_template Bye*****************************************************
D:\Prj\_C++Self\_12template\Debug\_12template.exe (进程 15140)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .