通过链表中存储对象而不是指针来解决
当链表被销毁的时候似乎它所包含的对象也必须被销毁
当看到创建一个包含string型对象的容器时
STL表现了它的闪光点
//: C07:StringVector.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// A vector of strings.
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include "../require.h"
using namespace std;
int main(int argc, char* argv[]) {
const char* fname = "StringVector.cpp";
if(argc > 1) fname = argv[1];
ifstream in(fname);
assure(in, fname);
vector<string> strings;
string line;
while(getline(in, line))
strings.push_back(line);
// Do something to the strings...
int i = 1;
vector<string>::iterator w;
for(w = strings.begin(); w != strings.end(); w++) {
ostringstream ss;
ss << i++;
*w = ss.str() + ": " + *w;
}
// Now send them out:
copy(strings.begin(), strings.end(),
ostream_iterator<string>(cout, "\n"));
// Since they aren't pointers, string
// objects clean themselves up!
getchar();
} ///:~
输出
1: //: C07:StringVector.cpp
2: // From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
3: // (c) 1995-2004 MindView, Inc. All Rights Reserved.
4: // See source code use permissions stated in the file 'License.txt',
5: // distributed with the code package available at www.MindView.net.
6: // A vector of strings.
7: #include <fstream>
8: #include <iostream>
9: #include <iterator>
10: #include <sstream>
11: #include <string>
12: #include <vector>
13: #include "../require.h"
14: using namespace std;
15:
16: int main(int argc, char* argv[]) {
17: const char* fname = "StringVector.cpp";
18: if(argc > 1) fname = argv[1];
19: ifstream in(fname);
20: assure(in, fname);
21: vector<string> strings;
22: string line;
23: while(getline(in, line))
24: strings.push_back(line);
25: // Do something to the strings...
26: int i = 1;
27: vector<string>::iterator w;
28: for(w = strings.begin(); w != strings.end(); w++) {
29: ostringstream ss;
30: ss << i++;
31: *w = ss.str() + ": " + *w;
32: }
33: // Now send them out:
34: copy(strings.begin(), strings.end(),
35: ostream_iterator<string>(cout, "\n"));
36: // Since they aren't pointers, string
37: // objects clean themselves up!
38: getchar();
39: } ///:~
一旦名为strings的vector<string>被创建
文件中的每一行都作为一个string对象被读入并且放入vector中