php - C++ unordered_set 插入插入 PHP

标签 php c++ unordered-set

我有一个 C++ 代码,我必须用 PHP 重写它。 奇怪的事情发生在我身上,因为我是 PHP 程序员并且不太了解 C++。 这是代码:

#include <iostream>
#include <unordered_set>
using namespace std;

int func(int choice) {

    unordered_set<int> hset;
    for (int counter = 0; counter < choice; counter++) {
        hset.insert(counter);
        if (counter % 2 == 0) {
            hset.insert(counter);
            hset.insert(counter + 1);
        }
    }
    return hset.size();
}

int main(int argc, char** argv) {
    cout << func(561);
    return 0;
}

代码的输出是:562;

我写过这样的 PHP 代码:

function func($choice) {

$hset = [];

for ($counter = 0; $counter < $choice; $counter++) {
    array_push($hset, $counter);
    if ($counter % 2 == 0) {
        array_push($hset, $counter);
        array_push($hset, $counter + 1);
    }
}

    return count($hset);
}

echo func(561);

它返回 1123。请帮忙。

最佳答案

C++ 的 unordered_set不允许重复元素。由于您要将 countercounter+1 压入,因此您通常会尝试将同一元素压入两次,其中一次会被拒绝。

如果您希望具有与 PHP 类似的行为,请使用 std::vector相反,使用 emplace_back (或 push_back )添加您的元素。

如果你想走另一条路,那么在 PHP 中你可以使用 array_unique

关于php - C++ unordered_set 插入插入 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981518/

相关文章:

php - SQL 内连接问题(可能很容易修复)

C++ 异常抛出 : Access violation writing

c++ - CDialog ShowWindow问题

c++ - 使用 mutable 允许修改 unordered_set 中的对象

c++ - STL 无序容器的局部迭代器有哪些用途?

php - 将不同的 CSS 应用于查询的前 10 个结果

php - 连续执行perl脚本

php - 为什么我的 PHP 表单验证不起作用?

c++ - 当编译器从代码中取出所有空格和注释时,GCC 如何知道错误发生在哪一行?

c++ - 使 std::unordered_set 的嵌套类型可散列