Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › C++ and dynamic arrays
New Posts  All Forums:Forum Nav:

C++ and dynamic arrays - Page 2

post #11 of 21
Quote:
Originally Posted by KingAroan View Post


What does .push_back() do?


It adds an item to the end of the array.

 

I suspect you're not really getting your money's worth from this class.

Underground
(14 items)
 
  
CPUMotherboardGraphicsRAM
Core i7 920 C0 ASUS P6T6 WS Revolution GTX 460 TR3X6G1600C8D 
Hard DriveOptical DriveCoolingOS
WD1001FALS SAMSUNG SH-S223F 22X DVD MULTI Corsair H50 Fedora 16 KDE x86_64 
MonitorKeyboardPowerCase
HP w19b Microsoft Comfort Curve Corsair CX600 Thermaltake Armor VA8003BWS 
MouseMouse Pad
Razer DeathAdder Black 
  hide details  
Reply
Underground
(14 items)
 
  
CPUMotherboardGraphicsRAM
Core i7 920 C0 ASUS P6T6 WS Revolution GTX 460 TR3X6G1600C8D 
Hard DriveOptical DriveCoolingOS
WD1001FALS SAMSUNG SH-S223F 22X DVD MULTI Corsair H50 Fedora 16 KDE x86_64 
MonitorKeyboardPowerCase
HP w19b Microsoft Comfort Curve Corsair CX600 Thermaltake Armor VA8003BWS 
MouseMouse Pad
Razer DeathAdder Black 
  hide details  
Reply
post #12 of 21
ok lets say i have a bunch of random integers like this in a text file...
Code:
1 2 5 9 9
2 3 8 4 0
2 4 2
20 398 28 1938 3
4921 394 

you have no idea how many integers there are...but you know there are integers separated by a white space...so do something like this
Code:
#include <fstream>  
#include <iostream> 
#include <string> 

using namespace std;  

int main(){

        ifstream file;
        file.open("digits.txt");
        string holder;
        int total = 0;
        while(file >> holder)  //determine the amount of ints or storage for the dynamic array
             ++total;

        file.close();

        file.open("digits.txt");  //reopen file from beginning to store ints into dynamic array

        int *p = new int[total]; //memory allocated for dynamic array
        
        int i = 0;
        while(file >> holder){
     
                 p[i] = atoi(holder.c_str()); //ints stored one by one to the end of the file...string converted to int value using atoi function
                 cout << "p[" << i << "] = " << p[i] << endl; //print elements of array
                 ++i;
        }

         return 0;
}

when it prints to the console it should look something like this
Code:
p[0] = 1
p[1] = 2
p[2] = 5
p[3] = 9
p[4] = 9
p[5] = 2
p[6] = 3
p[7] = 8
p[8] = 4
p[9] = 0
p[10] = 2
p[11] = 4
p[12] = 2
p[13] = 20
p[14] = 398
p[15] = 28
p[16] = 1938
p[17] = 3
p[18] = 4921
p[19] = 394


I actually just tested it...works perfectly for the situation explained above...when only ints are present in the text file. Your teacher is pretty pathetic...if I saw a student going above and beyond what I expected I would be elated.
Edited by surfbumb - 11/18/11 at 1:29pm
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
post #13 of 21
So is the task to create an expandable array, or do you simply need one to complete the assignment?

If its just a means to an end use vectors as FiX pointed out. They function the same as arrays, and are the same performance wise (except when resizing).

You should really only handle resizeable arrays yourself if you're coding in pure C, since C++ without the STL is like a car without a steering wheel.

Here's a more fleshed out example demonstrating vectors:
Code:
#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
        vector<int> myVector;
        myVector.resize(50);

        for(unsigned int i = 0; i < myVector.size(); i++)
        {
                myVector[i] = i;
        }
        
        myVector.push_back(myVector.size());
        myVector.push_back(myVector.size());
        myVector.push_back(myVector.size());
        
        for(unsigned int i = 0; i < myVector.size(); i++)
        {
                cout << myVector[i] << ' ';
        }
        cout << endl;
        
        return 0;
}

You can see how vector elements are accessed using square brackets [ ] just like normal arrays are, and if you use the resize() function can be used in the exact same way as arrays.

But the key difference is they are expandable. If you try to add an element to a full array it will silently resize.


Here's my hackish C attempt at the same thing:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv)
{
        int size = 0;
        int maxsize = 50;
        int * array = malloc(sizeof(int) * maxsize);
        
        int i;
        for(i = 0; i < 120; i++)
        {
                if(i < maxsize) { 
                        array[i] = i;
                        size++;
                } else {
                        maxsize += 50;
                        int  * temparray = malloc(sizeof(int) * size);
                        memcpy(temparray,array,sizeof(int)*size);
                        
                        array = (int *)malloc(sizeof(int)*(maxsize));
                        memcpy(array,temparray,sizeof(int)*size);
                        free(temparray);
                        
                        array[i] = i;
                        size++;
                }
        }
        
        for(i = 0; i < size; i++)
                printf("%d ",array[i]);
        printf("\n");
        
        free(array);
        
        return 0;
}


Arrays in C are fixed size, and unmovable, so resizing arrays in C is actually impossible. What you have to do instead is allocate a chunk of memory and slap a sign on it that says "this be an array of ints, and I'll gut the man that do say otherwise". Unfortunately that leaves you with a block of memory to manage, since C lacks garbage collection (hence the calls to free())
    
CPUMotherboardGraphicsRAM
Core i5 4670k ASUS Maximus VI Gene Gigabyte GTX 460 1GB Kingston Hyper-X 
Hard DriveHard DriveHard DriveHard Drive
Samsung 830 OCZ Vertex 3 WD6401AALS WD5000AAKS 
CoolingOSMonitorMonitor
Noctua NH-D14 elementary OS Dell Ultrasharp U2312HM LG W2442PA-BF 
KeyboardPowerCaseMouse
Microsoft Sidewinder X4 Corsair HX750W Corsair Graphite 600T Logitech G700 
Audio
ASUS Xonar DG 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
Core i5 4670k ASUS Maximus VI Gene Gigabyte GTX 460 1GB Kingston Hyper-X 
Hard DriveHard DriveHard DriveHard Drive
Samsung 830 OCZ Vertex 3 WD6401AALS WD5000AAKS 
CoolingOSMonitorMonitor
Noctua NH-D14 elementary OS Dell Ultrasharp U2312HM LG W2442PA-BF 
KeyboardPowerCaseMouse
Microsoft Sidewinder X4 Corsair HX750W Corsair Graphite 600T Logitech G700 
Audio
ASUS Xonar DG 
  hide details  
Reply
post #14 of 21
Thread Starter 
It needs to be an array

alright I got some help from a friend that is in a higher level programming class and he helped me understand a little bit and got me doing it, a little I guess. But Surfbumb your code with the explanations helped out a lot also.

Since I am new to pointers and stuff here is my code it is working 100% currently but was wondering if there is anything I should change or move around to clean it up. Also not sure if I am using all my variables that I declared, so if you see one that was added while my friend was helping me out, please let me know.
Code:
//Aaron Sullivan
//CSCI 111, Fall 2011
//Lab36a - Review for Exam 3

//LIBRARIES
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

//CONSTANT DECLARATIONS THROUGH THE PROGRAM
const string ID = "Aaron Sullivan - CSCI 111, Fall 2011 - Lab36a";

//PROTOTYPES TO CHECK IF THE NUMBER IS EVEN OR ODD, AND WHAT THOUSANDS IT BELONGS TO
void EvenOrOdd (int newNumber, ofstream& fout);
void ThousandsGroup (int newNumber, ofstream& fout);

