Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <iomanip>
- /*
- Antonio Villanueva Segura
- Array exercise
- You are given two arrays arr1 and arr2, where arr2 always contains integers.
- Write a function such that:
- For arr1 = ['a', 'a', 'a', 'a', 'a'], arr2 = [2, 4] the function returns ['a', 'a']
- For arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5], arr2 = [1, 4, 7] the function returns [1, 1, 1]
- For arr1 = [0, 3, 4], arr2 = [2, 6] the function returns [4]
- For arr1=["a","b","c","d"] , arr2=[2,2,2], the function returns ["c","c","c"]
- For arr1=["a","b","c","d"], arr2=[3,0,2] the function returns ["d","a","c"]
- Note that when an element inside arr2 is greater than the index of the last element of arr1 no element of arr1 should be added to the resulting array. If either arr1 or arr2 is empty, you should return an empty arr (empty list in python, empty vector in c++). Note for c++ use std::vector arr1, arr2.
- */
- #include <iostream>
- #include <vector>
- using namespace std;
- template <typename T,typename U>
- class Arrays {
- public:
- // Constructeur
- Arrays(const std::vector<T>& a , const std::vector<U>& b) : chaine(a),index(b) {}
- void printVector(){
- printVector(chaine);
- printVector(index);
- }
- std::vector<T> cutVector(){
- std::vector<T> tmp;
- for (const auto& i : index) {
- try{
- chaine.at(i);
- tmp.push_back (chaine[i]);
- }catch (const std::out_of_range& e){
- }
- }
- return tmp;
- }
- template <typename V>
- void printVector (const std::vector<V>& v){ //Print vector
- for (const auto& elem : v) {
- std::cout << elem << ",";
- }
- std::cout <<" - ";
- }
- private:
- std::vector<T> chaine;
- std::vector<U> index;
- };
- int main(int argc, char *argv[])
- {
- std::vector <char> arr1_a {'a', 'a', 'a', 'a', 'a'};//arr2 = [2, 4] the function returns ['a', 'a']
- std::vector<int> arr2_a {2, 4} ;
- std::vector <int> arr1_b {0, 1, 5, 2, 1, 8, 9, 1, 5};// arr2 = [1, 4, 7] the function returns [1, 1, 1]
- std::vector<int> arr2_b {1, 4, 7};
- std::vector <int> arr1_c {0, 3, 4};// arr2 = [2, 6] the function returns [4]
- std::vector<int> arr2_c {2, 6};
- std::vector <char> arr1_d {'a','b','c','d'} ;// arr2=[2,2,2], the function returns ["c","c","c"]
- std::vector<int> arr2_d {2,2,2};
- std::vector <char> arr1_e {'a','b','c','d'};// arr2=[3,0,2] the function returns ["d","a","c"]
- std::vector<int> arr2_e {3,0,2};
- Arrays <char,int> a (arr1_a,arr2_a);
- a.printVector (a.cutVector());
- Arrays <int,int> b (arr1_b,arr2_b);
- b.printVector (b.cutVector());
- Arrays <int,int> c (arr1_c,arr2_c);
- c.printVector (c.cutVector());
- Arrays <char,int> d (arr1_d,arr2_d);
- d.printVector (d.cutVector());
- Arrays <char,int> e (arr1_e,arr2_e);
- e.printVector (e.cutVector());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement