到目前为止,这是我的代码,我想做的是说我为第一个向量输入 1 2 3,为第二个向量输入 9 8 7,我希望它打印我们的 1 9 2 8 3 7。但我不知道它出来,有人可以指出我正确的方向。先感谢您。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> 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<int> merge(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> 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<int> merge_sorted(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> 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";
vector<int>a;
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";
vector<int>b;
more = true;
while (more)
{
int m;
cin >> m;
if (m == -1)
more = false;
else
b.push_back(m);
}
vector<int>d = append(a,b);
{
int i;
cout << "Appended: ";
for (i= 0; i < d.size(); i++)
cout << d[i] << " ";
cout << "\n";
}
vector<int>r = merge(a,b);
{
cout << "Merged: ";
vector<int> all_nodes(a.size() + b.size());
sort(a.begin(), a.end());
sort(b.begin(), b.end());
merge(a.begin(), a.end(), b.begin(), b.end(), all_nodes.begin());
cout << "\n";
}
vector<int>z = merge_sorted(a,b);
{
a.insert( a.end(), b.begin(), b.end() );
sort( a.begin(), a.end() );
cout << "Sorted: ";
for (vector<int>::iterator it = a.begin(); it != a.end(); ++it)
cout << *it << " ";
}
}