Recent Posts

Pages: [1] 2 3 ... 10
1
Ask the Author / Re: Breakfast ... it's time to feed at Jesus Feet ...
« Last post by David on August 08, 2017, 07:38:27 AM »
A start to 'Heaven's inspired answers':


Who is GOD?

Every building has a builder, but the builder of ALL things is God.

For every house is builded by some man; but he that built all things is God.
(Hebrews 3:4)

Genesis 1
1  In the beginning God created the heaven and the earth.
2  And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.
3  And God said, Let there be light: and there was light.
4  And God saw the light, that it was good: and God divided the light from the darkness.
5  And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.
6  And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.
7  And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so.
8  And God called the firmament Heaven. And the evening and the morning were the second day.
9  And God said, Let the waters under the heaven be gathered together unto one place, and let the dry land appear: and it was so.
10 And God called the dry land Earth; and the gathering together of the waters called he Seas: and God saw that it was good.
11 And God said, Let the earth bring forth grass, the herb yielding seed, and the fruit tree yielding fruit after his kind, whose seed is in itself, upon the earth: and it was so.
12 And the earth brought forth grass, and herb yielding seed after his kind, and the tree yielding fruit, whose seed was in itself, after his kind: and God saw that it was good.
13 And the evening and the morning were the third day.
14 And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years:
15 And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.
16 And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: he made the stars also.
17 And God set them in the firmament of the heaven to give light upon the earth,
18 And to rule over the day and over the night, and to divide the light from the darkness: and God saw that it was good.
19 And the evening and the morning were the fourth day.
20 And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl that may fly above the earth in the open firmament of heaven.
21 And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that it was good.
22 And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.
23 And the evening and the morning were the fifth day.
24 And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.
25 And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that it was good.
26 And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.
27 So God created man in his own image, in the image of God created he him; male and female created he them.
28 And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.

For in six days the LORD made heaven and earth, the sea, and all that in them is,
and rested the seventh day:wherefore the LORD blessed the sabbath day, and hallowed it.
(Exodus 20:11)

It is a sign between me and the children of Israel for ever:
for in six days the LORD made heaven and earth,
and on the seventh day he rested, and was refreshed.
(Exodus 31:17)


Who is Jesus?

Verily, verily, I say unto you, He that heareth my word, and believeth on him that sent me,
hath everlasting life, and shall not come into condemnation; but is passed from death unto life.
(John 5:24)

John 10
11  I am the good shepherd: the good shepherd giveth his life for the sheep.
...
14  I am the good shepherd, and know my sheep, and am known of mine.
...
26  But ye believe not, because ye are not of my sheep, as I said unto you.
27  My sheep hear my voice, and I know them, and they follow me:
28  And I give unto them eternal life; and they shall never perish, neither shall any man pluck them out of my hand.
29  My Father, which gave them me, is greater than all; and no man is able to pluck them out of my Fatherís hand.
30  I and my Father are one.

Ephesians 2
4  But God, who is rich in mercy, for his great love wherewith he loved us,
5  Even when we were dead in sins, hath quickened us together with Christ, (by grace ye are saved;)
6  And hath raised us up together, and made us sit together in heavenly places in Christ Jesus:
7  That in the ages to come he might shew the exceeding riches of his grace in his kindness toward us through Christ Jesus.
8  For by grace are ye saved through faith; and that not of yourselves: it is the gift of God:
9  Not of works, lest any man should boast.
10 For we are his workmanship, created in Christ Jesus unto good works, which God hath before ordained that we should walk in them.


John 8:38
I speak that which I have seen with my Father: ...

John 14:7
If ye had known me, ye should have known my Father also:
and from henceforth ye know him, and have seen him.

Joh 14:9
Jesus saith unto him, Have I been so long time with you,
and yet hast thou not known me, Philip?
he that hath seen me hath seen the Father;
and how sayest thou then, Shew us the Father?

John 15:24
If I had not done among them the works which none other man did, they had not had sin:
but now have they both seen and hated both me and my Father.

Isaiah 9
6 For unto us a child is born, unto us a son is given: and the government shall be upon his shoulder: and his name shall be called Wonderful, Counsellor, The mighty God, The everlasting Father, The Prince of Peace.
7 Of the increase of his government and peace there shall be no end, upon the throne of David, and upon his kingdom, to order it, and to establish it with judgment and with justice from henceforth even for ever. The zeal of the Lord of hosts will perform this.

Isaiah 12
1  And in that day thou shalt say, O LORD, I will praise thee: though thou wast angry with me, thine anger is turned away, and thou comfortedst me.
2  Behold, God is my salvation (Yeshua); I will trust, and not be afraid: for the LORD THE LORD is my strength and my song; he also is become my salvation (Yeshua).
3  Therefore with joy shall ye draw water out of the wells of salvation (Yeshua).
4  And in that day shall ye say, Praise the LORD, call upon his name, declare his doings among the people, make mention that his name is exalted.
5  Sing unto the LORD; for he hath done excellent things: this is known in all the earth.
6  Cry out and shout, thou inhabitant of Zion: for great is the Holy One of Israel in the midst of thee.

Isaiah 53
3  He is despised and rejected of men; a man of sorrows, and acquainted with grief: and we hid as it were our faces from him; he was despised, and we esteemed him not.
4  Surely he hath borne our griefs, and carried our sorrows: yet we did esteem him stricken, smitten of God, and afflicted.
5  But he was wounded for our transgressions, he was bruised for our iniquities: the chastisement of our peace was upon him; and with his stripes we are healed.
6  All we like sheep have gone astray; we have turned every one to his own way; and the LORD hath laid on him the iniquity of us all.
7  He was oppressed, and he was afflicted, yet he opened not his mouth: he is brought as a lamb to the slaughter, and as a sheep before her shearers is dumb, so he openeth not his mouth.
8  He was taken from prison and from judgment: and who shall declare his generation? for he was cut off out of the land of the living: for the transgression of my people was he stricken.
9  And he made his grave with the wicked, and with the rich in his death; because he had done no violence, neither was any deceit in his mouth.
10 Yet it pleased the LORD to bruise him; he hath put him to grief: when thou shalt make his soul an offering for sin, he shall see his seed, he shall prolong his days, and the pleasure of the LORD shall prosper in his hand.
11 He shall see of the travail of his soul, and shall be satisfied: by his knowledge shall my righteous servant justify many; for he shall bear their iniquities.
12 Therefore will I divide him a portion with the great, and he shall divide the spoil with the strong; because he hath poured out his soul unto death: and he was numbered with the transgressors; and he bare the sin of many, and made intercession for the transgressors.


