Saturday, May 9, 2009

Constructors and C array question in C++?

How can I take a type I've created and initalize it with a C string or character array?





ex:








MyType x("initalize to this char array");








How can I make this legal?





MyType::MyType(char ar[])


:


{


for(int i = 0; i %26lt; (sizeof(ar)/sizeof(ar[0])); ++i){


private_member_array[i] = ar[i];


};





}











So basically,





What would be the parameter in my constructor, to make it legal to pass it char array's in the form of:





MyType("data for my type");





Thanks!

Constructors and C array question in C++?
A working anwer:-





#include %26lt;iostream%26gt;


#include "MyType.h"


int main (int argc, char * const argv[])


{


MyType* mt = new MyType("data for my type");


std::cout %26lt;%26lt; char(mt-%26gt;pm_array[0]);


return 0;


}





// header MyType.h


class MyType


{


public:


int pm_array[];


MyType(char ar[]);


};





#include "MyType.h"


MyType::MyType(char ar[])


{


for(int i = 0; i %26lt; (sizeof(ar)/sizeof(ar[0])); ++i)


{


pm_array[i] = ar[i];


}


}
Reply:There are different ways to do it.


First could be use char*. (include string.h)





class MyType {


private:


char *private_str;


public:


MyType();


MyType(char*);


~MyType();


}





MyType::MyType() {


private_str = NULL;


};


MyType::MyType(char* str) {


private_str = new char[strlen(str)];


strcpy(private_str,str);


};


//Helps to free memory on destruction.


MyType::~MyType() {


if (private_str) delete private_str;


};





Another way could be to use string. (include string)





class MyType {


private:


std::string private_str;


public:


MyType(std::string%26amp;);





}





MyType::MyType(std::string %26amp;str) {


private_str = str;


};





I hope this helps!!
Reply:Templates
Reply:The correct argument to the constructor is either a character array (as you did) or a character pointer. If you have a character array, use strcpy to copy from the literal to the array. If you have a pointer, you can use assignment.





See http://c-faq.com/decl/autoaggrinit.html . http://cppreference.com/





Take note that if you use a pointer, you can't modify the string contents. But you can with an array.
Reply:I think you're looking for





MyType::MyType (const char * text)





Note that I strongly recommend to use std::string for the internal storage of the string. Handles the classical zero terminated string issues of overruns, memory allocation, concatenation much more pleasantly that C strings.

daisy

Urgent C++ array sorting question?

I have to create a C++ program that has one main function and one void function. "sortof" must be the void function's name. the void function has 2 arguements, which are both 1-D arrays of length 4. the main program asks the user for 4 different numbers. these are stored in one of the arrays. the function is then called and it sorts the numbers form smallest to biggest in the second array. the main program then prints both the input array and the sorted array to the screen. As far as sorting goes, i'm lost. it says i'm supposed to just determine the max, the nin and then do the same for the two left behind. HELP PLEASE!!!

Urgent C++ array sorting question?
I have a quicksort function on my website. It is easy and can be implemented in your code





iamtruancy.co.nr


Navigate to c++, click the link "median" or "mode"





void ord(int size){





int i, j;





//test original number against all





for (i = 0; i %26lt; size; i++){





for (j = i + 1; j %26lt;= size; j++){





//arr is your array


//if new number is bigger than swap them





if ( arr[j] %26gt; arr[i] )





swap(arr[j], arr[i]);}





//show array





cout %26lt;%26lt; endl %26lt;%26lt; arr[i]; }}
Reply:I do not under stand where you are stuck at. Did you get the arrays to work? Or are you stuck on that? If you need any help go on google and search for "C++ Array Functions" and you should get some help.
Reply:void sortof(double f[], double s[] ,int size)//u need to pass size also


{


int temp;


//copy the original array


for(int i=0;i%26lt;size;i++)


s[i]=f[i];


for(int i=0;i%26lt;size-1;i++)


{


if(s[i]%26gt;s[i+1])


{


temp=s[i];


s[i]=s[i+1];


s[i+1]=temp;


}


}











}


thats it





after calling sort of function





display min=s[0]


max=s[size-1]





that s all
Reply:sounds like you need to implement a sorting function, unless you can use the standard qsort method in C.





google "quick sort" and "insertion sort" to get started on that.


