Hello guys! I am a bit confused! Can we transfer elements so that array 'a' has total elements 4,9,7,6,5,3,12,14,3,2 ..so total 10 elements! but then we need a size of 10 in 'a'..so how we will make that program?
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
usingnamespace std;
int main()
{
int a[5]= {4,9,7,6,5};
int b[5]= {3,12,14,3,2};
for (int i=0;i<5;i++)
{
a[i] = b[i];
cout << a[i];
}
}
The size of array is set when writing the code; it cannot change.
std::vector can resize:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a {4,9,7,6,5};
std::vector<int> b {3,12,14,3,2};
a.reserve( a.size() + b.size() );
for ( auto x : b )
{
a.push_back( x );
}
for ( auto x : a )
{
std::cout << ' ' << x;
}
}
You can create a larger array, but use only some of it:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
int a[14] {4,9,7,6,5};
for ( auto x : a )
{
std::cout << ' ' << x;
}
}