使用 count_if() 查找相同的字符串值

Using count_if() to find the same string value

我尝试使用 lambda 表达式和 count_if()vector 中查找相同的字符串值,但没有成功。错误信息是:

variable 'str' cannot be implicitly captured in a lambda with no capture-default specified

std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"};

for (unsigned int i = 0; i < hello.size(); i++)
{
    int n=0;
    std::string str=hello[i];
    n=std::count_if(hello.begin(),hello.end(),[](std::string s){return s==str;});
    std::cout<<n;
}

@史蒂文 lambda 函数的括号 [] 称为 捕获列表 。它们定义了 lambda 函数使用的变量范围。参见 this reference

当您使用这种格式 [&] 时,这意味着您可以在您的 lambda 函数中看到当前作用域的所有变量(通过引用)。所以变量的类型并不重要。

对于你的例子,当你写:

s == str

lambda 函数只知道作为参数传递的变量 s。要查看 str,您可以使用以下任一方法:

  1. [&],通过引用传递所有内容
  2. [&str],只传递变量str作为参考

注意,也有传值的方式。

此函数具有相同的机制,只是它使用 <hash><unordered_map> 来存储值和每个重复的次数(如果它大于 1 出现).

template <typename T>
void elements(vector<T>& e) 
{
    auto h = [](const T* v) { return std::hash<T>()(*v); };
    auto eq = [](const T* v1, const T* v2) { return v1->compare(*v2) == 0; };
    std::unordered_map<const T*, size_t, decltype(h), decltype(eq)> m(e.size(), h, eq);

    // Count occurances.
    for (auto v_i = e.cbegin(); v_i != e.cend(); ++v_i)
        ++m[&(*v_i)];

    // Print value that occur more than once:
    for (auto m_i = m.begin(); m_i != m.end(); ++m_i)
        if (m_i->second > 1)
            std::cout << *m_i->first << ": " << m_i->second << std::endl;
}

Example