I am Charmie

メモとログ

C++: give std::vector as array

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,

[code lang="cpp"]

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 xxx; }

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 &lt; numData; ++n)
{
    vecI[n] = n;
    vecF[n] = square((float)n);
    vecD[n] = cube((double)n);
}

std::cout &lt;&lt; &quot;print integer array: &quot;;
printArray(&amp;vecI.front(), vecI.size());
std::cout &lt;&lt; &quot;print integer vector: &quot;;
printVector(vecI);
std::cout &lt;&lt; &quot;print float array: &quot;;
printArray(&amp;vecF[0], vecF.size());
std::cout &lt;&lt; &quot;print float vector: &quot;;
printVector(vecF);
std::cout &lt;&lt; &quot;print double array: &quot;;
printArray(vecD.data(), vecD.size());
std::cout &lt;&lt; &quot;print double vector: &quot;;
printVector(vecD);

} [/code]