我需要一个 std 函数来检查有多少元素在向量中恰好出现一次

I need a std function which checks how many elements occur exactly once in vector

本文关键字:向量 一次 元素 检查 一个 std 函数 多少      更新时间:2023-10-16

有没有STL函数可以做到这一点?对于矢量:

4 4 5 5 6 7

预期的输出应该是2的,因为有一个6 and 7

如果没有 STL 函数,你能帮我数经典吗?

我认为STL中没有这种算法。您可以复制到multimap中或按照建议使用频率map,但它会执行不必要的额外工作,因为您的数组恰好已排序。这是一个简单的算法,用于计算奇异元素的数量,即在排序序列中仅出现一次的元素。

int previous = v.front();
int current_count = 0;
int total_singular = 0;
for(auto n : v) {
    if(previous == n)          // check if same as last iteration
        current_count++;       // count the elements equal to current value
    else {
        if(current_count == 1) // count only those that have one copy for total
            total_singular++;
        previous = n;
        current_count = 1;     // reset counter, because current changed
    }
}
if(current_count == 1)         // check the last number
    total_singular++;

您也可以将count_if与有状态的lambda一起使用,但我认为它不会使算法更简单。

如果性能和内存对您无关紧要,请使用std::map(或无序版本)来完成此任务:

size_t count(const std::vector<int>& vec){
    std::map<int,unsigned int> occurenceMap;
    for (auto i : vec){
        occurenceMap[i]++;
    }
    size_t count = 0U;
    for (const auto& pair : occurenceMap){
        if (pair.second == 1U){
            count++;
        }
    }
    return count;
} 

使用模板,它可以泛化为任何容器类型和任何包含对象类型。

使用 std::unique 对唯一条目 (ct_u) 进行计数,然后对原始条目进行用户向量计数 (ct_o)。ct_o-ct_u的差异会给出答案。

PS:这只有在原始向量中相同的条目在一起时才有效。如果没有,您可能需要先对向量进行排序。

使用算法:

std::size_t count_unique(const std::vector<int>& v)
{
    std::size_t count = 0;
    for (auto it = v.begin(); it != v.end(); )
    {
        auto it2 = std::find_if(it + 1, v.end(), [&](int e) { return e != *it; });
        count += (it2 - it == 1);
        it = it2;
    }
    return count;
}

演示