主要有五个容器
This chapter introduces five classes - Vector, Stack, Queue, Map, and Set - each of which represents an important abstract data types.
Being able to separate the behavior of a class from it underlying implementation is a fundamental precept of object-oriented programming.
这节使用的stanford的库,所以vector会大写开头,不过并不影响使用。
Vector vec;
When you declare a Vector variable, it start out as an empty vector, which means that it contains no elements.
vec.add(10);
vec.add(20);
vec.insertAt(1, 15);
删除
vec.removeAt(1);
get和set
获取和修改相应的值。
The get, set, insertAt and removeAt methods all check to make sure that the index value you supply is valid for the vector.
One of the characteristics of C++ that sets it apart from other language is that classes can override the definition of the standard operators.
Thus, to select the element at position i, you can use the expression vec[i], just as you would with a traditional array.
vec[2] = 70;
cout << "[";
for (int i =0; i < vec.size(); i++) {
if (i > 0) cout << ", ";
cout << vec[i];
}
cout << "]" << endl;
/*
* This program displays the lines of an input file in reverse order.
*/
#include
#include
#include
#include "console.h"
#include "filelib.h"
#include "vector"
using namespace std;
int main() {
ifstream infile;
Vector 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;
}
void readEntireFile(std::istream& is, Vector& lines) {
lines.clear();
while (true) {
std::string line;
getline(is, line);
if (is.fail()) break;
lines.add(line);
}
}
Input file: test.txt
And the mome raths outgrabe.
All misy were the borogoves,
Die gyre and gimble in the wabe;
构造器的讨论,不同的构造器。
The C++ compiler determines which version of the constructor to call by looking at the arguments appearing in the declaration, just as it does for overloaded functions. The declaration of lines provides no arguments, which tells the compiler to invoke the constructor that takes no arguments, which is called the default constructor. The declaration of letterCounts provides an integer argument, which tells the compiler to invoke the version of the constructor that takes an integer indicating the vector size.
数独
Vector
Grid类
这章的内容已经很熟悉了,就是那几个类。记得多加应用。
This chapter introduced the C++ classes Vector, Stack, Queue, Map, and Set that together represent a powerful framework for storing collections.
到第六章。