C++ array programming. Please help and/or assist!?

I'm currently trying to develop an array class that addresses some of the shortcomings of the standard C++ array implementation.





The file has functions for an array. I'm having trouble coding correct functions. Please help





public Array(int); //Constructor that uses the passed integer to set the size of the array.





public Array(int, double); //constructor that uses the passed integer to set the size of the array and initializes all elements to the passed double value





public SetData(int, double); //sets the int-th element to the value of the passed double.





I'm currently working on this, but these are giving me the most problems. Any advice or help is GREATLY appreciated. Any snippets of codes or comment lines are greatly appreciated as well.

C++ array programming. Please help and/or assist!?
okay, I won't give you an array, but think on this:





file TestClass.h





class test


{


public:


test(); //default constructor


test(int i); constructor that takes an integer


};





file test.cpp





#include %26lt;iostream%26gt;


#include %26lt;test.h%26gt;





test::test()


{


std::cout %26lt;%26lt; "default constructor" %26lt;%26lt; std::endl;


} //implementation of default constructor


test::test(int i)


{


std::cout %26lt;%26lt;"constructor with int" %26lt;%26lt; std::endl;


std::cout %26lt;%26lt; i %26lt;%26lt; std::endl;


}





file main.cpp





#include %26lt;iostream%26gt;


#include %26lt;test.h%26gt;





int main(int argc, char* argv[])


{


test t;


test t2( 3);





test *pt = new test(3);


test *pt1 = new test();





delete pt;


delete *pt1;


}


C++ array question - "removing" an item from an array?

If I had an array in C++, with a capacity of 10 items but only 5 items in the array, and I wanted to remove the item located at position 2 in the array...how would I go about doing that?





I just don't know the syntax...I know that to delete an entire array, you would type:





delete [] array;





But for just deleting one item, you can't do something like:


delete array[2];





So how would I go about removing that item? Just set it to zero and move everything else over to fill the gap (putting a zero in the last occupied location of the array), use the null factor or what?

C++ array question - "removing" an item from an array?
Depending on what you want to acheive, resorting an array maybe a waste of time. Array are not the best data structure to insert and delete. Depending on how often you gonna do this operation and the size of your array, this might not be a good idea performence wise.





I usually give a null value to the value I want out and ignore it whenever I browse through the array. If you intend to add and delete stuff from your array very often, your maybe better off with a chained list.
Reply:First delete [] array is only to be used to delete an array created with new [] array. If you want to remove an element from a static array then you will have to copy the remaining elements to the one you wish to remove. For example





int array[10];


//Assume elements placed into array


for (int i(2); i %26lt; 9; ++i)


array[i] = array[i + 1];


array[9] = 0;





However C++ has something called the standard template library (STL), this is a library as defined by ISO/ANSI as a part of C++, it contains template funcitons and containers, by far the most used container is vector which is a variable length array. The previous example would become





std::vector%26lt;int%26gt; array;


//Assume elements placed into the vector


array.erase(array.begin() + 2);





This is shorter and easier to use, if you want to know more about the STL then read Accelerated C++ by Andrew Koeing and Barberer E. Moo.
Reply:Just a couple of quick notes. The first poster is correct in saying that you can just move each element forward one space and overwrite the element you wish to delete. However, there is a caveat. If the element you wish to delete is a pointer to something that's been allocated using the new operator, you should explicitly delete it first before you overwrite it.





The second poster has a good point, although chained lists are more normally called linked lists.





Third, you can implement the 1st posters suggestion using 1 line using the movemem() function, which would be faster. But it's easier to screw that up, so I wouldn't recommend it unless you need every bit of speed.
Reply:While the most popular method is to move items ahead when deleting (as presented above), there is another way. By moving all the items down in the array you would not have to worry about overflowing your array when using a more familiar looking for loop.





//code begin





int removeIndex = 2;


int arrayLength = 10;





for(int i = removeIndex + 1; i %26lt; arrayLength; i++)


{


array[i-1] = array[i];


}


arrayLength--;





//end code





The other information about using delete and checking for invalid removal indexes is applicable, but this code does the trick as well.
Reply:Hello





You don't need to set it to zero. Do a FOR function that goes from the desired deletion point to the end that moves a[n+1] into n. So just move all the positions from the desired point one position back. Do a function and appeal it.





