排序vector,并清除相同項目:
1 #include <algorithm> 2 vector<int> vec; 3 4 bool cmp(const int &tmpa, const int &tmpb) { 5 return tmpa < tmpb; // 降序改爲大寫 6 } 7 8 int main(void) { 9 vec init; 10 std::sort(vec.begin(), vec.end(), cmp); 11 vector<int>::iterator iter = std::unique(vec.begin(), vec.end()); 12 vec.erase(iter, vec.end()); 13 }
1 int main() { 2 vector<int> vec; 3 vec.push_back(1); 4 vec.push_back(3); 5 vec.push_back(2); 6 vec.push_back(1); 7 vec.push_back(9); 8 vec.push_back(3); 9 for (int tmpi = 0; tmpi < vec.size(); tmpi++) printf("%d ", vec[tmpi]); 10 printf("\n"); 11 std::sort(vec.begin(), vec.end(), sortcmp); 12 for (int tmpi = 0; tmpi < vec.size(); tmpi++) printf("%d ", vec[tmpi]); 13 printf("\n"); 14 vector<int>::iterator iter = unique(vec.begin(), vec.end()); 15 vec.erase(iter, vec.end()); 16 for (int tmpi = 0; tmpi < vec.size(); tmpi++) printf("%d ", vec[tmpi]); 17 printf("\n"); 18 }