John 1
1  In the beginning was the Word, and the Word was with God, and the Word was God.
2  The same was in the beginning with God.
3  All things were made by him; and without him was not any thing made that was made.
4  In him was life; and the life was the light of men.
5  And the light shineth in darkness; and the darkness comprehended it not.

Through faith we understand that the worlds were framed by the word of God,
so that things which are seen were not made of things which do appear.
(Hebrews 11:3)



Philippians 2
3  Let nothing be done through strife or vainglory; but in lowliness of mind let each esteem other better than themselves.
4  Look not every man on his own things, but every man also on the things of others.
5  Let this mind be in you, which was also in Christ Jesus:
6  Who, being in the form of God, thought it not robbery to be equal with God:
7  But made himself of no reputation, and took upon him the form of a servant, and was made in the likeness of men:
8  And being found in fashion as a man, he humbled himself, and became obedient unto death, even the death of the cross.
9  Wherefore God also hath highly exalted him, and given him a name which is above every name:
10 That at the name of Jesus every knee should bow, of things in heaven, and things in earth, and things under the earth;
11 And that every tongue should confess that Jesus Christ is Lord, to the glory of God the Father.



Joh 1:10
He was in the world, and the world was made by him, and the world knew him not.

Joh 5:17
But Jesus answered them, My Father worketh hitherto, and I work.

Joh 5:18
Therefore the Jews sought the more to kill him, because he not only had broken the sabbath,
but said also that God was his Father, making himself equal with God.

Joh 5:19
Then answered Jesus and said unto them, Verily, verily, I say unto you, The Son can do nothing of himself,
but what he seeth the Father do: for what things soever he doeth, these also doeth the Son likewise.

Ge 1:26
And God said, Let us make man in our image, after our likeness:
and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle,
and over all the earth, and over every creeping thing that creepeth upon the earth.

Ps 33:6
By the word of the LORD were the heavens made; and all the host of them by the breath of his mouth.

Ps 102:25
Of old hast thou laid the foundation of the earth: and the heavens are the work of thy hands.

Isa 45:12
I have made the earth, and created man upon it:
I, even my hands, have stretched out the heavens, and all their host have I commanded.

Isa 45:18
For thus saith the LORD that created the heavens; God himself that formed the earth and made it;
he hath established it, he created it not in vain,
he formed it to be inhabited:
I am the LORD; and there is none else.

Eph 3:9
And to make all men see what is the fellowship of the mystery,
which from the beginning of the world hath been hid in God,
who created all things by Jesus Christ:


For by him were all things created, that are in heaven, and that are in earth, visible and invisible,
whether they be thrones, or dominions, or principalities, or powers: all things were created by him, and for him:
And he is before all things, and by him all things consist.
(Colossians 1:16, 17)

Hath in these last days spoken unto us by his Son, whom he hath appointed heir of all things, by whom also he made the worlds;
Who being the brightness of his glory, and the express image of his person, and upholding all things by the word of his power, when he had by himself purged our sins, sat down on the right hand of the Majesty on high;
...
And, Thou, Lord, in the beginning hast laid the foundation of the earth; and the heavens are the works of thine hands:
They shall perish; but thou remainest; and they all shall wax old as doth a garment;
And as a vesture shalt thou fold them up, and they shall be changed: but thou art the same, and thy years shall not fail.
(Hebrews 1:2,3,10,11,12)

For this man was counted worthy of more glory than Moses, inasmuch as he who hath builded the house hath more honour than the house.
For every house is builded by some man; but he that built all things is God.
(Hebrews 3:3,4)

Thou art worthy, O Lord, to receive glory and honour and power:
for thou hast created all things,
and for thy pleasure they are and were created.
(Revelation 4:11)





2
Ask the Author / Re: Breakfast ... it's time to feed at Jesus Feet ...
« Last post by David on August 08, 2017, 07:29:15 AM »
Read the story of Jesus and the woman of Samaria at the well ...

What is worship?

What is Spirit? Truth?

What does it mean to be (born again)
born of the Spirit?
Born of the Word?
Born of God?
(Do we have any part in 'being born again'?)

New Covenant ... why ?
All taught by God

The letter kills but the Spirit gives life.

We are all (who follow Christ, are commissioned to be) ministers of the Spirit ...

In the very place of Christ, we implore men to be reconciled to God ... since ...
(He who knew no sin, was made to be sin for us, that we might be made the righteousness of God in HIM.)

2 Corinthians 5:
14  For the love of Christ constraineth us; because we thus judge, that if one died for all, then were all dead:
15  And that he died for all, that they which live should not henceforth live unto themselves, but unto him which died for them, and rose again.
16  Wherefore henceforth know we no man after the flesh: yea, though we have known Christ after the flesh, yet now henceforth know we him no more.
17  Therefore if any man be in Christ, he is a new creature: old things are passed away; behold, all things are become new.
18  And all things are of God, who hath reconciled us to himself by Jesus Christ, and hath given to us the ministry of reconciliation;
19  To wit, that God was in Christ, reconciling the world unto himself, not imputing their trespasses unto them; and hath committed unto us the word of reconciliation.
20  Now then we are ambassadors for Christ, as though God did beseech you by us: we pray you in Christís stead, be ye reconciled to God.
21  For he hath made him to be sin for us, who knew no sin; that we might be made the righteousness of God in him.

3
Ask the Author / Re: Breakfast ... it's time to feed at Jesus Feet ...
« Last post by David on August 08, 2017, 07:27:30 AM »
What is the HOLY BIBLE?

Who wrote it?

How has it come to us?

Did God promise to preserve it?

So where is it (in English) today?

(Compare versions to see: 1 John 4:19 KJV vs NIV; Matthew 7:14 KJV vs NKJV)
(Then see:  Matthew 11: 28-30 'yoke easy ... burden light', Galations 1:6,7, Numbers 24:3-9, Jude 11)

Note: God chose the foolishness of preaching to save whoever would believe ... why? (1 Corinthians 1:17-31)

We love him, because he first loved us. (KJV:  1 John 4:19)
We love because he first loved us.         (NIV:  1 John 4:19)

Because strait is the gate, and narrow is the way, which leadeth unto life, and few there be that find it.
(KJV:     Matthew 7:14 )
Because narrow is the gate and difficult is the way which leads to life, and there are few who find it.
(NKJV:  Matthew 7:14 )

Now note these precious words of Jesus:
Come unto me, all ye that labour and are heavy laden, and I will give you rest. Take my yoke upon you, and learn of me; for I am meek and lowly in heart: and ye shall find rest unto your souls. For my yoke is easy, and my burden is light. (Matthew 11:28-30 -- so NKJV Matthew 7:14 is preaching a false gospel.)

