今天的力扣周赛(第239场)第三题,看了大神的解答才知道,原来 C++ stl 里提供的有 next_permutation 函数,深感自己学艺不精。于是想在这里整理一下 C++ stl 在算法题里的使用。
vector<int> a{4, 1, 5, 1, 7, 1};
sort(a.begin(), a.end());
a.erase(unique(a.begin(), a.end()), a.end());vector<int> a{1, 2, 3, 4, 5};
cout << accumulate(a.begin(), a.end(), 0);上述代码等价于:
vector<int> a{1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < a.size(); ++i)
sum += a[i];
cout << sum;unordered_map<int, string> hash {{1, "a"}, {2, "b"}, {3, "c"}};
for (auto& [key, value] : hash)
cout << key << ' ' << value << endl;vector<int> v(10);
iota(v.begin(), v.end(), 10);等价于:
vector<int> v(10);
int start = 10;
for (int i = 0; i < v.size(); ++i)
v[i] = start++;iota函数可以节省一两行代码,iota这个名字来源于希腊字母。
14. partition
按给定的条件,将容器内的元素分为两组。刷题时偶尔会用到。