从出现在该值之前的向量 <pair> 添加第二个值

Adding the second values from a vector<pair> which appear before this value

因此,我正在尝试创建一个函数,该函数通过成对向量移动并将 的第二个值与先前值相加到当前目标。但是,我不确定如何向后循环以获取目标之前的所有值。

这是我到目前为止所做的:

int cWeight (KEY_T key) const
{
    int size = _valueToWeightMap.size();

    for (int x = 0; x < size; x++)
    {
        if (_valueToWeightMap[x].first == key && x == 0)
            return _valueToWeightMap[x].second;

        if (_valueToWeightMap[x].first == key && x != 0)
            return _valueToWeightMap[x].second + _valueToWeightMap[x - 1].second;
    }

    return 0;
}

_valueToWeightMap是向量的名称,KEY_T只是一个查找字符串的typename

目前,该函数仅从向量中紧随其后的对中获取次要值,但我希望它从其后面的所有对中获取次要值。我该怎么做呢?

这是我添加到向量中的一些东西。

dist1.add("Helmet", 1);
dist1.add("Boots", 10);
dist1.add("Gloves", 20);
dist1.add("Cloud", 15);
dist1.add("Ring", 4);
dist1.add("Wind", 12);

所以,我想要函数做的是:

  1. 位置 0 的对的第二个值等于 1,因此函数应该 return 一个。
  2. 位置 1 的对子的第二个值等于 10,因此函数应该 return 11. (10 + 1)
  3. 位置 2 的货币对的第二个值等于 20,因此它应该 return 31。(20 + 10 + 1) 等等。

使用 for 循环:

int cWeight (KEY_T key) const
{
    int size = _valueToWeightMap.size();

    for (int x = 0; x < size; x++)
    {
        // Find the appropriate key
        if (_valueToWeightMap[x].first == key)
        {
            // Start with the value of this one
            auto values = _valueToWeightMap[x].second;
            // Add all values lower in the map:
            for (auto i = 0; i < x; ++i)
            {
                values += _valueToWeightMap[i].second;
            }
            return values;
        }
    }

    return 0;
}

这里你不需要对第一种情况进行任何特殊处理。