java to c++?

S

SneakyElf

i have written code in java, how would it look in c++?

int amtOfLetters = currInput.length;
HashMap letters = new HashMap(amtOfLetters);
for(int currCharPos = 0; currCharPos < amtOfLetters; currCharPos++) {
if (letters.get(currInput[currCharPos]) == null) {//doesn't exist yet
letters.put(currInput[currCharPos], 1)
} else {//if it is already there
letters.put(currInput[currCharPos],
letters.get(currInput[currCharPos]) + 1)

thank you.
 
G

Guest

i have written code in java, how would it look in c++?

int amtOfLetters = currInput.length;

Is currInput some kind of array of characters?
HashMap letters = new HashMap(amtOfLetters);

Is using a hashmap necessary, would a normal map work just as well?
for(int currCharPos = 0; currCharPos < amtOfLetters; currCharPos++) {
if (letters.get(currInput[currCharPos]) == null) {//doesn't exist yet
letters.put(currInput[currCharPos], 1)
} else {//if it is already there
letters.put(currInput[currCharPos],
letters.get(currInput[currCharPos]) + 1)

If the answers to both questions above are yes, then the following
should do:

std::vector<char> currInput;
// --> Add letters to currInput here <--

std::map<char, size_t> letters; // The map

for (size_t i = 0; i < currInput.size(); ++i)
{
++letters[currInput];
}
 
J

Jerry Coffin

i have written code in java, how would it look in c++?

int amtOfLetters = currInput.length;
HashMap letters = new HashMap(amtOfLetters);
for(int currCharPos = 0; currCharPos < amtOfLetters; currCharPos++) {
if (letters.get(currInput[currCharPos]) == null) {//doesn't exist yet
letters.put(currInput[currCharPos], 1)
} else {//if it is already there
letters.put(currInput[currCharPos],
letters.get(currInput[currCharPos]) + 1)

If you really wanted to, you could probably get that code to compile as
C++, so it'd like precisely identical. Then again, you probably don't
really want that.

The obvious version in C++ would be something like:

std::map<char, int> letters;

for (int i=0; i<currInput.length(); ++i)
++letters[currInput];

OTOH, since you're apparently only using char as the index, you can
pretty easily use a vector instead:

std::vector<int> letters(UCHAR_MAX, 0);

for (int i=0; i<currInput.length(); ++i)
++letters[(unsigned char)currInput];

IIRC, in Java the char type is really 16 bits, but unless you're really
short of memory, using something like 256K for the array is often
reasonable, using extra memory to improve speed. If you want to support
a really complete character set, chances are that an array won't be very
practical though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
474,270
Messages
2,571,353
Members
48,039
Latest member
CrystalLeM

Latest Threads

Top