您的位置:首页 > 编程语言 > C语言/C++

C++ collection容器基础知识

2017-03-31 10:12 417 查看
最常见的类为vector,基本上可以取代C的array,而且比array好用很多。

下面这个例子,是从文件中读取所有的行存入到lines中,然后输出。

vector类

不用去管promptUserForFile以及readEntireFile怎么实现的,包含那个库很重要。

#include <iostream>
#include <fstream>
#include <string>
#include "filelib.h"
#include "vector.h"
#include "console.h"
using namespace std;
void readEntireFile(istream &is, Vector<string> &lines);

int main() {
ifstream infile;
Vector<string> lines;
promptUserForFile(infile, "Input file: ");
readEntireFile(infile, lines);
infile.close();
for (int i = lines.size() - 1; i >= 0; i--) {
cout << lines[i] << endl;
}
return 0;
}


下面这个例子,统计字符

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
#include "filelib.h"
#include "vector.h"
#include "console.h"

using namespace std;

static const int COLUMNS = 7;

int main() {
Vector<int> letterCounts(26);
ifstream infile;
promptUserForFile(infile, "Input file: ");
char ch;
while (infile.get(ch)) {
if (isalpha(ch)) {
letterCounts[toupper(ch) - 'A']++;
}
}
infile.close();
for (char ch = 'A'; ch <= 'Z'; ch++) {
cout << setw(COLUMNS) << letterCounts[ch - 'A'] << " " << ch << endl;
}
return 0;
}


Input file: /home/wang/3english

377 A

55 B

190 C

247 D

575 E

119 F

62 G

203 H

344 I

2 J

14 K

205 L

105 M

318 N

288 O

92 P

2 Q

253 R

364 S

389 T

108 U

34 V

53 W

32 X

60 Y

4 Z

定义两层容器,最容易想到的就是棋盘

Vector<Vector<int>> sudoku(9, Vector<int>(9));


注意>> 和> >的区别。

stack类

stack是写一个rpn计算机,这是个toy表达式,真正的计算器并不是这样实现的。

/*
* This porgram simulates an electronic calculator that uses
* reverse Polish notation, in which the operators come after
* the operands to which they apply. Information for users
* of this application appears in the helpCommand function.
*/

#include <iostream>
#include <cctype>
#include <string>
#include "error.h"
#include "simpio.h"
#include "stack.h"
#include "strlib.h"
#include "console.h"

using namespace std;

void applyOperator(char op, Stack<double> &operandStack) {
double result;
double rhs = operandStack.pop();
double lhs = operandStack.pop();
switch (op) {
case '+': result = lhs + rhs; break;
case '-': result = lhs - rhs; break;
case '*': result = lhs * rhs; break;
case '/': result = lhs / rhs; break;
default:
error("Illegal operator");
}
cout << result << endl;
operandStack.push(result);
}

void helpCommand() {
cout << "Enter expressions in Reverse Polish Notation." << endl;
}

int main() {
cout << "RPN Calculator Simulation (type H for help)" << endl;
Stack<double> operandStack;
while (true) {
string line = getLine("> ");
if (line.length() == 0) line = "Q";
char ch = toupper(line[0]);
if (ch == 'Q') {
break;
} else if (ch == 'C') {
operandStack.clear();
} else if (ch == 'H') {
helpCommand();
} else if (isdigit(ch)) {
operandStack.push(stringToReal(line));
} else {
applyOperator(ch, operandStack);
}
}
return 0;
}


RPN Calculator Simulation (type H for help)

> 12

> 12

> +

24

> 12

> 12

> /

1

> +

25

>

Queue类

这个例子是排队付钱的例子,比较常见,有英文注释,可以理解这个queue