I marvel that ye are so soon removed from him that called you into the grace of Christ unto another gospel: Which is not another; but there be some that trouble you, and would pervert the gospel of Christ.  But though we, or an angel from heaven, preach any other gospel unto you than that which we have preached unto you, let him be accursed. As we said before, so say I now again, If any man preach any other gospel unto you than that ye have received, let him be accursed. (Galatians 1:6-9)

Carefully note this warning from Jesus: (Matthew 7:21-23)
Not every one that saith unto me, Lord, Lord, shall enter into the kingdom of heaven; but he that doeth the will of my Father which is in heaven. Many will say to me in that day, Lord, Lord, have we not prophesied in thy name? and in thy name have cast out devils? and in thy name done many wonderful works? And then will I profess unto them, I never knew you: depart from me, ye that work iniquity.

And see the end of Balaam ... and those who have hearts like his: (Jude 11,12,13)
Woe unto them! for they have gone in the way of Cain, and ran greedily after the error of Balaam for reward, and perished in the gainsaying of Core. These are spots in your feasts of charity, when they feast with you, feeding themselves without fear: clouds they are without water, carried about of winds; trees whose fruit withereth, without fruit, twice dead, plucked up by the roots; Raging waves of the sea, foaming out their own shame; wandering stars, to whom is reserved the blackness of darkness for ever.

Now see the amazing experience and prophecy that Balaam had ... but tragically, it seems he never was truly converted.

And he took up his parable, and said, Balaam the son of Beor hath said, and the man whose eyes are open hath said:
He hath said, which heard the words of God, which saw the vision of the Almighty, falling into a trance, but having his eyes open:
How goodly are thy tents, O Jacob, and thy tabernacles, O Israel!
As the valleys are they spread forth, as gardens by the riverís side, as the trees of lign aloes which the LORD hath planted, and as cedar trees beside the waters.
He shall pour the water out of his buckets, and his seed shall be in many waters, and his king shall be higher than Agag, and his kingdom shall be exalted.
God brought him forth out of Egypt; he hath as it were the strength of an unicorn: he shall eat up the nations his enemies, and shall break their bones, and pierce them through with his arrows.
He couched, he lay down as a lion, and as a great lion: who shall stir him up? Blessed is he that blesseth thee, and cursed is he that curseth thee. ( Numbers 24:3-9)
4
Ask the Author / Breakfast ... it's time to feed at Jesus Feet ...
« Last post by David on August 08, 2017, 07:24:53 AM »


A first rough draft to get started ...

Who IS GOD?

Every building has a builder, but the builder of all things is God. (also see: Hebrews 3:4, Genesis 1)
Note that we ALL know that every building has to have a builder ... so for this given we will all be held accountable.

Who IS JESUS? (John 1:1-18, see also Isaiah 9:6,7, Isaiah 12, Isaiah 53)
In the beginning was the Word, and the Word was with God, and the Word was God.
The same was in the beginning with God.
All things were made by him; and without him was not any thing made that was made.
In him was life; and the life was the light of men.
And the light shineth in darkness; and the darkness comprehended it not.
There was a man sent from God, whose name was John. The same came for a witness, to bear witness of the Light, that all men through him might believe. He was not that Light, but was sent to bear witness of that Light. That was the true Light, which lighteth every man that cometh into the world.
He was in the world, and the world was made by him, and the world knew him not.
He came unto his own, and his own received him not.
But as many as received him, to them gave he power to become the sons of God, even to them that believe on his name:
Which were born, not of blood, nor of the will of the flesh, nor of the will of man, but of God.
And the Word was made flesh, and dwelt among us, (and we beheld his glory, the glory as of the only begotten of the Father,) full of grace and truth.
John bare witness of him, and cried, saying, This was he of whom I spake, He that cometh after me is preferred before me: for he was before me.
And of his fulness have all we received, and grace for grace.
For the law was given by Moses, but grace and truth came by Jesus Christ.
No man hath seen God at any time; the only begotten Son, which is in the bosom of the Father, he hath declared him.

Why do we need a SAVIOUR? (Romans 3:23, 5:12)
For all have sinned, and come short of the glory of God;  ... Wherefore, as by one man sin entered into the world, and death by sin; and so death passed upon all men, for that all have sinned:

Who is the SAVIOUR?  (Is there more than one SAVIOUR?) (Isaiah 43:11, 44:8,  Hosea 13:4)
I, even I, am the LORD; and beside me there is no saviour. ... Fear ye not, neither be afraid: have not I told thee from that time, and have declared it? ... ye are even my witnesses. Is there a God beside me? yea, there is no God; I know not any. ... Yet I am the LORD thy God from the land of Egypt, and thou shalt know no god but me: for there is no saviour beside me. (See also: Isaiah 12, Matthew 1:21 ... call his name JESUS: {YESHUA Ė GOD my SAVIOUR} for he shall save his people from their sins.)

Why do we need to get to know HIM? (John 17:3, Matthew 11:28-30)
And this is life eternal, that they might know thee the only true God,
and Jesus Christ, whom thou hast sent. ... Come unto me, all ye that labour and are heavy laden, and I will give you rest. Take my yoke upon you, and learn of me; for I am meek and lowly in heart: and ye shall find rest unto your souls. For my yoke is easy, and my burden is light.

How do we (1) get to know HIM, (2) come to know that we know HIM? (John 8:31,32; 1 John 2:3)
Then said Jesus to those Jews which believed on him, If ye continue in my word,
then are ye my disciples indeed; And ye shall know the truth, and the truth shall make you free. ...
And hereby we do know that we know him, if we keep his commandments.

Does He still speak to us today? (John 10:27, 14:26)
My sheep hear my voice, ... they follow me:  ... the Comforter, which is the Holy Ghost (the Holy Spirit), whom the Father will send in my name, he shall teach you all things, and bring all things to your remembrance, whatsoever I have said unto you.
5
And now back to a demo of coding and using an iterator for a binary search tree ...

Firstly the .txt data file (Name it Persons.txt), then the test .cpp file ... and then the .h file ...

Enjoy :)

Code: [Select]
19570810 101440980 Bob Lamprey NY
19270624 103980155 Pinky Fellowes OR
19470314 106100903 Oliver Kringle ND
19480105 108690448 Louie Brown KS
19641028 111180924 Alan Davies UT
19710227 112200747 Bella Napster OK
19730716 112550407 Roger Stone OR
19750716 111111111 Mary Stone OR
19570504 113070570 James Mitchell TX
19401023 113220519 Jilly Aston WY
19670607 114680858 Matt Vincent MI


Now the . cpp file ...

