//数据结构与算法基础题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的使用对于基本算法和数据结构实现的方便性。