C++ collection容器基础知识
2017-03-31 10:12
417 查看
最常见的类为vector,基本上可以取代C的array,而且比array好用很多。
下面这个例子,是从文件中读取所有的行存入到lines中,然后输出。
vector类
不用去管promptUserForFile以及readEntireFile怎么实现的,包含那个库很重要。
下面这个例子,统计字符
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
定义两层容器,最容易想到的就是棋盘
注意>> 和> >的区别。
stack类
stack是写一个rpn计算机,这是个toy表达式,真正的计算器并不是这样实现的。
RPN Calculator Simulation (type H for help)
> 12
> 12
> +
24
> 12
> 12
> /
1
> +
25
>
Queue类
这个例子是排队付钱的例子,比较常见,有英文注释,可以理解这个queue
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;
下面这个例子,是从文件中读取所有的行存入到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;
相关文章推荐
- [C++ 面试基础知识总结] 顺序容器
- 对C++中关联容器一些基础知识的认识
- C++ 顺序容器基础知识总结
- [C++ 面试基础知识总结] 关联容器
- C++ 顺序容器基础知识总结
- C++顺序容器基础知识总结
- C++学习(4)--基础知识(4)--关于const
- C++基础知识(二)
- C++的基础知识
- pascal→→c++常用基础小知识
- 基础知识C++
- 您需要注意的c++ 的11个要点[转贴] 基础知识
- 基础知识提问:关于HashTable和List两个容器Add改变了属性的同一对象的问题
- C++ 基础小知识学习[1]
- C++基础小知识[2]---堆与栈的区别[转]
- c++基础知识---名字空间
- C++相关基础知识(转贴)
- 自己总结C/C++的一些容易被遗忘的基础知识!
- Jack整理的Win32汇编基础知识 - [C/C++]
- C++基础知识