growdemo.cpp

来自「C++&datastructure书籍源码,以前外教提供现在与大家共享」· C++ 代码 · 共 60 行

CPP
60
字号
#include <iostream>
#include <string>
using namespace std;

#include "prompt.h"
#include "tvector.h"
#include "worditer.h"
#include "ctimer.h"

// show differences between push_back and calling resize explicity

void ReadAll(WordStreamIterator& iter, tvector<string>& list)
// postcondition: all words from iter stored in list
{
    for(iter.Init(); iter.HasMore(); iter.Next())
    {    list.push_back(iter.Current());
    }
}

void ReadAll2(WordStreamIterator& iter, 
              tvector<string>& list, int& count)
// postcondition: all words from iter stored in list,
//                count = number of words read
{
    count = 0;
    for(iter.Init(); iter.HasMore(); iter.Next())
    {   if (count >= list.capacity())
        {   list.resize(list.capacity()*2 + 1);  // grow by doubling
        }
        list[count] = iter.Current();
        count++;
    }
}

int main()
{
	CTimer timer;
    string filename = PromptString("enter filename ");
    WordStreamIterator iter;
    iter.Open(filename);
    
    tvector<string> listA;  // listA.reserve(100000);
    tvector<string> listB;  // listB.reserve(100000);
    
	timer.Start();
    ReadAll(iter,listA);
	timer.Stop();
	cout << "# words: " << listA.size() 
         << " capacity: " << listA.capacity() 
		 << " time: " << timer.ElapsedTime() << endl;
		
	int count;             // # elements stored in listB 
	timer.Start();
    ReadAll2(iter,listB,count);
	timer.Stop();
    cout << "# words: " << count
         << " capacity: " << listB.capacity() 
		 << " time: " << timer.ElapsedTime() << endl;
    return 0;
}    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?