C ++代码到Java,几乎没有问题

时间:2016-05-15 21:34:40

标签: java c++

我得到了一个代码,但它是我不知道的C ++。 但在我看来,C ++和Java之间有许多相似之处。 我不知道它们的意思/如何用Java编写它们的唯一内容是:

u = getNextUglyNumber(twoQ, threeQ, fiveQ, &q); //and what is &q, the &?

twoQ.push(u << 1); //what is << ?

std::cout << u << ' '; //this i dont understand at all

*q = 2; // same as q = 2*q?

if (fiveQ.front() < u) {
        u = fiveQ.front(); //whats front?

非常感谢您提供任何帮助!

以下是完整的代码:

typedef std::queue<int> Queue;
int findNthUglyNumber(int n) {
    Queue twoQ, threeQ, fiveQ;
    twoQ.push(2);
    threeQ.push(3);
    fiveQ.push(5);
    int u, q;
    while (n) {
        u = getNextUglyNumber(twoQ, threeQ, fiveQ, &q);
        switch (q) {
        case 2:
            twoQ.push(u << 1);           /// u * 2
        case 3:
            threeQ.push(u << 2 - u);     /// u * 3
        case 5:
            fiveQ.push(u << 2 + u);      /// u * 5
        }
        n--;
        std::cout << u << ' ';
    }
    return u;
}

int getNextUglyNumber(Queue &twoQ, Queue &threeQ, Queue &fiveQ, int &q) {
    int u = twoQ.front();
    *q = 2;
    if (threeQ.front() < u) {
        u = threeQ.front();
        *q = 3;
    }
    if (fiveQ.front() < u) {
        u = fiveQ.front();
        *q = 5;
    }
    switch (*q) {
    case 2:
        twoQ.pop();
        break;
    case 3:
        threeQ.pop();
        break;
    case 5:
        fiveQ.pop();
        break;
    }
    return u;
}

1 个答案:

答案 0 :(得分:1)

第一个<<是左移位运算符,在C ++和Java中是相同的。

2 << 5表示向左移动5次,等于32。

<<中的第二个std::cout << u << ' '是C ++流插入运算符,用于将变量和常量写入流。这里,它等同于Java代码:

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

C ++ push上的frontpopstd::queue操作将一个项目添加到队列的末尾,查看(但不删除)队列前面的项目,并分别删除并返回队列前面的项目。它们映射到Java Queue上的操作,如下所示:

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++

将此转换为C ++的最棘手的部分是代码的&q*q部分(看起来不正确;我无法用g ++ 5.3.0编译它)。

在C ++中有指针和引用。您可以传递变量的地址,并通过该地址读取或修改它。带&的形式函数参数是引用;表达式&q采用q变量的地址。表达式*q正在通过该地址读取和修改q。您可以在Java中使用AtomicInteger,或者编写MutableInt类:

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);
    }
}

然后,您可以为q创建此实例并传递它。然后,需要访问和更新其值的函数可以这样做。

祝你好运。