Code: [Select]
// test_bsTreeIterator.h.cpp //  // 2017-04-16 //


#include "bsTreeIterator.h"

#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>


const char* MENU =
    "Find .............. Enter :  F lastname \n"
    "Print (tree) ...... Enter :  P lastname \n"
    "eXit .............. Enter :  X";

const char* FNAME = "Persons.txt";
/*
19570810 101440980 Bob Lamprey NY
19270624 103980155 Pinky Fellowes OR
19470314 106100903 Oliver Kringle ND
19480105 108690448 Louie Brown KS
19641028 111180924 Alan Davies UT
19710227 112200747 Bella Napster OK
19730716 112550407 Roger Stone OR
19750716 111111111 Mary Stone OR
19570504 113070570 James Mitchell TX
19401023 113220519 Jilly Aston WY
19670607 114680858 Matt Vincent MI
*/


class Person
{
public:
    // ctor... (also default ctor with default values) //
    Person( int dob=0, int ssn=0, std::string fn="", std::string ln="", std::string st="" )
        : dob(dob), ssn(ssn), fname(fn), lname(ln), state(st) {}

    // re. 'ordering rule' for 'Person' objects ...
    bool operator < ( const Person& other ) const
    {
        if( lname != other.lname )
            return lname < other.lname;
        // else are the same ... so ...
        return fname < other.fname;
    }
    // re. search on names ...
    bool operator == ( const Person& other ) const
    {
        return lname == other.lname;
    }
private:
    int dob;
    int ssn;
    std::string fname;
    std::string lname;
    std::string state;
   
    // def'n of overloaded operator << for Person objects ...
    friend std::ostream& operator << ( std::ostream& os, const Person& per )
    {
        return os << std::left << std::setw(25) << per.lname + ", " + per.fname
                  << std::right << ' ' << per.state
                  << ' ' << per.dob << ' ' << per.ssn;
    }
    // to facilitate file input //
    friend std::istream& operator >> ( std::istream& is, Person& per )
    {
        is >> per.dob >> per.ssn >> per.fname >> per.lname >> per.state;
        return is;
    }
} ;


// load into (an empty) BSTree object, all records from file with name: fname
// BUT only load up to MAX elements //
bool load( const char* fname, BSTree< Person >& bst )
{
    std::ifstream fin( fname );
    if( fin )
    {
        Person tmp;
        while( fin >> tmp )
            bst.insert( tmp );
        fin.close();
        return true;
    }

    std::cout << "\nThere was a problem opening file "
              << fname << '\n';
    return false;
}

Person extractSearchInfo( const std::string& ans )
{
    std::string dummy, lname;
    std::istringstream iss( ans );
    iss >> dummy >> lname;
    return Person( 0, 0, "", lname );
}

std::string showMenuGetChoice()
{
    std::cout << MENU << "\nEnter your choice of line :  ";
    std::string line;
    getline( std::cin, line );
    return line;
}




int main()
{
    using std::cout; using std::string;
   
    BSTree< Person > tree;
    if( load( FNAME, tree ) )
    {
        cout << "There were " << tree.size() << " people in file '"
             << FNAME << "'\n";
             
        BSTree< Person >::Iterator it;
        for( it = tree.begin(); it != tree.end(); ++ it )
        {
            cout << *it << '\n';
        }
       
        for( ; ; )
        {
            char ch = 0;
            string ans = showMenuGetChoice();
            if( ans.size() ) ch = ans[0];
            Person tmp;
            switch( ch )
            {
                case 'f' : case 'F' : /* take in search info and search and report */
                    tmp = extractSearchInfo( ans );
                    if( tree.isItem( tmp, true ) ) // 'true' to show num checks //
                        cout << "Found and data on file is: "
                             << *tree.find( tmp ) << '\n';
                    else cout << "Not found.\n";
                break;
                case 'p' : case 'P' : /* talke in top of tree info and report (from there) */
                    tmp = extractSearchInfo( ans );
                    if( tree.isItem( tmp ) )
                    {
                        cout << "Found and tree (printed in order) from there is:\n";
                        tree.print_r( tree.findNode(tmp), cout, '\n' );

                    }
                    else cout << "Not found.\n";
                break;
                case 'x' : case 'X' :
                    return 0;
                break;
                default  : cout << "'" << ch << "' is NOT a valid entry here ...\n";
            }
        }
    }
}


And finally, the .h file ...

Code: [Select]
// BSTreeIterator.h //  // revised 2017-04-16 //

// this revision was on 2017-04-15 ...
// and was to make (most all) recursive methods PRIVATE
// since these meyhods are NOT to Be called by the user. //


// Using the C++ library stack in the following (nested) class iterator  ...

#ifndef BSTREEITERATOR_H
#define BSTREEITERATOR_H

#include <iostream>
#include <stack>


////////////////////////////////////////////////////////////
//
// // USAGE example:
//
// // constuct begin ('it') and end ('end') iterators:
// BSTree< objTYPE >::Iterator it = bst.begin(), end = bst.end();
//
// // print tree via *it and ++ it  ... till reach end:
// for( ; it != end ;  ++ it ) std::cout << *it << '\n';
//
////////////////////////////////////////////////////////////


template< typename T >
class BSTree
{
    // forward declaration ...
    class TreeNode;
public:
    // default ctor...
    BSTree() : root(0), len(0) {}

    // dtor...
    ~BSTree() { clean(); }
   
    void clean()
    {
std::cout << "Please wait a bit while the tree memory is freed up ... ";
        clean_r( root );

        root = 0;
        len = 0;
    }
   
    // copy ctor ... calls the recursive private method given below...
    BSTree( const BSTree& bst )
    {
        root = 0;
        len = 0;
        BSTree_r( root, bst.root );
    }

    // overloaded asignment ... calls the same recursive private method ...
    BSTree& operator = ( const BSTree& bst )
    {
        if( this != &bst )
        {
            clean(); // Note: sets root to 0 and len to 0 //
            BSTree_r( root, bst.root );
        }
        return *this;
    }

    void insert( const T& data )
    {
        insert_r( root, data ); // calls the private resursive method below ... //
        ++ len;
    }

