C++ 从向量中添加第二个值<;配对>;显示在此值之前的
所以,我试图创建一个函数,它通过一对向量进行移位,并将的第二个值与之前的值相加到当前目标。但是,我不确定如何向后循环以获取目标之前的所有值 以下是我迄今为止所做的工作:C++ 从向量中添加第二个值<;配对>;显示在此值之前的,c++,loops,stdvector,std-pair,C++,Loops,Stdvector,Std Pair,所以,我试图创建一个函数,它通过一对向量进行移位,并将的第二个值与之前的值相加到当前目标。但是,我不确定如何向后循环以获取目标之前的所有值 以下是我迄今为止所做的工作: int cWeight (KEY_T key) const { int size = _valueToWeightMap.size(); for (int x = 0; x < size; x++) { if (_valueToWeightMap[x].first == key &
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;
}
所以,我想要函数做的是:
对循环使用
:
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;
}
int-cWeight(键)常量
{
int size=_valuetowightmap.size();
用于(int x=0;x
在这里,对于第一种情况,您不需要任何特殊处理。将的第二个值与以前的值相加到当前目标中。我不太明白您的意思。用示例数据添加一些文本描述,以及您希望看到函数对数据所做的操作将非常有用。我同意,这有点不清楚。您可以展示一个小样本数据,并解释您希望如何对其进行操作,这样您的问题将受益匪浅。@RSahu修复了它@塔斯希望这能增加更多的清晰度
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;
}