与std :: pairs初始化混淆

时间:2015-06-12 16:33:44

标签: c++ qt hash unordered-map std-pair

以下代码在编译时会产生以下错误:

  

错误C2439:'std :: pair :: first':无法初始化成员

     

错误C2440:'初始化':无法从'int'转换为'const AnalyticsToolKit :: ParcelPassingLogic :: ParticipantNode&'

但是当我注释掉底线时,没有这样的错误,所以这对从哈希表传回的方式一定有问题吗?

P.S。我也使用Qt包,QHash与unordered_map基本相同,QStrings就像std :: string,但它们可以用作哈希键。

任何帮助都将非常感谢!!

struct ParticipantNode
{
    QHash<const QString, std::pair<const ParticipantNode&, double> > soldToParticipants;
};

QHash<QString, QHash<QString, ParticipantNode> > mGraphs;


QString buyer = "someString";
QString seller = "someString";
QString security = "someString";
double value = someDouble;

QHash<QString, ParticipantNode>& tradeGraph = mGraphs[security];
ParticipantNode& sellerNode = tradeGraph[seller];
QHash<const QString, std::pair<const ParticipantNode&, double> > sellersSoldToParticipants = sellerNode.soldToParticipants;

std::pair<const ParticipantNode&, double> tradeDetails = sellersSoldToParticipants[buyParticipant];

1 个答案:

答案 0 :(得分:2)

我对QT一无所知,但如果QHashunordered_map类似,那么问题就在于您使用operator[]的问题。如果给定键不存在,该函数将插入默认构造的值。为此,value-type必须是默认可构造的,并且:

std::pair<const ParticipantNode&, double>

不是默认构造的,因为const ParticipantNode&不是默认构造的。

您将不得不使用find()或QT相当于它:

auto it = sellersSoldToParticipants.find(buyParticipant);
if (it != sellersSoldToParticipants.end()) {
    std::pair<const ParticipantNode&, double> tradeDetails = it->second;
}