Re: [Dev-C++] How to work with *.txt files??
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: ZwiQ <zw...@he...> - 2004-09-18 20:37:58
|
Per Westermark wrote:
> <>Ouch.
>
> Don't do that.
>
> There is the vector template class in the stl.
(Hielke blames himself for not reading a good C++ book himself :o)
Hm, you're right. Thanks! I said I would use a vector but in the code I
did use an simple array. Now I think of it, the code I wrote down there
without good thinking was ment to store an array of pointers to strings,
not strings themselves. Used it mainly when I had to reorganize the
order of the stored strings with manipulation members (eg. sort).
I assume that assigning pointers isn't as resourcesconsuming as
assigning strings? However, you're still right about the complexity.
Vector operations themselves all are lineair? So I should use a vector
in that case too as well?
Regards,
Hielke
Zw...@he...
> <>Do not write a method that reallocates all strings every time.
>
> First line - allocate one string.
> Second line - allocate two strings.
> Third line - allocate three strings.
> ...
>
> By doing this, you manage to transform a linear operation - proportional
> to number of lines in the file - to become O(n^2).
>
> If you open a 100,000 line file, you would perform 100,000^2 / 2 or
> 5,000,000,000 string assigns.
>
> Never add complexity when it isn't needed.
>
> std::vector<std::string> strings;
>
> and then
>
> strings.push_back(line);
>
> or
>
> strings.reserve(10);
> strings[n++] = line;
>
> is a lot nicer code, and tremendously much more efficient.
>
> /Per W
>
> On Sat, 18 Sep 2004, hielke_prins wrote:
>
>>>>How do I refer to each line of my *.txt file???
>>>>
>>>>
>>/*
>> If you don't have any clue how to read a simple textfile, the first
>>thing you
>> proably have to do is buying a good book on C(++). But here ya go.
>>
>> I usually read small plaintext files in a vector using a simple
>>wrapperclass.
>> Something like this (if you meant to write it in C++ at least),
>>didn't test it:
>>*/
>>
>>Class Lines
>>{
>> string *d_line;
>> unsigned d_nLines;
>>
>> public:
>> Lines(istream streamIn);
>> /*
>> (of course you need some simple memberfunctions
>> returning linecount and lines on a given index too)
>> */
>>}
>>
>>Lines::Lines(istream streamIn)
>>:
>> d_nLines(0)
>>{
>> string inputLine,
>> *tempLine;
>>
>> while(getline(streamIn, inputLine))
>> {
>> d_nLines++;
>> tempLine = new string[d_nLines];
>> for(unsigned i = 0; i < d_nLines; i++)
>> {
>> tempLine[i] = d_line[i];
>> }
>> delete d_line;
>> d_line = tempLine;
>> }
>>}
>>
>>Regards,
>> Hielke
>>
>>
>
>
>
>
|