Saturday, May 9, 2009

(C++) How do i change C-style strings into string objects, and a 1d array into a vector?

I've written a program that uses C-style strings and one-demensional arrays, but i need to switch the C-style strings to string objects and the arrays into vectors. Is there some simple way to go about doing this? I'm not 100% clear on how to use string objects and vectors, but is there some way where I can just change the way the strings and arrays are written and basically keep the program I've written?

(C++) How do i change C-style strings into string objects, and a 1d array into a vector?
yes, it's quite easy actually.





When declaring an array say:


int myIntArray[10]; use


std::vector%26lt;int%26gt; myVector; and optionnally : myVector.reserve(10);


Even better: typedef std::vector%26lt;int%26gt; TIntVector;


TIntVector myVector;








Everywhere you were using the array replace by the vector.


and everywhere you were receiving an array, receive an TIntVector instead.





All access stay valid. So myArray[9] = 0; become myVector[9] = 0;





string can be initialized directly from the c string like this.


std::string someString = szSomeCString;


No comments:

Post a Comment