获取密钥相等(如果密钥存在于地图中)或严格小于地图中的给定输入

时间:2017-01-04 02:31:39

标签: c++ stl stdmap

我将numberOfItems个键作为输入并将它们放在这样的地图中:

int numberOfItems;
int query;
scanf("%d",&numberOfItems);
int temp;
map<int,int> iimap;
for(int i=0;i<numberOfItems;i++)
{
    scanf("%d",&temp);
    iimap.insert(make_pair(temp,1));
}
printf("Enter query: ");
scanf("%d",&query);
int VstrictlyLessOrEqual = FstrictlyLessOrEqual(query);

我为每个输入设置了默认键= 1;因此,不存在的键具有值= 0。

  

6 100 5 4 3 2 1 50

对于此输入(第一个输入6为numberOfItems&amp;最后一个输入50为queryFstrictlyLessOrEqual()应返回值5

2 个答案:

答案 0 :(得分:2)

您想使用std::map upper_bound()lower_bound()方法:

UPPER_BOUND()

upper_bound()返回第一个密钥的迭代器,该密钥高于搜索的密钥。所以:

  1. 致电upper_bound()

  2. 如果upper_bound()返回begin(),则表示搜索的内容低于地图中的最低密钥。

  3. 否则减少迭代器。现在它将指向一个等于所搜索的密钥的密钥,或者指向下一个较小的密钥。

  4. LOWER_BOUND()

    lower_bound()返回地图中第一个键的迭代器,该迭代器等于或大于搜索到的键,因此为了实现您的目标,您需要:

    1. 致电lower_bound()

    2. 检查lower_bound()是否未返回end(),并且迭代器的键与您搜索的密钥相同。密钥存在于地图中。

    3. 否则,请检查lower_bound()是否返回了地图的begin()迭代器值。如果是这样,这意味着您搜索的密钥低于地图中的第一个密钥,因此存在此值。

    4. 否则,递减返回的迭代器。您搜索的键在地图中不存在,并且递减的迭代器指向地图中下一个最小的键。

答案 1 :(得分:0)

如果不需要键的默认顺序(Sub searchrange2() With Range("A2", Cells(Rows.Count, 1).End(xlUp)) ' reference active sheet column A cells from row 2 down to last not empty one .Offset(, 3).FormulaR1C1 = "=IF(RC3=505,""A"",RC1)" ' write referenced cells offset three column to the right (i.e. column D) with a formula that places an "A" if corresponding column C cell content is 505, otherwise the content of corresponding column A cell .Value = .Offset(, 3).Value ' write formula result in column A cells .Offset(, 3).ClearContents ' clear "helper" column D End With End Sub ),则只需将std::less用作std::greater并进行一次key_compare调用就可以解决问题。< / p>

lower_bound()