Confusion with std::pairs initialization

371 views Asked by At

The code below, when compiled produces the following errors:

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

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

When I comment out the bottom line however, there is no such error, so there must be something wrong with the way the pair is being passed back from the hash table?

P.S. I'm also using the Qt package, QHash is basically the same as unordered_map, and QStrings are like std::string, but they can be used as hash keys.

Any help would be much appreciated!!

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

There are 1 answers

2
Barry On BEST ANSWER

I don't know anything about QT, but if QHash is anything like unordered_map, then the issue is where you're using operator[]. That function will insert a default-constructed value for a given key if it doesn't exist. In order to do that, the value-type must be default constructible, and:

std::pair<const ParticipantNode&, double>

is not default-constructible because const ParticipantNode& is not default-constructible.

You will have to use find() instead, or the QT equivalent of it:

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