我如何准确地找到我在 a 中有多少个重复符号std::vector
?
我们的想法是编写以下程序 - 您输入一系列符号(应该是字母),例如:
aaaabbbccccc
当然,这是一个字符串,然后将其写入 a vector
(好吧,我想如果将其写入 a 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';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句