    // A NON recursive search method ... //
    bool isItem( const T& data, bool show_count_steps = false ) const
    {
        // Return true if data is one of the items in the binary
        // sort tree to which root points.   Return false if not.
        TreeNode* cur = root;  // For "running" down the tree ...
                                    // start at the root node
        int count = 0; // so can count 'steps' ... and report if needed. //
        for( ; ; )
        {
            if( cur == 0 ) // We've fallen off the tree without finding data.
            {
                if( show_count_steps)
                    std::cout << "Number of tests was: " << ++count << '\n';
                return false;
            }
            else if( data == cur->data ) // We've found the data.
            {
                if( show_count_steps)
                    std::cout << "Number of tests was: " << ++count << '\n';
                return true;
            }
            else if( data < cur->data )
            {
                ++ count;
                // If the data occurs, it must be in the left subtree,
                // So, advance the runner down one level to the left.
                cur = cur->left;
            }
            else
            {
                ++ count;
                // If the data occurs, it must be in the right subtree.
                // So, advance the runner down one level to the right.
                cur = cur->right;
            }
        }  // end 'loop for ever' ... until return is reached //
    }
   
    TreeNode* findNode( const T& data )
    {
        return findNode( root, data ); // calls private method //
    }
   
   
    class Iterator
    {
    private:
        TreeNode* curNode;
        std::stack< TreeNode* > stkNodes;
    public:
        Iterator() : curNode(0) {}
       
        void set_curNode( TreeNode* tn ) { curNode = tn; }
       
        Iterator( TreeNode* binTree )
        {
            TreeNode* root = binTree;

            while( root )
            {
                stkNodes.push( root );
                root = root->left;
            }

            if( stkNodes.size() > 0 )
            {
                curNode = stkNodes.top();
                stkNodes.pop();
            }
            else
                curNode = 0;
        }

        T& operator * ()             { return curNode->data; }
        const T& operator * () const { return curNode->data; }


        bool operator == (const Iterator& other) const
        {
            return curNode == other.curNode;
        }

        bool operator != (const Iterator& other) const
        {
            return curNode != other.curNode;
        }

        Iterator& operator ++ ()
        {
            if( curNode->right )
            {
                stkNodes.push( curNode->right );

                if( curNode->right->left )
                    stkNodes.push( curNode->right->left );
            }

            if( stkNodes.empty() )
            {
                curNode = 0;
                return *this;
            }

            curNode = stkNodes.top();
            stkNodes.pop();

            return *this;
        }

        // Note that since, here, we are returning ONLY a copy,
        // this version does NOT permit records to be updated. //
        Iterator operator ++ ( int )
        {
            // NOTE this cpy here, i..e the correct way to implement POST ++ //
            Iterator cpy = *this;

            if( curNode->right )
            {
                stkNodes.push( curNode->right );

                if( curNode->right->left )
                    stkNodes.push( curNode->right->left );
            }

            if( stkNodes.empty() )
            {
                curNode = 0;
                return *this;
            }

            curNode = stkNodes.top();
            stkNodes.pop();
           
            return cpy;
        }
       
    } ; // END class Iterator //
   
    Iterator begin() { return Iterator( root ); }
    Iterator end() { return Iterator( 0 ); }
   
    Iterator find( const T& data )
    {
        Iterator tmp;
        tmp.set_curNode( findNode( root, data ) ); // calls the private method def'd below ... //
        return tmp;
    }
   
   
    //TreeNode* get_root() { return root; }

    size_t size() const { return len; }

/*
    size_t countNodes_r( const TreeNode< T >* cur ) const // recursive //
    {
        if( cur == 0 ) return 0;  // The tree is empty.  It contains no nodes.
        // else

        size_t count = 1;  // Start by counting the root.
        count += countNodes_r( cur->left) ;  // Add the number of nodes in the left subtree.
        count += countNodes_r( cur->right ); // Add the number of nodes in the right subtree.
        return count;  // Return the total.
    }
    size_t countNodes() const { return countNodes_r( root ); }
*/
    int maxDepth_r( const TreeNode* cur ) const
    {
        if( cur == 0 ) return 0;
        // else
       
        /* get depth of each subtree */
        int ld = maxDepth_r( cur->left );
        int rd = maxDepth_r( cur->right );

        /* return greater of two values + 1 */
        return ( ld > rd ? ld +1 : rd +1 );
    }
    int maxDepth() const // calls above method //
    {
        return maxDepth_r( root );
    }
   
    // print in order  ... used in main here so left here in public section ... //
    void print_r( const TreeNode* root, std::ostream& os = std::cout, char end = ' ' ) const
    {
        // The items in the left subtree are printed first, followed
        // by the data in the root node, followed by the items in
        // the right subtree.
        if( root == 0 )  return;         // there's nothing to print //

        print_r( root->left, os, end );  // Print items in left subtree.
        os << root->data << end;         // Print the root data.
        print_r( root->right, os, end ); // Print items in right subtree.
    }

    // print in order //
    void print( std::ostream& os = std::cout, char end = ' ' ) const
    {
        print_r( root, os, end );
    }
    void preorderPrint( std::ostream& os = std::cout, char end = ' ' ) const
    {
        preorderPrint_r( root, os, end );
    }
    void postorderPrint( std::ostream& os = std::cout, char end = ' ' ) const
    {
        postorderPrint_r( root, os, end );
    }

private:
    struct TreeNode
    {
        T data;           // The data in this node.
        TreeNode* left;   // Pointer to the left subtree.
        TreeNode* right;  // Pointer to the right subtree.
       
        // ctor...
        TreeNode( T data ) : data(data), left(0), right(0) {}
/*
        friend std::ostream& operator << ( std::ostream& os, const TreeNode& tn )
        {
            return os << tn.data;
        }
*/
    } ;

    TreeNode* root;
    size_t len;
   
    void clean_r( TreeNode* root )
    {
        if( root == 0 ) return;

        clean_r( root->left  );
        clean_r( root->right );
        delete root;
    }
   
    // Note ...traversing the passed in const bst in pre-order

    // Note that this recusive method is also called by
    // the overloaded assignment nelow //
    void BSTree_r( TreeNode*& nroot, const TreeNode* bstroot  )
    {
        if( ! bstroot ) return; // there's nothing to insert //

        insert( bstroot->data );           // insert the root data
        BSTree_r( nroot, bstroot->left );  // ...items in left subtree
        BSTree_r( nroot, bstroot->right ); // ... items in right subtree
    }
   
    // recursive method //
    void insert_r( TreeNode*& root, const T& data )
    {
        // Note that root is passed by reference since its value
        // can change in the case where the tree is empty.
        if( ! root )
        {
            // The tree is empty. Set root to point to a new node containing
            // the new data. This becomes the only node in the tree.

            root = new TreeNode( data );

            // NOTE: The left and right subtrees of root
            // are automatically set to 0 by the constructor.
            // This is important! !!! //

            return;
        }
        if( data < root->data )
            insert_r( root->left, data );
        else
            insert_r( root->right, data );
    }

