//資料結構與算法基礎題1:線性表操作,實作A并B,結果放入A中
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#pragma warning(disable:4996)
using namespace std;
int main()
{
vector<int> set_A, set_B;
int num_of_elements_in_A, num_of_elements_in_B;
//下面輸入集合A和B的元素
//從輸入友善的角度考慮,沒有進行去重,隻在最後合并的時候進行了去重
cout << "請輸入集合A的元素個數:";
cin >> num_of_elements_in_A;
if (num_of_elements_in_A <= 0) {
cout << "元素個數不可以小于0!" << endl;
return 1;
}
cout << "集合A元素個數為:" << num_of_elements_in_A << endl;
for (int i = 0; i < num_of_elements_in_A; i++) {
int temp = 0;
cout << "請輸入集合A的第" << i + 1 << "個元素:";
cin >> temp;
set_A.push_back(temp);
}
cout << "請輸入集合B的元素個數:";
cin >> num_of_elements_in_B;
if (num_of_elements_in_B <= 0) {
cout << "元素個數不可以小于0!" << endl;
return 1;
}
cout << "集合B元素個數為:" << num_of_elements_in_B << endl;
for (int i = 0; i < num_of_elements_in_B; i++) {
int temp = 0;
cout << "請輸入集合B的第" << i + 1 << "個元素:";
cin >> temp;
set_B.push_back(temp);
}
//把B的元素先全部插入A中
vector<int>::iterator iter_B = set_B.begin();
while (iter_B != set_B.end())
{
set_A.push_back(*iter_B);
iter_B++;
}
sort(set_A.begin(), set_A.end());
set_A.erase(unique(set_A.begin(), set_A.end()), set_A.end());
vector<int>::iterator iter_A = set_A.begin();
cout << "合并後A中的實際元素為:";
while (iter_A != set_A.end())
{
cout << *iter_A << " ";
iter_A++;
}
cout << endl;
system("pause");
return 0;
}
注意,中間erase裡的unique使用,得要先對vector進行排序,否則不會進行所有的去重(即隻對相鄰的重複進行去重)
進一步體會了STL的使用對于基本算法和資料結構實作的友善性。