最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What is the equivalent of C++ std::unordered_map<char, int> in Javascript? - Stack Overflow

programmeradmin8浏览0评论

So I am trying to map the number of times a char appears in a string. I know that in C++ it would be.

std::string str = "AbBAaaaa";
std::unordered_map<char, int> myMap;

for(auto i = str)
{
   ++mymap[i];
}

How would I translate this to JavaScript?

So I am trying to map the number of times a char appears in a string. I know that in C++ it would be.

std::string str = "AbBAaaaa";
std::unordered_map<char, int> myMap;

for(auto i = str)
{
   ++mymap[i];
}

How would I translate this to JavaScript?

Share Improve this question edited Aug 20, 2018 at 0:50 Tas 7,1114 gold badges39 silver badges54 bronze badges asked Aug 20, 2018 at 0:33 Tom OconnorTom Oconnor 4132 gold badges7 silver badges14 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

I would reduce the string into an object indexed by character. The function passed to reduce is called for each element in the input, where the first argument (the a) is the accumulator, which is either the initial value ({} here) or what the last iteration returned. The second argument (the char) is the current character being iterated over.

const str = "AbBAaaaa";
const charCounts = Array.prototype.reduce.call(str, (a, char) => {
  a[char] = (a[char] || 0) + 1;
  return a;
}, {});
console.log(charCounts);

You could also use

const charCounts = [...str].reduce((a, char) => // ...

which is shorter and probably a bit easier to understand at a glance, but unnecessarily creates an intermediate array from the str.

The imperative version of this, with a for loop, would look like:

const str = "AbBAaaaa";
const charCounts = {};
for (let i = 0; i < str.length; i++) {
  const char = str[i];
  charCounts[char] = (charCounts[char] || 0) + 1;
}
console.log(charCounts);

Javascript already has map and you can achieve same result of your C++ app as shown in this snippet

function charOccurances(str) {
  var myMap = {};
  if(str.length!==0){
    for (let i = 0; i < str.length; i++) {
      myMap[str[i]] = (myMap[str[i]] || 0) + 1;
    }
  }
  return myMap;
}

const str = "AbABaaaa";
console.log(charOccurances(str));

发布评论

评论列表(0)

  1. 暂无评论