Fill an array with even numbers and a list with odd numbers. Use STL vector clas
ID: 3715155 • Letter: F
Question
Fill an array with even numbers and a list with odd numbers. Use STL vector class member functions, or
STL algorithms to merge these containers into a vector. Display the vector contents to show that all
went well. Note the vector should combine the numbers on the array and the list without change their
original order.
Now re-arrange the contents on the vector so that they are in ascending order. Display the vector
contents again.
There are many ways to get the above tasks done. Look for the best ways and make your code look
elegant. Repeatedly use the push_back function should be avoided.
To practice on STL syntax, don’t use the array notation when display the vector contents.
Explanation / Answer
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <array>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
//Filling the array
int evenNumberArray[] = {2,4,6,8,10,12,14,16};
//Initalizing the list
list <int> oddNumberArray;
//filling the list
for (int i = 0; i < 8; i++)
{
oddNumberArray.push_back(2*i+1);
}
//Initalizing the vector
vector<int> numbersVector(16);
//merging array and list to vector using STL algo
std::copy(evenNumberArray, evenNumberArray + 8, numbersVector.begin());
std::copy(oddNumberArray.begin(), oddNumberArray.end(),numbersVector.begin()+8);
//displaying the merged value
cout<<"Merged vector"<<endl;
for (std::vector<int>::iterator it = numbersVector.begin(); it!=numbersVector.end(); ++it)
std::cout << ' ' << *it;
cout<<endl;
//sorting the result vector
std::sort(numbersVector.begin(), numbersVector.end());
//displaying the sorted vector
cout<<"Sotred vector"<<endl;
for (std::vector<int>::iterator it = numbersVector.begin(); it!=numbersVector.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
//PLEASE PROVIDE FEEDBACK THUMBS UP
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.