    // A NON-recursive find ...
    // BUT!!! do NOT CHANGE, via this pointer,
    // the 'key' field(s) in the Mode !!! //
    TreeNode* findNode( TreeNode* cur, const T& data )
{
while( cur )
{
            if( data == cur->data )
                return cur;
if( data < cur->data )
cur = cur->left;
else
cur = cur->right;
}
return 0; // NOT found ... //
     }
     
    void preorderPrint_r( const TreeNode* root, std::ostream& os, char end ) const
    {
        if( root == 0 ) return;

        os << root->data << end; // Print the root data.
        preorderPrint_r( root->left, os, end );  // Print items in left subtree.
        preorderPrint_r( root->right ); // Print items in right subtree.
    }
    void postorderPrint_r( const TreeNode* root, std::ostream& os, char end ) const
    {
        if( root == 0 ) return;

        postorderPrint_r( root->left );  // Print items in left subtree.
        postorderPrint_r( root->right ); // Print items in right subtree.
        os << root->data << end;  // Print the root data.
    }
   
} ;

 #endif
6
C/C++ & Visual C++ / Re: Six Fast Steps to a simple template class Vector ...
« Last post by David on March 11, 2017, 06:59:04 AM »
Here in step 6, we add iterators ... and separate out our Vector class into its own .h file with suitable guards ...


So, firstly, a little test program ...

Code: [Select]
// Vector_6_iterators.cpp //  // 2017-03-10 //


// Here, in step 6, we add iterators ...
// Also, we separate out our class Vector into its own .h file
// with suitable guards //


#include "Vector.h" // includes <iostream>



// a little external print function to aid testing input/output ... //
template< typename T >
void print( const Vector< T >& v )
{
    using std::cout;
    typename Vector< T >::const_iterator it;
    for( it = v.begin(); it != v.end(); ++ it )
        cout << *it << ' ';
       
    cout << "\nThe size = " << v.size()
         << ", the capacity = " << v.capacity() << '\n';
}



int main()
{
    using std::cout;
   
    Vector< int > v, w;
    v.reserve(10);
    print( v );
   
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    v.shrink();
    cout << "After v.reserve(10) and 3 push_backs and calling v.shrink() ...\n";
    print( v );
   
    Vector< int > x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.resize(10);
    w.push_back( 9 );
    cout << "After calling w.resize(10) and w.push_back(9) ...\n";
    print( w );
   
    w.resize(6);
    cout << "After calling w.resize(6)...\n";
    print( w );

    w.resize(3);
    cout << "After calling w.resize(3)...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
   
    w.swap(v);
    cout << "After calling w.swap(v) ... print( w ) is ...\n";
    print( w );
    cout << "And print( v ) is ...\n";
    print( v );
}


And now, the file Vector.h needed above ...

Code: [Select]
// Vector.h //  // 2017-03-10 //

#ifndef VECTOR_2017_03_10_H
#define VECTOR_2017_03_10_H


#include <iostream>


const unsigned INIT_CAP = 2;

template< typename T >
class Vector
{
public:
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}

    // copy ctor ...
    Vector( const Vector< T >& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }

    // overloaded assignment ...
    Vector< T >& operator = ( const Vector< T >& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }

    // destructor ...
    ~Vector() { clear(); }

    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }

    void push_back( const T& val );

    void reserve( size_t );
    void resize( size_t );

    void swap( Vector& );
    void shrink();


    const T& operator [] ( size_t i ) const { return ary[i]; } // read only //

    // NOT const and returned by ref
    // so can set new values inside the vector //
    T& operator [] ( size_t i ) { return ary[i]; }

    size_t size() const { return len; }
    size_t capacity() const { return cap; }
   
    typedef T* iterator;
    iterator begin() { return ary; }
    iterator end() { return ary+len; }

    typedef const T* const_iterator;
    const_iterator begin() const { return ary; }
    const_iterator end() const { return ary+len; }

private:
    size_t len;
    size_t cap;
    T* ary;

    void enlarge();
} ;


// definitions //
template< typename T >
void Vector< T >::push_back( const T& val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}

template< typename T >
void Vector< T >::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;

    T* tmp = new int[cap]; // get enlarged memory //

    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //

    delete [] ary; // delete OLD array memory //

    ary = tmp; // update ary pointer to point to new memory ///
}

template < typename T >
void Vector< T >::reserve( size_t newCap )
{
    if( newCap > cap )
    {
        cap = newCap;
        T* tmp = new T[ cap ];
        for( size_t i = 0; i < len; ++i ) tmp[i] = ary[i];
        delete [] ary;
        ary = tmp; // update the base address of ary
    }
}

template < typename T >
void Vector< T >::resize( size_t newSize )
{
    if( newSize > len )
    {
        reserve( newSize );
        for( size_t i = len; i < cap; ++ i ) ary[i] = T();
        len = newSize;
    }
    else if( newSize < len )
        len = newSize;
}

template < typename T >
void Vector< T >::swap( Vector& vec )
{
    T* aryTmp  = vec.ary; // save start address
    size_t lenTmp = vec.len;
    size_t capTmp = vec.cap;

    vec.ary = ary;
    vec.len = len;
    vec.cap = cap;

    ary = aryTmp;
    len = lenTmp;
    cap = capTmp;
}

template < typename T >
void Vector< T >::shrink()
{
    if( len < cap )
    {
        T* tmp = new T[ len ]; // get 'right-sized' memory //
        for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i];
        delete [] ary; // now can delete old memory //
        ary = tmp; // update with the address of the new memory //
        cap = len;
    }
}

#endif


Also ... to get hints about how to add these methods

push
pop
back
empty

You can look here ...

class Vector ... and Stacks and Queues ...

http://developers-heaven.net/forum/index.php/topic,2622.0.html
7
C/C++ & Visual C++ / Re: Six Fast Steps to a simple template class Vector ...
« Last post by David on March 11, 2017, 06:43:54 AM »
Step 5 ... (again, please see comments in program ... and at the top ...)


Code: [Select]
// Vector_5_shrink_swap.cpp //  // 2017-03-10 //


// Here, in step 5, we add methods shrink and swap //


#include <iostream>


const unsigned INIT_CAP = 2;

template< typename T >
class Vector
{
public:
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}

    // copy ctor ...
    Vector( const Vector< T >& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }

    // overloaded assignment ...
    Vector< T >& operator = ( const Vector< T >& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }

    // destructor ...
    ~Vector() { clear(); }

    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }

    void push_back( const T& val );

    void reserve( size_t );
    void resize( size_t );
   
    void swap( Vector& vec );
    void shrink();

    const T& operator [] ( size_t i ) const { return ary[i]; } // read only //

    // NOT const and returned by ref
    // so can set new values inside the vector //
    T& operator [] ( size_t i ) { return ary[i]; }


    size_t size() const { return len; }
    size_t capacity() const { return cap; }

