How to use & operator in C++ In C++
When used on the first element of an STL SequenceContainer (std::vector, std::array…), the & operator returns a pointer to the first element of an internally used C-style array. That array can be accessed and modified directly.
Example:
C++
// C++ program to convert vector to // array using transform() function #include <bits/stdc++.h> using namespace std; int main() { // Initialising the vector vector< int > v{ 1, 2, 3, 4, 5 }; int n = v.size(); // Printing original vector cout<< "Vector: " ; for ( int i: v) { cout << i << ' ' ; } cout<<endl; // returning the address // of the first element // of vector to array int * arr = &v[0]; // Printing the array cout<< "Array: " ; for ( int i=0;i<n;i++) { cout<<arr[i]<< " " ; } cout<<endl; return 0; } |
Vector: 1 2 3 4 5 Array: 1 2 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)
Different Ways to Convert Vector to Array in C++ STL
An array is the collection of data belonging to a primitive data type. The data in this is kept in a continuous memory location. Vectors are dynamic arrays that can be resized to meet the needs. We can convert vectors to arrays in the following ways given below.
Example:
Input : Vector: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5]Input : Vector: [‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
Output: Array: [‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
- Naive Approach to Convert Vector to Array
- Using copy() function in C++ STL
- Using transform() function in C++ STL
- Using data() function in C++ STL
- Using & operator in C++