I have a code on C++ which I have to rewrite on PHP. Weird thing happens for me as I'm PHP programmer and don't know C++ well. This is the code:
#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;
}
Output of the code is: 562
;
I have written PHP code like this:
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);
It returns 1123
. Please help.
C++'s unordered_set
will not allow duplicate elements. Since you are pushing counter
and counter+1
in, you are generally trying to push the same element twice, and one of those times it gets rejected.
If you want to have similar behavior as PHP, use a std::vector
instead, with emplace_back
(or push_back
) to add your elements.
If you want to go the other way, then in PHP you could use array_unique