C++向量中找到重复的符号

C++ find repeating symbols in vector

本文关键字:符号 向量 C++      更新时间:2023-10-16

如何准确找到一个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