Using iterators with the C Standard Library

The C Standard Library will often require pointers to data. For example, when a C function requires a string, it will need a const char* pointer to the character array containing the string. The C++ Standard Library has been designed to allow you to use its classes with the C Standard Library; indeed, the C Standard Library is part of the C++ Standard Library. In the case of string objects, the solution is simple: when you need a const char* pointer, you simply call the c_str method on a string object.

The containers that store data in contiguous memory (array, string, or data) have a method called data that gives access to the container's data as a C array. Further, these containers have [] operator access to their data, so you can also treat the address of the first item as being &container[0] (where container is the container object), just as you do with C arrays. However, if the container is empty, this address will be invalid, so before using it you should call the empty method. The number of items in these containers is returned from the size method, so for any C function that takes a pointer to the start of a C array and its size, you can call it with &container[0] and the value from the size method.

You may be tempted to get the beginning of the container that has contiguous memory by calling its begin function, but this will return an iterator (usually an object). So, to get a C pointer to the first item, you should call &*begin; that is, dereference the iterator returned from the begin function to get the first item and then use the address operator to get its address. To be frank, &container[0] is simpler and more readable.

If the container does not store its data in contiguous memory (for example, deque and list), then you can obtain a C pointer by simply copying the data into a temporary vector.

    list<int> data; 
// do some calculations and fill the list
vector<int> temp(data.begin(), data.end());
size_t size = temp.size(); // can pass size to a C function
int *p = &temp[0]; // can pass p to a C function

In this case, we have chosen to use a list and the routine will manipulate the data object. Later in the routine, these values will be passed to a C function so the list is used to initialize a vector object, and these values are obtained from the vector.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset