### How to Merge two vectors

can someone help me out here, say i have two vectors, one equals [1,2,3] and the other equals [9,8,7],what i am trying to do is make it so that the program prints out [1 9 2 8 3 7]. if anyone can point me onto the right direction i would greatly appreciate it. thank you who comment in advance.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130`` ``````#include #include #include using namespace std; vector append(vector a, vector b) { int n = a.size(); int m = b.size(); vector c(n + m); int i; for (i = 0; i < n; i++) c[i] = a[i]; for (i = 0; i < m; i++) c[n + i] = b[i]; return c; } vector merge(vector a, vector b) { int n = a.size(); int m = b.size(); vector c(n + m); int i; for (i = 0; i < n; i++) c[i] = a[i]; for (i = 0; i < m; i++) c[n + i] = b[i]; return c; } vector merge_sorted(vector a, vector b) { int n = a.size(); int m = b.size(); vector c(n + m); int i; for (i = 0; i < n; i++) c[i] = a[i]; for (i = 0; i < m; i++) c[n + i] = b[i]; return c; } int main() { cout << "Please enter a set of numbers, insert -1 when done.\n"; vectora; bool more = true; while (more) { int n; cin >> n; if (n == -1) more = false; else a.push_back(n); } cout << "Please enter another set of numbers, insert -1 when done.\n"; vectorb; more = true; while (more) { int m; cin >> m; if (m == -1) more = false; else b.push_back(m); } vectord = append(a,b); { int i; cout << "Appended: "; for (i= 0; i < d.size(); i++) cout << d[i] << " "; cout << "\n"; } vectorr = merge(a,b); { //int i; cout << "Merged: "; //for (i = 0; i < r.size();++i) /*{ merge (a.begin(), a.end(), b.begin(), b.end(), r.begin()); }*/ //cout << r[i] << " "; sort (a.end(),a.begin()); sort (b.end(),b.begin()); merge (a.end(),a.begin(),b.end(),b.begin(),r.begin()); for (std::vector::iterator it=r.begin(); it!=r.end(); ++it) std::cout << ' ' << *it; cout << "\n"; } vectorz = merge_sorted(a,b); { a.insert( a.end(), b.begin(), b.end() ); sort( a.begin(), a.end() ); cout << "Sorted: "; for (vector::iterator it = a.begin(); it != a.end(); ++it) cout << *it << " "; cout << "\n"; } }``````
Last edited on
> one equals [1,2,3] and the other equals [9,8,7],
> what i am trying to do is make it so that the program prints out [1 9 2 8 3 7].

To avoid confusion, you should not call that operation merge.

 ``123456789101112131415161718192021222324252627`` ``````#include #include #include std::vector interleave( const std::vector& a, const std::vector& b ) { std::vector result ; auto m = std::min( a.size(), b.size() ) ; for( std::size_t i=0 ; i

http://liveworkspace.org/code/1JkyNQ\$0
Topic archived. No new replies allowed.