Thursday, July 30, 2009

C++ vector help please?

i'm pretty sure it's simple but i was not in class for 3 days due to an early spring break. i got sent the stuff we did so i need to write the program of the executable file








i'm a little confused as to how to do vectors..like...let's say for vector 1. it's an int vector or whatever...so...the exectuable file asks what size u want it to be. and what the filler value will be. so far....at the top i have








int a;


int b;


vector%26lt;int%26gt;one(a,b);


cin%26gt;%26gt;a;


cin%26gt;%26gt;b;








is that the correct way to do it??








and also. for let's say for vector 2, it's a string vector..idk how u would get the user to enter in something?








so far i have








string a;


string b;


vector%26lt;string%26gt;two(a,b);


cout%26lt;%26lt;"What will be the size of vector 2? ";


getline(cin,a);


cout%26lt;%26lt;"What will be the filler value for vector 2? ";


getline(cin,b);











but i know that's not right...could someone help me correct it. and also how do u get the vectors to print?

C++ vector help please?
So, it helps to think out what you are doing rather than guessing with code.





int a;


int b;


// Ok so you have two integers.


vector%26lt;int%26gt;one(a,b);


// So, now you create a vector. Wait a minute, what is a and b though?


cin%26gt;%26gt;a;


cin%26gt;%26gt;b;


// So you create a vector with a and b first, and *then* you take inputs for a and b? Huh? Shouldn't you be inputting the values of a and b first?





Same thing in your second example. You create the vector first, and then ask for inputs? Hey, it's top down. Line 1 comes first, line 2 comes next, line 3 comes after that. If you have code to create a vector, and you have it on an earlier line, guess what happens...
Reply:Okay, so I am assuming that your vector is just an abstract datastructure for making a fancy array.





The way you use the vector datastructure is like this:





vector%26lt;type%26gt;name(length, preset value);





So you need to declare your a and b values before you call the structure. Right now you are declaring vectors of undefined length a with a default value of undefined b. Those values are whatever they were the last time that piece of memory was used. So basically they are full of bad data.





If you want to dynamically allocate memory, you need to use malloc or calloc. But in C++ you can just use "new."





So you could type:





int a = 0;


int *array;





cout%26lt;%26lt;"How long do you want your int array to be? ";


cin%26gt;%26gt;a;


array = new a*(sizeof int);





But when you use new you have to do a delete later.





fortunately, C++ keeps track of the length, so you can just do





delete [] array; after you are done with the array to clean up in the end.


No comments:

Post a Comment