int main()
{
        //DECLARATIONS
        ofstream fout;
        ifstream fin;
        char    exit;
        int             inputNumber,
                        count,
                        singleDigit,
                        amountOfNumbers,
                        *numberArray,
                        temp,
                        arraysize = 0;
        
        //ADMINISTRATIVE
        cout << "Running lab36a . . . " << endl;
        cout << ID << endl << endl;
        fout.open ("Aaron Sullivan - CSCI 111, Fall 2011 - Lab36a.out");
        fin.open ("Lab36a.dat");
        fout << ID << endl << endl;

        //CHECKS FOR AN INPUT FILE
        if (!fin)
        {
                cout << "Could not open the input file" << endl << endl;
                fout << "Could not open the input file" << endl << endl;
                cout << "ERROR:  Press any key then enter to exit the program:  ";
                cin >> exit;
                return 1;
        }
        
        //CHECKS HOW MANY NUMBERS ARE IN THE FILE TO CREATE THE SIZE OF THE ARRAY
        for (count = 0; fin >> inputNumber; count ++)
        {
                //VALIDATES DATA SO THAT THE ARRAY IS NOT TO LARGE
                if (inputNumber <= -9999 || inputNumber >= 9999)
                {
                        cout << "ERROR: Number out of range:  " << inputNumber << endl;
                        count --;
                        continue;
                }
        
                while (fin >> temp)
                        arraysize ++;
        }

        numberArray = new int [arraysize];              //Sets the arrays size depending on how many intergers in file

        //CLOSED INPUT FILE, THEN REOPENS INPUT TO READ DATA AGAIN, VERIFY THAT INPUT FILE WAS OPENED.
        fin.close ();
        fin.open ("Lab36a.dat");
        if (!fin)
        {
                cout << "Could not open the input file" << endl << endl;
                fout << "Could not open the input file" << endl << endl;
                cout << "ERROR:  Press any key then enter to exit the program:  ";
                cin >> exit;
                return 1;
        }

        //REVERIFIES DATA, STORES NUMBERS INTO THE ARRAY
        for (count = 0; fin >> inputNumber; count ++)
        {
                if (inputNumber <= -9999 || inputNumber >= 9999)
                {
                        cout << "ERROR: Number out of range:  " << inputNumber << endl;
                        count --;
                        continue;
                }
        
                numberArray[count] = inputNumber;
                
                //SEPARATES FOR DIGITS
                fout << setw (7) << " " << "the digits of " << setw(5) << inputNumber << " are:  ";
                while (inputNumber)
                {
                        singleDigit = inputNumber % 10;
                        fout << "  " << singleDigit << " ";
                        inputNumber = inputNumber / 10;
                }
                fout << endl;
        }

        amountOfNumbers = count;

        //RUNS FUNCTIONS TO FIND IF THE NUMBER IN THE ARRAY IS EVEN OR ODD, AND CHECKS THOUSANDS
        fout << endl << endl;
        for (count = 0; count < amountOfNumbers; count ++)
        {
                EvenOrOdd (numberArray[count], fout);
                ThousandsGroup (numberArray[count], fout);
        }


        //EXIT
        cout << endl << "Press any key then enter to exit the program:  ";
        cin >> exit;
        return 0;
}


void EvenOrOdd (int newNumber, ofstream& fout)
//FUNCTION TO CHECK IF THE INTERGER IS EVEN OR ODD
{
        if (newNumber % 2 == 0)
                fout << newNumber << " is an even number" << endl;
        else if (newNumber % 2 == 1)
                fout << newNumber << " is an odd number" << endl;
}

void ThousandsGroup (int newNumber, ofstream& fout)
//FUNCTION TO CHECK WHAT THOUSANDS THE INTERGER BELONGS TO
{

        fout << newNumber;
        newNumber = newNumber / 1000;

        switch (newNumber)
        {
                case 0:
                        fout << " is less than a thousand" << endl << endl;
                        break;
                case 1:
                        fout << " belongs to the one thousands" << endl << endl;
                        break;
                case 2:
                        fout << " belongs to the two thousands" << endl << endl;
                        break;
                case 3:
                        fout << " belongs to the three thousands" << endl << endl;
                        break;
                default:
                        fout << " is greater than 3999" << endl << endl;
        }
}

Thanks for all the help guys Rep going out to all that helped out, or gave me good information that I can use for a later date, like the vectors.

Sent from my Broodcomb using Tapatalk
Edited by KingAroan - 11/19/11 at 12:59am
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
post #15 of 21
Thread Starter 
Quote:
Originally Posted by error10 View Post



Quote:
Originally Posted by KingAroan View Post


What does .push_back() do?


It adds an item to the end of the array.

 

I suspect you're not really getting your money's worth from this class.


I would agree with you on that

Where would I need to delete[ ] from? Because it works perfectly as it is, but I think it was surfbumb that said I needed to do it.

Also @surfbumb I agree with you about my teacher being pathetic, he claims that he is preparing us for the future where apparently nothing is good enough. One of our projects after the first exam was to compare two dates to see which one was older. The teacher told us to validate our data with the minimum of days don't go above 31, months are between 1 and 12, and years are positive. I verified the data all the way through leap years where February has 28 or 29, months 1, 3, 5, 7, 8, 10, 12 have 31 days and months 2, 4, 6, 9, 11 have 30 days. Did a lot of extra work, he complained because it was more for him to grade. Since then he has started putting in bold print ONLY VALIDATE USING: and then the parameters. So its kinda funny

Sent from my Broodcomb using Tapatalk
Edited by KingAroan - 11/19/11 at 1:41am
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
post #16 of 21
whenever you are done using your dynamic array deallocate memory tied to it. In short, whenever you use the keyword "new" you need a corresponding "delete".

this will be the last statement in main...right before "return 0".
Code:
delete [] numberArray;

I'd recommend during your break to look into "classes", "objects", "pointers", "constructors", "destructors". If you get these down before your 200 level programming course, you will be way ahead of the game...unless of course you already know them.
Edited by surfbumb - 11/19/11 at 10:10am
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
post #17 of 21
Thread Starter 
Quote:
Originally Posted by surfbumb View Post

whenever you are done using your dynamic array deallocate memory tied to it. In short, whenever you use the keyword "new" you need a corresponding "delete".

this will be the last statement in main...right before "return 0".
Code:
delete [] numberArray;

I'd recommend during your break to look into "classes", "objects", "pointers", "constructors", "destructors". If you get these down before your 200 level programming course, you will be way ahead of the game...unless of course you already know them.

Thanks for the help and valuable information, I will look into those this week.

Sent from my Broodcomb using Tapatalk
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
post #18 of 21
Once you feel you have a good grip on all those, consider reading Effective C++ and More Effective C++, while testing out the good practices mentioned (or you'll forget everything you read). The tips mentioned in the book are essential for writing good C++ code. Games that crash are games whose programmers didn't follow those tips.
Akiyama Mio
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6420 @ stock, 0.98v Asus P5N-E SLI Gainward GTX 460 1GB @ 800/1600/1900 2x2GB Kingston @ 800MHz 5-5-5-15 2T 
Hard DriveOptical DriveOSMonitor
WD 250GB, 320GB SATA/3, 16MB Cache, Seagate 1TB LG GSA-H62N 18x SATA Ubuntu 9.10 x86 & Win7 x86 Asus VW222U 
KeyboardPowerCase
Logitech Classic Corsair 650HX NZXT Apollo Black 
  hide details  
Reply
Akiyama Mio
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6420 @ stock, 0.98v Asus P5N-E SLI Gainward GTX 460 1GB @ 800/1600/1900 2x2GB Kingston @ 800MHz 5-5-5-15 2T 
Hard DriveOptical DriveOSMonitor
WD 250GB, 320GB SATA/3, 16MB Cache, Seagate 1TB LG GSA-H62N 18x SATA Ubuntu 9.10 x86 & Win7 x86 Asus VW222U 
KeyboardPowerCase
Logitech Classic Corsair 650HX NZXT Apollo Black 
  hide details  
Reply
post #19 of 21
Thread Starter 
Quote:
Originally Posted by Coma View Post

Once you feel you have a good grip on all those, consider reading Effective C++ and More Effective C++, while testing out the good practices mentioned (or you'll forget everything you read). The tips mentioned in the book are essential for writing good C++ code. Games that crash are games whose programmers didn't follow those tips.

Do you know of where I can get those books for cheap or free online legally?

Sent from my Broodcomb using Tapatalk
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
2600K Sandy Bridge 5+Ghz ASUS P8P67 DELUXE x2 EVGA GTX 580 Water Cooled in SLI G.SKILL Ripjaws X Series 16GB 1600 
OSMonitorPowerCase
Duel Boot, Win 7 & Unbuntu 2 x 24in monitors Plus a 1080p projector CORSAIR Professional Series Corsair 600T 
  hide details  
Reply
post #20 of 21
Quote:
Originally Posted by Coma View Post

Once you feel you have a good grip on all those, consider reading Effective C++ and More Effective C++, while testing out the good practices mentioned (or you'll forget everything you read). The tips mentioned in the book are essential for writing good C++ code. Games that crash are games whose programmers didn't follow those tips.

Not necessarily... Most programmers try their hardest not to have bugs but sometimes its quite hard to not have them.
    
CPUMotherboardGraphicsGraphics
FX-8350 Asus Crosshair V MSI GTX460 Hawk 1gb MSI GTX460 Hawk 1gb 
RAMHard DriveHard DriveHard Drive
Kingston HyperX 8gb (2x4gb) Crucial M4 64GB Samsung F3 1TB Western Digital 320GB 
CoolingOSMonitorMonitor
Custom WC Windows 7 Ultimate X64 Dell E2311H Dell E2311H 
MonitorKeyboardPowerCase
LH 23EN43 Ducky Year of the Dragon 2012 SilverStone Strider 1000W-P Corsair 800D 
Audio
Asus Xonar Essence STX 
  hide details  
Reply
    
CPUMotherboardGraphicsGraphics
FX-8350 Asus Crosshair V MSI GTX460 Hawk 1gb MSI GTX460 Hawk 1gb 
RAMHard DriveHard DriveHard Drive
Kingston HyperX 8gb (2x4gb) Crucial M4 64GB Samsung F3 1TB Western Digital 320GB 
CoolingOSMonitorMonitor
Custom WC Windows 7 Ultimate X64 Dell E2311H Dell E2311H 
MonitorKeyboardPowerCase
LH 23EN43 Ducky Year of the Dragon 2012 SilverStone Strider 1000W-P Corsair 800D 
Audio
Asus Xonar Essence STX 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › C++ and dynamic arrays