C++向量中找到重复的符号
C++ find repeating symbols in vector
如何准确找到一个std::vector
中有多少个重复符号?
这个想法是编写以下程序 - 您输入一系列符号(应该是字母(,例如:
aaaabbbccccc
当然,这是一个字符串,然后将其写入vector
(好吧,我想如果您将其写入vector
,则迭代会容易得多(
输出为:4a3b5c
(因为有四个a
,三个b
和五个c
(
我的主要问题是找到重复的符号并用它们进行操作。
这是实现相同目标的另一种方法。这可能比基于std::map
的解决方案更有效一些,因为std::array
在内存中是连续的,并且通过迭代器支持任意输入和输出容器。
可以使用数组,因为我们只能有 256 个不同的字符。
#include <array>
#include <vector>
#include <iostream>
#include <type_traits>
#include <utility>
#include <limits>
template <
typename InputIter,
typename OutputIter,
typename = typename std::enable_if_t<
std::is_same_v<
typename std::iterator_traits<InputIter>::value_type,
char>>>
OutputIter encode(InputIter begin, InputIter end, OutputIter out)
{
constexpr auto num_chars = std::numeric_limits<char>::max();
std::array<int, num_chars> counts = {};
while (begin != end)
++counts[*begin++];
for (char i = 0; i < num_chars; ++i)
if (counts[i] > 0)
*out++ = std::make_pair(i, counts[i]);
return out;
}
int main()
{
std::vector<char> v = {
'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c'};
std::vector<std::pair<char, int>> out;
encode(v.begin(), v.end(), std::back_inserter(out));
for (auto e : out)
std::cout << e.second << e.first;
std::cout << 'n';
}
您可以使用std::map
来在迭代std::vector
时保持符号的计数,并使用std::vector
的元素作为std::map
的键:
#include <vector>
#include <iostream>
#include <map>
int main()
{
std::vector<char> vec{'a', 'a', 'a', 'a',
'b', 'b', 'b',
'c', 'c', 'c', 'c', 'c'};
std::map<char, int> cnt;
// count symbols
for (auto elem: vec)
cnt[elem]++;
// display count
for (auto elem: cnt)
std::cout << elem.second << elem.first;
std::cout << std::endl;
}
运行上面的代码将生成输出4a3b5c
。
相关文章:
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 尝试将字符串从文件读取到无符号字符向量中
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 如何使用istream_iterator将无符号字符向量转换为字符串?
- 快速将无符号字符的向量强制转换为POD结构的向量,反之亦然
- C++向量中找到重复的符号
- 将无符号字符的向量写入二进制文件 c++
- 如何确定向量的元素是否交替为符号?
- 自动符号转换,用于对类等数学向量进行操作
- 如何以精度换取速度来评估C++中两个向量的点积符号?(不特定于硬件)
- C++将向量转换为<string>无符号字符数组
- SSE2 内部函数 - 找到两个无符号短向量的最大值
- 您可以将向量<无符号字符>转换为字节[]吗?
- C++ 强制转换向量<无符号字符>到无符号字符 *
- 无符号字符迭代器的向量不起作用
- 将字符串存储在无符号长整型的向量中
- 将 int 数组值传输到无符号向量
- 无法解析符号向量
- 在类之间共享向量时,无法解析的外部符号向量