/*
* This program simulate a checkout line, such as one you
* might encounter in a grocery store. Customers arrive at
* the checkout stand and get in line. Those customers wait
* in the lines until the cashier is free, at which point
* they are served and occupy the cashier for some period
* of time. After the service time is complete, the cashier
* is free to serve the next customer in the line.
*
* In each unit of time, up to the constant SIMULATION_TIME,
* the following operations are performed:
* 1. Detemine whether a new customer has arrived.
*    New customers arrives randomly, with a probability
*    determined by the constant ARRIVAL_PROBABILITY.
* 2. If the cashier is busy, note that the crashier has spent
*    another minute with that customer. Eventually,
*    the customer's time request is satisfied, which frees the cashier.
* 3. If the cashier is free, serve the next customer in line.
*    The service time is taken to be a random period betweens
*    MIN_SERVICE_TIME and MAX_SERVICE_TIME.
*
* At the end of the simulations, the program displays the simulation
* constants and the following computed results:
*  The number of customers served
*  The average time spent in line
*  The average number of people in line.
*/

#include <iostream>
#include <iomanip>
#include "queue.h"
#include "random.h"
using namespace std;

const double ARRIVAL_PROBABILITY = 0.05;
const int MIN_SERVICE_TIME = 5;
const int MAX_SERVICE_TIME = 15;
const int SIMULATION_TIME = 2000;

void runSimulation(int &nServed, int &totalWait, int &totalLength);
void printReport(int nServed, int totalWait, int totalLength);

int main() {
int nServed;
int totalWait;
int totalLength;
runSimulation(nServed, totalWait, totalLength);
printReport(nServed, totalWait, totalLength);
}

void runSimulation(int &nServed, int &totalWait, int &totalLength) {
Queue<int> queue;
int timeRemaining = 0;
nServed = 0;
totalWait = 0;
totalLength = 0;
for (int t = 0; t < SIMULATION_TIME; t++) {
if (randomChance(ARRIVAL_PROBABILITY)) {
queue.enqueue(t);
}
if (timeRemaining > 0) {
timeRemaining--;
} else if (!queue.isEmpty()) {
totalWait += t - queue.dequeue();
nServed++;
timeRemaining = randomInteger(MIN_SERVICE_TIME, MAX_SERVICE_TIME);
}
totalLength += queue.size();
}
}

void printReport(int nServed, int totalWait, int totalLength) {
cout << "Simulation results given the following constants:" << endl;
cout << fixed << setprecision(2);
cout << "SIMULATION TIME:   " << setw(4) << SIMULATION_TIME << endl;
cout << "Customers served: " << setw(4) << nServed << endl;
cout << "Average waiting time: " << setw(7) << double(totalWait) / nServed << endl;
cout << "Average queue length: " << setw(7) << double(totalLength) / SIMULATION_TIME << endl;

}
输出:

Simulation results given the following constants:

SIMULATION TIME: 2000

Customers served: 103

Average waiting time: 5.60

Average queue length: 0.29

map介绍

A map is a generalization of this idea that provides an association between an identify tag called a key and an associated value, which may be a much larger and more complicated structure.

定义一个字典类

Map<string, string> dictionary;

key 和 value都是string类型。

读取文件操作

// This program looks up a three-letter airport code in a Map object.
#include <iostream>
#include <fstream>
#include <string>
#include "error.h"
#include "map.h"
#include "strlib.h"
using namespace std;

void readCodeFile(string filename, Map<string, string> &map);

int main() {
Map<string, string> airportCodes;
readCodeFile("AirportCodes.txt", airportCodes);
while (true) {
string line;
cout << "Airport code: ";
getline(cin, line);
if (line == "") break;
string code = toUpperCase(line);
if (airportCodes.containsKey(code)) {
cout << code << " is in " << airportCodes.get(code) << endl;
} else {
cout << "There is no such airport code" << endl;
}
}
return 0;
}

void readCodeFile(string filename, Map<string, string> &map) {
ifstream infile;
infile.open(filename.c_str());
if (infile.fail()) error("Can't read the data file");
string line;
while (getline(infile,line)) {
if (line.length() < 4 || line[3] != '=') {
error("Illegal data line: " + line);
}
string code = toUpperCase(line.substr(0, 3));
map.put(code, line.substr(4));
}
infile.close();
}

map[key] = value;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: