我需要一个 std 函数来检查有多少元素在向量中恰好出现一次
I need a std function which checks how many elements occur exactly once in vector
有没有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;
}
演示
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 在循环工作时,首先将两个文件读为向量,但仅次于迭代一次
- 使用迭代器时遇到问题,每 M 次传递一次擦除一个向量项
- C++ 向量元素被最后一次调用push_back替换
- 一次遍历 8 个向量字节并执行按位运算
- 尝试保存到成员向量的连接-一次只保存一个
- while(getline(myReadFile, temp, ':')) 执行一次迭代太多导致向量越界
- 如何在一次内创建N个向量或数组
- 一次向 C++ 向量添加多个元素
- 我需要一个 std 函数来检查有多少元素在向量中恰好出现一次
- STD 向量构造元素一次
- 有没有一种方法可以将无符号字符块移动到 STL 向量中,而不是一次移动 1 个无符号字符
- 对指针向量进行排序一次,然后崩溃并"unable to read memory"
- 如何一次将多个整数传递到一个向量中