C++ code to Java, few questions [closed]

The first << is the left shift operator which is the same in C++ and Java.

2 << 5 means 2 shifted left 5 times, and is equal to 32.

The second << in std::cout << u << ' ' is the C++ stream insertion operator, and is used to write variables and constants to a stream. Here, it is equivalent to the Java code:

System.out.print(u);
System.out.print(' ');

The push, front, and pop operations on the C++ std::queue add an item to the end of the queue, look at (but do not remove) the item at the front of the queue, and remove and return the item at the front of the queue, respectively. They map to operations on a Java Queue as follows:

Queue<Integer> fiveQ = new LinkedList<>();
fiveQ.add(5); // fiveQ.push(5); in C++
fiveQ.peek(); // fiveQ.front(); in C++
fiveQ.remove(); // fiveQ.pop(); in C++

The trickiest part about translating this to C++ is the &q and *q part of the code (which does not appear to be correct; I cannot compile it with g++ 5.3.0).

In C++ there are pointers, and references. You can pass around the address of a variable, and read it or modify it through that address. The formal function parameters with & are references; the expression &q is taking the address of the q variable. The expression *q is reading and modifying q via that address. You could use an AtomicInteger in Java, or write a MutableInt class:

public class MutableInt {
    private int value = 0;

    public int get() {
        return value;
    }

    public void set(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }
}

You could then create an instance of this for q and pass it around. The functions that need to access and update its value could then do so.

Good luck.

Leave a Comment