94 lines
3.2 KiB
C++
Raw Normal View History

2024-03-08 15:25:16 +08:00
#include "ABasic.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
/*
next_permutation
[first, last) [first, last)
next_permutation
使
true false
cppreference
[first, last) operator< comp
true
std::sort(first, last) false
123 132
next_permutation
next_permutation
false
*/
// 生成 N 个不同元素的全排列
void generatePermutations()
{
int elements[] = {1, 2, 3, 4};
const size_t N = sizeof(elements) / sizeof(elements[0]);
std::vector<int> vec(elements, elements + N);
int count = 0;
do {
std::cout << ++count << ": ";
// 打印写法
std::copy(vec.begin(), vec.end(),
std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
} while (next_permutation(vec.begin(), vec.end()));
}
/*
7 3
{ 1, 1, 1, 0, 0, 0, 0 }
1
*/
void combinationDemo()
{
int values[] = {1, 2, 3, 4, 5, 6, 7};
int elements[] = {1, 1, 1, 0, 0, 0, 0};
const size_t N = sizeof(elements) / sizeof(elements[0]);
assert(N == sizeof(values) / sizeof(values[0]));
std::vector<int> selectors(elements, elements + N);
int count = 0;
do {
std::cout << ++count << ": ";
for (size_t i = 0; i < selectors.size(); ++i) {
if (selectors[i]) {
std::cout << values[i] << ", ";
}
}
std::cout << std::endl;
} while (prev_permutation(selectors.begin(), selectors.end()));
}
// 这里写一个仿函数 或者 使用 lambda 表达式都可以
struct AreBothSpaces {
bool operator()(char x, char y) const { return x == ' ' && y == ' '; }
};
// 移除连续空格
void removeContinuousSpaces(std::string& str)
{
std::cout << "PreString:" << str << std::endl;
// std::string::iterator last =
// std::unique(str.begin(), str.end(), AreBothSpaces());
std::string::iterator last2 =
std::unique(str.begin(), str.end(),
[](char x, char y) { return x == ' ' && y == ' '; });
str.erase(last2, str.end());
std::cout << "AfterString:" << str << std::endl;
}