function delarraypos (int n)


{ cin%26gt;%26gt;n; //desired position


for (i=n;i%26lt;=m;i++) //m is array length


a[n]=a[n+1]


}
Reply:Mihai is largely correct, but here are a few more things to be aware of if you are to use his code:





function delarraypos (int n)


{ cin%26gt;%26gt;n; //desired position


for (i=n;i%26lt;=m;i++) //m is array length


a[n]=a[n+1]


}





1. The second element of an array is not array[2], so make sure that you either decrement n or pass in the proper index of the item you want to delete.





2. If the array length is m, the indices are 0 through m-1, so you don't want to go until m. Also, since you are going to set a[n]=a[n+1], going all the way to the end will make a[n+1] go past the end of the array, so you really only want to iterate to m-2.





3. The last element of the array will be left as it is if you do this. If you want to indicate unused elements of the array with 0, then you need to set array[m-1]=0. This will be important if the element to be deleted is at the end of the array, where there is nothing to move on top of it, if you want to make sure that it is not left with a non-0 value.





4. If you are concerned with a memory leak due to the array being populated with objects that have been "newed" elsewhere, then you still need to do a "delete array[2]" before rearranging the array to make sure the memory is freed up. Your example of setting the unused elements to 0 implies that this is an array of integers. If that is the case, then there is no need to delete the integer.





5. If the array's current length "m" is being stored somewhere, you will want to decrement it. (By "current lenngth," I mean how much of the array is filled as opposed to how much memory has been allocated for the array.)





6. Finally, unless you can be sure that the n value being passed in is good, it is good practice to check that n%26gt;=0 and n%26lt;m, and either throw an exception or assert out. If n is too big, this procedure will mess seriously with your memory in a way that will be hard to track down.





Hope this helps.


C++ array to hold full name (first last) as a single string in array?

I need to store the full name, first and last name in an array as a single string, and its corresponding value in a parallel array. This means to store the full name in one location in the array. Using C++ and my compiler is Dev C++. I need help with this array primarily how to store the name as one unit and the value in a corresponding location in a parallel array. Here is my code so far:





#include%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;cstring%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;





using namespace std;








int main()





{





ifstream inFile;





char array1 [10] [50];


char array2 [10] [5];





inFile.open("celebs.txt");





int location = 0 ;





inFile %26gt;%26gt; array1[ location ] %26gt;%26gt; array2[ location ] ;





while ( inFile %26amp;%26amp; location %26lt; 50 )


{


location++;


inFile %26gt;%26gt; array1[ location ] %26gt;%26gt; array2[ location ] ;





}





this is the input file:





Donald Trump 5.1


Paris Hilton 2.98


Lindsey Lohan 3.65


Marion Jones 1.03


Paul McCartney 3.75


Snoop Dogg 1.65


Britney Spears 2.14


Sean Combs 1.07


Heather Mills 2.31


Michael Vick 4.67

C++ array to hold full name (first last) as a single string in array?
Since this is C++, you can take advantage of string methods. I recommend that you scan backward in your input for the last separating space and split the input at that point. Also, instead of two-dimensional char arrays, why not use array of strings? See below for my attempt:





#include%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;cstring%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;





using namespace std;





const int TotalRows = 10;





int main()





{





ifstream inFile;





string input_string, array1[TotalRows], array2[TotalRows];





inFile.open("celebs.txt");





int location = 0, linecount = 0 ;





while ( linecount %26lt; TotalRows )


{


getline(inFile, input_string);


location = input_string.rfind(" ");


array1[linecount] = str.substr(0, location);


array2[linecount] = str.substr(location+1);


linecount++;


}


inFile.close();





}

gladiolus

C++ array function programming.?

I'm currently trying to develop an array class that addresses some of the shortcomings of the standard C++ array implementation.





The file has functions for an array. I'm having trouble coding correct functions. Please help








double GetData(int); //returns value of the int-th element. If past the array boundaries, then return first or last element





public Resive(int); //resizes the array to the new int size





public Output(); //prints the entire array onto stdout





public Input(); //inputs individual elements of the array





~array(); //destructor





I'm currently working on this, but these are giving me the most problems. Any advice or help is GREATLY appreciated. Any snippets of codes or comment lines are greatly appreciated as well.

C++ array function programming.?
If your array class has a member variable size, then double GetDouble(int element) should be straightforward:





{


if (element %26lt;0) return Array[0];


else if (element %26gt;= size) return Array[size-1];


else return Array[element];


}





Remember an array of size elements is number 0 through size-1, not 1 through size.





As a C programmer, primarily, I would use Realloc for the Resize(int) program. Information here:





http://www.cplusplus.com/reference/clibr...





for output what is so hard about:





for (int counter=0;counter %26lt; size; counter+=1)


cout %26lt;%26lt; array[counter];





The others I'll leave you with. As I said I'm primarily a C programmer and will occasionally do constructors but VERY rarely destructors. I hate C++ so much I won't even do it if I can't get away with an occasional memory leak.





It's not the classes I hate, it's the namespaces.


C++ Array Sorting Problem?

for ( k = 1; k %26lt;= howmany; k++ )


{


for ( c = 2; c %26lt;= howmany + 1; c++ )


{


if ( taxes[k] %26gt; taxes[c] )


taxes[k] = taxtemp;


taxes[k] = taxes[c];


taxes[c] = taxtemp;


status_array[k] = statustemp;


status_array[k] = status_array[c];


status_array[c] = statustemp;


income_array[k] = incometemp;


income_array[k] = income_array[c];


income_array[c] = incometemp;


ssn_array[k] = ssntemp;


ssn_array[k] = ssn_array[c];


ssn_array[c] = ssntemp;


}


}

C++ Array Sorting Problem?
First your for loops should start with zero. Second you forgot the curly bracket after the if statement. Thirdly you should write a swap function and use that. :)





for( k=1; k %26lt;= howmany-1; k++ )


{


for( c=1; c %26lt;= howmany; c++ )


{


if( taxes[k] %26gt; taxes[c])


{


swap(%26amp;taxes[k], %26amp;taxes[c]);


swap(%26amp;status_array[k], %26amp;status_array[c]);


swap(%26amp;income_array[k], %26amp;income_array[c]);


swap(%26amp;ssn_array[k], %26amp;ssn_array[c]);


}


}


}





void function swap(int a, int b)


{


int temp = a;


a = b;


b = temp;


}





// I hope this helps :)
Reply:You may contact a c++ helper live at website


like http://ccietutorial.com/


C++ array?

#include %26lt;string%26gt;


#include %26lt;iostream%26gt;





using std::cout;


using std::cin;


using std::endl;


using std ::string;





int main ()


{





string numberMonth[12]= {"Janurary","Feburary","March","April","...


string flowerOfmonth [12]={" "};


flowerOfmonth[0]="Carnation";


flowerOfmonth[1]="Violet";


flowerOfmonth[2]="Daffodile";


flowerOfmonth[3]="Daisy";


flowerOfmonth[4]="Lily-of-the-Valley";


flowerOfmonth[5]="Rose";


flowerOfmonth[6]="Water Lily";


flowerOfmonth[7]="Gladiolus";


flowerOfmonth[8]="Aster";


flowerOfmonth[9]="Cosmos";


flowerOfmonth[10]="Chrysanthemum";


flowerOfmonth[11]="Narcissus";





//get number of month


cout %26lt;%26lt; "Enter month (1-12) :" %26lt;%26lt; endl;


cin %26gt;%26gt;numberMonth;


if (month %26gt;= 1 %26amp;%26amp; month %26lt;= 12)


cout %26lt;%26lt; flowerOfmonth[numberMonth - 1] %26lt;%26lt; endl;


//else


cout %26lt;%26lt; "Invalid month" %26lt;%26lt; endl;


//end if


//end display salary





return 0;


} //end of main function








why cant i get this to work..thanks

C++ array?
You are expecting users to enter NUMERIC representation of the months. The wording of the months is NEVER used. So, numberMonths array definition is not needed.





Define numberMonths as an INTEGER.





Look what exactly you are doing with the numberMonth variable! It's an index for an array. Yet, you defined it as string.
Reply:try to chaneg this line


string flowerOfmonth [12]={" "};


to


string flowerOfmonth [12];


OR


initialize the second array as you have done with the first one


string flowerOfmonth = {"Carnation", "Violet", "Daffodile", ... }