This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

OT: std::vector to C array


Hello,
how would you convert a std::vector to an C array?

#include <vector>
#include <algorithm>

using namespace std;

int main()
{
	std::vector<int> v( 10);
	int* a;

	// Approach 1
	// I suppose this is the most general way to
	// convert a vector to an array.  But it 
	// doubles the memory consumption and is slow.
	a = new int [v.size()];
	copy( v.begin(), v.end(), a);
	delete [] a;

	// Approach 2
	// This is short, but works only with special
	// implementations (in case of 'T* == vector::iterator').
	a = v.begin();

	// Approach 3;
	// Is this valid in the context of the latest C++ standard?
	// It works at least with gcc 2.95.3 and 3.2.
	// 'front' returns 'vector::reference' which is 'allocator<T>::reference'
	// which is 'T&'. Thus it should be ok.
	if (!v.empty()) {
		a = &v.front();
	}

	// Approach 2 and 3 assumes that nobody alters the vector during the
	// usage of 'a' and that the vector implementation works
	// with contigous fields. But you can read directly into the vector, even
	// with a system call: 'read( fd, &v.front(), v.size());'

	return 0;
}


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]