如何在C ++中实现Java中的Pair类[重复]

问题描述 投票:-6回答:3

这个问题在这里已有答案:

如何在C ++中实现Java中的类对,如何在C ++中使用?

java c++ class std-pair
3个回答
0
投票

当我这样做时,我做了类似于标准库中的Map.Entry<K, V>接口。您应该覆盖Object.equals(Object)Object.hashCode(),以便键和值在逻辑上彼此相等的两对在逻辑上相等并且散列相同 - 请参阅Bloch的Effective Java的第9项,以获取有关如何执行良好实现的一些指示。

这是我做的:

@Override
public String toString() {
    //same convention as AbstractMap.SimpleEntry
    return key + "=" + value;
}

@Override
public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Pair)) return false;

    Object otherKey = ((Pair<?, ?>)o).getKey();
    Object otherValue = ((Pair<?, ?>)o).getValue();
    return (key == null ? otherKey == null : key.equals(otherKey))
            && (value == null ? otherValue == null
                    : value.equals(otherValue));
}

@Override
public int hashCode() {
    return 17 + 55555 * (key == null ? 72 : key.hashCode())
            + 232323 * (value == null ? 73 : value.hashCode());
}

-1
投票
class Pair<F,S> {
    private F first;
    private S second;

    public Pair(F first, S second) { 
        this.first = first;
        this.second = second;
    }

    public F getFirst() { return first }
    public S getSecond() { return second }
}

-1
投票

您只需要包含正确的标题

#include <utility>
#include <string>

using std::string;
using std::makepair;
using std::pair;

void foo()
{
    string hello("Hello");
    float  value(42);

    auto p = makepair(hello, value); // or: pair<string, float> = ...
}
© www.soinside.com 2019 - 2024. All rights reserved.