c++ - 与 std::pairs 初始化混淆

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

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

error C2439: 'std::pair::first' : member could not be initialized

error C2440: 'initializing' : cannot convert from 'int' to 'const AnalyticsToolKit::ParcelPassingLogic::ParticipantNode &'

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

附言我也是用的Qt包,QHash和unordered_map基本一样,QStrings像std::string,但是可以作为hash key。

任何帮助将不胜感激!!

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];

最佳答案

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

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

关于c++ - 与 std::pairs 初始化混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808060/

相关文章:

c++ - 当在类主体中使用 unique_ptr 声明析构函数作为同一类的成员时出现编译器错误

c++ - 如何在 Qt 中导出新的基本文件名?

javascript - 在 URL 中使用多个片段标识符

ruby-on-rails - Ruby:如何有效地对两个哈希数组执行 "left join"

c++ - 查看返回值?

c++ - 使用 ref-qualifiers 的重载决议

c++ - 二维数组分配,C++

c++ - 如何最小化QDialog?

qt - QJsonValue 的转换方法始终返回其默认值

algorithm - 为所有字谜生成相同的唯一哈希码