C++编程思想 第2卷 第7章 通用容器 概述 字符串容器

通过链表中存储对象而不是指针来解决
当链表被销毁的时候似乎它所包含的对象也必须被销毁
当看到创建一个包含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中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值