algorithm

What is correct answer:
a. runtime error?
or
b. 0,3,9,2,0,0,0 ?
What will happen when you attempt to compile and run the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void printer(int i) {        cout << i << ", ";	}
int main() {
        int mynumbers1[]={3, 9, 0, 2};
        int mynumbers2[]={6, 1, 4, 5};
        vector<int> v1(7);
        sort(mynumbers2, mynumbers2 + 3);
        sort(mynumbers1, mynumbers1 + 3);//LINE I
        set_difference(mynumbers1, mynumbers1+4, mynumbers2, mynumbers2+4, v1.begin());//LINE II
        for_each(v1.begin(), v1.end(), printer);        return 0;	}
You know there are c++ compilers available:
https://ideone.com/
http://rextester.com/l/cpp_online_compiler_visual
or even
http://cpp.sh/
the latter you can access directly by clicking the gear icon to the right of the code in the OP.
Use an iterator adaptor like std::back_insert_iterator<std::vector<int>> which calls the push_back() method of the underlying container and right-sizes the vector. The reason you're getting the additional trailing 0's is that you've declared more memory (vector<int> v1(7);) than required in this particular case.
http://en.cppreference.com/w/cpp/iterator/back_insert_iterator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
//using namespace std;
//http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
void printer(int i) { std::cout << i << ", ";	}
int main() {
        std::vector<int> mynumbers1{3, 9, 0, 2};//use std::vector<int> throughout
        std::vector<int> mynumbers2 {6, 1, 4, 9};
        std::vector<int> v1{};//declare empty vector
         //instead of counting off numbers use the vector iterators:
        std::sort(mynumbers2.begin(), mynumbers2.end());
        sort(mynumbers1.begin(), mynumbers1.end());//LINE I
       // set_difference(mynumbers1, mynumbers1+4, mynumbers2, mynumbers2+4, v1.begin());//LINE II
      set_difference(mynumbers1.begin(), mynumbers1.end(), mynumbers2.begin(), mynumbers2.end(),std::back_insert_iterator<std::vector<int>>(v1));

        for_each(v1.begin(), v1.end(), printer);        return 0;	}
Last edited on
Topic archived. No new replies allowed.