private:
    size_t len;
    size_t cap;
    T* ary;

    void enlarge();
} ;


// definitions //
template< typename T >
void Vector< T >::push_back( const T& val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}

template< typename T >
void Vector< T >::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;

    T* tmp = new int[cap]; // get enlarged memory //

    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //

    delete [] ary; // delete OLD array memory //

    ary = tmp; // update ary pointer to point to new memory ///
}

template < typename T >
void Vector< T >::reserve( size_t newCap )
{
    if( newCap > cap )
    {
        cap = newCap;
        T* tmp = new T[ cap ];
        for( size_t i = 0; i < len; ++i ) tmp[i] = ary[i];
        delete [] ary;
        ary = tmp; // update the base address of ary
    }
}

template < typename T >
void Vector< T >::resize( size_t newSize )
{
    if( newSize > len )
    {
        reserve( newSize );
        for( size_t i = len; i < cap; ++ i ) ary[i] = T();
        len = newSize;
    }
    else if( newSize < len )
        len = newSize;
}

template< typename T >
void Vector< T >::swap( Vector& vec )
{
    T* aryTmp  = vec.ary; // save start address
    size_t lenTmp = vec.len;
    size_t capTmp = vec.cap;

    vec.ary = ary;
    vec.len = len;
    vec.cap = cap;

    ary = aryTmp;
    len = lenTmp;
    cap = capTmp;
}

template< typename T >
void Vector< T >::shrink()
{
    if( len < cap )
    {
        T* tmp = new T[ len ]; // get 'right-sized' memory //
        for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i];
        delete [] ary; // now can delete old memory //
        ary = tmp; // update with the address of the new memory //
        cap = len;
    }
}


// a little external print function to aid testing input/output ... //
template< typename T >
void print( const Vector< T >& v )
{
    using std::cout;
   
    for( size_t i = 0; i < v.size(); ++ i )
        cout << v[i] << ' ';

    cout << "\nThe size = " << v.size()
         << ", the capacity = " << v.capacity() << '\n';
}




int main()
{
    using std::cout;
   
    Vector< int > v, w;
    v.reserve(10);
    print( v );
   
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    v.shrink();
    cout << "After v.reserve(10) and 3 push_backs and calling v.shrink() ...\n";
    print( v );
   
    Vector< int > x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.resize(10);
    w.push_back( 9 );
    cout << "After calling w.resize(10) and w.push_back(9) ...\n";
    print( w );
   
    w.resize(6);
    cout << "After calling w.resize(6)...\n";
    print( w );

    w.resize(3);
    cout << "After calling w.resize(3)...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
   
    w.swap(v);
    cout << "After calling w.swap(v) ... print( w ) is ...\n";
    print( w );
    cout << "And print( v ) is ...\n";
    print( v );
}
8
C/C++ & Visual C++ / Re: Six Fast Steps to a simple template class Vector ...
« Last post by David on March 09, 2017, 09:12:34 AM »
In step 4 ... (again please see comments at top of program)


Code: [Select]
// Vector_step4.cpp //  // 2017-03-10 //


// Here, in step 4, we add methods reserve and resize


#include <iostream>


const unsigned INIT_CAP = 2;

template< typename T >
class Vector
{
public:
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}

    // copy ctor ...
    Vector( const Vector< T >& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }

    // overloaded assignment ...
    Vector< T >& operator = ( const Vector< T >& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }

    // destructor ...
    ~Vector() { clear(); }

    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }

    void push_back( const T& val );

    void reserve( size_t );
    void resize( size_t );

    const T& operator [] ( size_t i ) const { return ary[i]; } // read only //

    // NOT const and returned by ref
    // so can set new values inside the vector //
    T& operator [] ( size_t i ) { return ary[i]; }


    size_t size() const { return len; }
    size_t capacity() const { return cap; }

private:
    size_t len;
    size_t cap;
    T* ary;

    void enlarge();
} ;


// definitions //
template< typename T >
void Vector< T >::push_back( const T& val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}

template< typename T >
void Vector< T >::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;

    T* tmp = new int[cap]; // get enlarged memory //

    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //

    delete [] ary; // delete OLD array memory //

    ary = tmp; // update ary pointer to point to new memory ///
}

template < typename T >
void Vector< T >::reserve( size_t newCap )
{
    if( newCap > cap )
    {
        cap = newCap;
        T* tmp = new T[ cap ];
        for( size_t i = 0; i < len; ++i ) tmp[i] = ary[i];
        delete [] ary;
        ary = tmp; // update the base address of ary
    }
}

template < typename T >
void Vector< T >::resize( size_t newSize )
{
    if( newSize > len )
    {
        reserve( newSize );
        for( size_t i = len; i < cap; ++ i ) ary[i] = T();
        len = newSize;
    }
    else if( newSize < len )
        len = newSize;
}




// a little external print function to aid testing input/output ... //
template< typename T >
void print( const Vector< T >& v )
{
    using std::cout;
   
    for( size_t i = 0; i < v.size(); ++ i )
        cout << v[i] << ' ';
       
    cout << "\nThe size = " << v.size()
         << ", the capacity = " << v.capacity() << '\n';
}



int main()
{
    using std::cout;
   
    Vector< int > v, w;
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    print( v );
   
    Vector< int > x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.reserve(10);
    w.push_back( 9 );
    cout << "After calling w.reserve(10) and w.push_back(9) ...\n";
    print( w );
   
    w.resize(6);
    cout << "After calling w.resize(6)...\n";
    print( w );

    w.resize(3);
    cout << "After calling w.resize(3)...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
}


A test to check-out a specific case of resize method ...


Code: [Select]
// Vector_4_test_resize.cpp //  // 2017-03-10 //


// Here, in step 4, we add specific test of resize //


#include <iostream>


const unsigned INIT_CAP = 2;

template< typename T >
class Vector
{
public:
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}

    // copy ctor ...
    Vector( const Vector< T >& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }

    // overloaded assignment ...
    Vector< T >& operator = ( const Vector< T >& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }

    // destructor ...
    ~Vector() { clear(); }

    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }

    void push_back( const T& val );

    void reserve( size_t );
    void resize( size_t );

    const T& operator [] ( size_t i ) const { return ary[i]; } // read only //

    // NOT const and returned by ref
    // so can set new values inside the vector //
    T& operator [] ( size_t i ) { return ary[i]; }


    size_t size() const { return len; }
    size_t capacity() const { return cap; }

private:
    size_t len;
    size_t cap;
    T* ary;

    void enlarge();
} ;


