Vector v1 with 5 elements and vector v2 with 3 elements are
Merge into vector v3 (empty) or I want to put the sum of v1 and v2 in vector v3.//#define_CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v1 = { 50,10,30,80,60 };
vector<int> v2 = { 20,70,40 };
vector<int> v3(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
auto iter = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
v3.resize(iter,-v3.begin());
}
I wrote the code like above, but the merge() and set_union() functions have errors. Did I write it wrong? I can't catch any grammar errors, but I wonder why there are errors. The error appears as "sequence not ordered".
c++
The "sequence not ordered" error is due to merging vectors out of alignment. You must sort the vectors before using the merge function. Please refer to the code below
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v1 = { 10,30,50,60,70,80 };
vector<int> v2 = { 20,40,70 };
vector<int> v3(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
cout << "v1: ";
for (int v : v1)
cout << v << " ";
cout << endl;
cout << "v2: ";
for (int v : v2)
cout << v << " ";
cout << endl;
cout << "v3: ";
for (int v : v3)
cout << v << " ";
cout << endl;
vector<int>::iterator result = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
v3.resize(result - v3.begin());
cout << "v3: ";
for (int v : v3)
cout << v << " ";
cout << endl;
}
© 2024 OneMinuteCode. All rights reserved.