There exist several ways to give a std::vector as an array. Suppose we have a vector std::vector vec. The ways are
- &vec[0]
- &vec.front()
- vec.data() supported by C++11
The following code should output as
print integer array: 0,1,2,3,4,
print integer vector: 0,1,2,3,4,
print float array: 0,1,4,9,16,
print float vector: 0,1,4,9,16,
print double array: 0,1,8,27,64,
print double vector: 0,1,8,27,64,
#include <iostream> #include <vector> template <typename ValueType> void printArray( const ValueType* array, const int size ) { for(int n = 0; n < size; ++n) { std::cout << array[n] << ","; } std::cout << std::endl; } template <typename ValueType> void printVector( const std::vector<ValueType> vec ) { for(int n = 0; n < vec.size(); ++n) { std::cout << vec[n] << ","; } std::cout << std::endl; } template <typename ValueType> ValueType square( const ValueType x ) { return x*x; } template <typename ValueType> ValueType cube( const ValueType x ) { return x*x*x; } int main() { int numData = 5; std::vector<int> vecI(numData); std::vector<float> vecF(numData); std::vector<double> vecD(numData); for(int n = 0; n < numData; ++n) { vecI[n] = n; vecF[n] = square((float)n); vecD[n] = cube((double)n); } std::cout << "print integer array: "; printArray(&vecI.front(), vecI.size()); std::cout << "print integer vector: "; printVector(vecI); std::cout << "print float array: "; printArray(&vecF[0], vecF.size()); std::cout << "print float vector: "; printVector(vecF); std::cout << "print double array: "; printArray(vecD.data(), vecD.size()); std::cout << "print double vector: "; printVector(vecD); }
Advertisements