Array in C ++, vector, string

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/oqqWang1234567/article/details/81809942

        C ++ language is compatible with the C language, so C ++ arrays can be used C language style traditional arrays. But an array of C language format in a lot of time is not so easy to use. In C ++ may be used instead of the vector.

         This article considers only the relationship between the char array with Vector, string.

          If you use the string, consider using string, but if you only consider the array, you should use vector instead of as char arrays and strings, after all, is not the same.

          char array interchangeable with the vector:

          1, array to a vector

float arrHeight[] = { 1.68,1.72,1.83,2.05,2.35,1.78,2.1,1.96 };  
vector<float> vecHeight(arrHeight, arrHeight+sizeof(arrHeight)/sizeof(float));  

         2, vector array transfer 
         because the vector data is stored in the internal storage space continuous, vector transfected array fact only need to obtain the vector length of the first data and address data. If only parameter passing, without any operation, the address can be directly transmitted, if the data to be copied, you can borrow the memory copy function "memcpy". E.g:

float *buffer = new float[sizeof(arrHeight)];  
if (!vecHeight.empty())  
{  
    memcpy(buffer, &vecHeight[0], vecHeight.size()*sizeof(float));  
}  

3. Application Recommendations

1, vector as a dynamic array, which implementation is: pre-allocate a block of memory, when not enough feeling, redistribution of a larger block of memory, and then copy the data will automatically prior to the new memory block.

Therefore, for efficiency, if the implementation knows the length of data to be stored, may be used to open up enough memory resize function, prevent subsequent memory copy.

Reference https://blog.csdn.net/ei1990/article/details/80175610

Guess you like

Origin blog.csdn.net/oqqWang1234567/article/details/81809942