// definitions //
template< typename T >
void Vector< T >::push_back( const T& val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}

template< typename T >
void Vector< T >::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;

    T* tmp = new int[cap]; // get enlarged memory //

    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //

    delete [] ary; // delete OLD array memory //

    ary = tmp; // update ary pointer to point to new memory ///
}

template < typename T >
void Vector< T >::reserve( size_t newCap )
{
    if( newCap > cap )
    {
        cap = newCap;
        T* tmp = new T[ cap ];
        for( size_t i = 0; i < len; ++i ) tmp[i] = ary[i];
        delete [] ary;
        ary = tmp; // update the base address of ary
    }
}

template < typename T >
void Vector< T >::resize( size_t newSize )
{
    if( newSize > len )
    {
        reserve( newSize );
        for( size_t i = len; i < cap; ++ i ) ary[i] = T();
        len = newSize;
    }
    else if( newSize < len )
        len = newSize;
}




// a little external print function to aid testing input/output ... //
template< typename T >
void print( const Vector< T >& v )
{
    using std::cout;

    for( size_t i = 0; i < v.size(); ++ i )
        cout << v[i] << ' ';

    cout << "\nThe size = " << v.size()
         << ", the capacity = " << v.capacity() << '\n';
}




int main()
{
    using std::cout;
   
    Vector< int > v, w;
    v.resize(10);
    print( v );
   
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    print( v );
   
    Vector< int > x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.reserve(10);
    w.push_back( 9 );
    cout << "After calling w.reserve(10) and w.push_back(9) ...\n";
    print( w );
   
    w.resize(6);
    cout << "After calling w.resize(6)...\n";
    print( w );

    w.resize(3);
    cout << "After calling w.resize(3)...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
}
9
C/C++ & Visual C++ / Re: Six Fast Steps to a simple template class Vector ...
« Last post by David on March 09, 2017, 09:10:04 AM »
In step 3 ... (again, please see comments at top of program)


Code: [Select]
// Vector_step3.cpp //  // 2017-03-10  //


// Here, in step 3, we do simple and fairly straight-foward
// update to a template class //



#include <iostream>

using namespace std;

const unsigned INIT_CAP = 2;

template< typename T >
class Vector
{
    size_t len;
    size_t cap;
    T* ary;
public:
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}
   
    // copy ctor ...
    Vector( const Vector< T >& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }
   
    // overloaded assignment ...
    Vector< T >& operator = ( const Vector< T >& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }
   
    // destructor //
    ~Vector() { clear(); }
   
    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }
   
    void push_back( const T& val );
    void enlarge();
   
    const T& operator [] ( size_t i ) const { return ary[i]; } // read only //
   
    // NOT const and returned by ref
    // so can set new values inside the vector //
    T& operator [] ( size_t i ) { return ary[i]; }
   
    size_t size() const { return len; }
    size_t capacity() const { return cap; }
} ;


// definitions //
template< typename T >
void Vector< T >::push_back( const T& val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}
template< typename T >
void Vector< T >::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;
   
    T* tmp = new int[cap]; // get enlarged memory //
   
    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //
   
    delete [] ary; // delete OLD array memory //
   
    ary = tmp; // update ary pointer to point to new memory //
}


// a little external print function to aid testing input/output ... //
template< typename T >
void print( const Vector< T >& v )
{
    for( size_t i = 0; i < v.size(); ++ i )
        cout << v[i] << ' ';
       
    cout << "\nThe size = " << v.size()
         << ", the capacity = " << v.capacity() << '\n';
}



int main()
{
    Vector< int > v, w;
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    print( v );
   
    Vector< int > x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
}
10
C/C++ & Visual C++ / Re: Six Fast Steps to a simple template class Vector ...
« Last post by David on March 09, 2017, 09:07:43 AM »
In step 2 we ... (please see comments in program at top)


Code: [Select]
// Vector_step2.cpp //  // 2017-03-09 //


// Here, in step 2,
// we add "BIG THREE" needed when you use new memory
// 1) destructor ... (that calls a clear method)
// and 2) copy ctor
// and 3) overloaded assignment //


#include <iostream>

using namespace std;

const unsigned INIT_CAP = 2;

struct Vector
{
    size_t len;
    size_t cap;
    int* ary;
   
    // default ctor ...
    Vector() :len(0), cap(0), ary(0) {}
   
    // copy ctor ...
    Vector( const Vector& v )
    {
        len = v.len;
        cap = v.cap;
        ary = new int[ cap ];
        for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
    }
   
    // overloaded assignment ...
    Vector& operator = ( const Vector& v )
    {
        if( this != &v ) // if NOT same addresses //
        {
            delete [] ary; // since NOT same memory can now do this //

            len = v.len;
            cap = v.cap;
            ary = new int[ cap ];
            for( size_t i = 0; i < len; ++ i ) ary[i] = v.ary[i];
        }
        return *this;
    }
   
    // destructor //
    ~Vector() { clear(); }
   
    void clear()
    {
        delete [] ary;
        cap = len = 0;
        ary = 0; // this fix clears up case of calling destructor after calling clear //
    }
   
    void push_back( int val );
    void enlarge();
   
    int operator [] ( size_t i ) const { return ary[i]; }
   
    // so can set new values in vector //
    int& operator [] ( size_t i ) { return ary[i]; }
} ;


// definitions //

void Vector::push_back( int val )
{
    if( len == cap ) enlarge();
    ary[len] = val;
    ++ len;
}

void Vector::enlarge()
{
    if( cap ) cap += cap; // it gets doubled if had a value
    else cap = INIT_CAP;
   
    int* tmp = new int[cap]; // get enlarged memory //
   
    for( size_t i = 0; i < len; ++ i ) tmp[i] = ary[i]; // copy over //
   
    delete [] ary; // delete OLD array memory //
   
    ary = tmp; // update ary pointer to point to new memory //
}




// a little test ... //
void print( const Vector& v )
{
    for( size_t i = 0; i < v.len; ++ i )
        cout << v[i] << ' ';
       
    cout << "\nThe len = " << v.len
         << ", the cap = " << v.cap << '\n';
}


int main()
{
    Vector v, w;
    v.push_back( 6 );
    v.push_back( 7 );
    v.push_back( 8 );
   
    print( v );
   
    Vector x(v); // calling copy ctor //
    cout << "After calling Vector x(v) ...\n";
    print( x );
   
    w = x; // call overloaded assignemnt //
    cout << "After calling w = x ...\n";
    print( w );
   
    w.clear();
    cout << "After calling w.clear() ...\n";
    print( w );
   
   
}
Pages: [1] 2 3 ... 10