【问题标题】:Element multiplicities in container? [duplicate]容器中的元素多重性? [复制]
【发布时间】:2016-03-15 14:35:33
【问题描述】:

我有一个strings的向量:

std::vector<std::string> data;

我需要一个返回std::map&lt;std::string, int&gt; 的算法,将每个不同的std::string 及其多重性(在data 中重复出现的次数)存储在data 中。

这是在 C++ 标准库中实现的吗?在哪里?

如果不是,你能提出一个有效的算法来做到这一点吗?

注释:这相当于Counter 在 Python 中所做的。我正在寻找一个 C++ 实现。

【问题讨论】:

  • 我在想这个。期待答案
  • @NathanOliver 这不是重复的。类似,但数据类型不同。我也可以使用循环。我认为这是一个不同的问题
  • 为什么向量中的数据类型很重要?
  • @NathanOliver 它简化了事情。将该问题中接受的答案与 Vlad 的答案进行比较。另请注意,那边的 OP 不想使用循环,这会限制事情。
  • 所以你得到了一些奖励信息。第二个代码块的前三行做了 Vlad 所做的事情。

标签: c++ dictionary vector stl


【解决方案1】:

你可以写

std::vector<std::string> data;
std::map<std::string, int> m;

//...

for ( const std::string &s : data ) ++m[s];

【讨论】:

  • 所以如果没有找到会创建新的?
  • @FirstStep 会的。
【解决方案2】:
#include <iostream>
#include <vector>
#include <string>
#include <map>

std::map<std::string, int> counts(const std::vector<std::string>& v)
{
    std::map<std::string, int> result;
    for (auto const& s : v) {
        ++result[s];
    }
    return result;
}

int main()
{
    auto m = counts({"a", "a", "b", "c", "c", "c" });
    for (auto const& e : m)
    {
        std::cout << e.first << " : " << e.second << std::endl;
    }
    return 0;
}

预期结果:

a : 2
b : 1
c : 3

解释:

使用 std::map,operator[k] 将在映射匹配键 k 中搜索项目。如果未找到,则将 (k,v) 插入到映射中,其中 v 是 V 的默认初始化值。在任何一种情况下,无论是否找到,都会返回对与 k 对应的 V 的引用。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2016-01-26
    • 2020-04-29
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2017-11-25
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多