【问题标题】:How to convert this C# script to native C++?如何将此 C# 脚本转换为本机 C++?
【发布时间】:2013-04-23 18:39:52
【问题描述】:

我是 C++ 的初学者。在我使用 C# 之前。 Bellow 是一个 C# 脚本。我如何在原生 C++ 中做同样的事情?

我只需要:

  • 列表或类似列表具有 int-int 键值对
  • 可以按值自动排序。如果不是,它必须是可按键排序的,它可以得到一个索引 价值(我的每一个价值都是确定的)

我尝试了std::map,但它没有内置的按值排序或按值获取键。 C++ 是否在 c# 中有类似 sortedlist 的东西?

非常感谢!

public static SortedList<int, int> sortedList1 = new SortedList<int, int>();

static void List_Add(int i) // 0 < i < 1000
{
    if (!sortedList1.ContainsValue(i))
        sortedList1[Environment.TickCount] = i;
}

static void List_Remove(int i) // 0 < i < 1000
{
    if (sortedList1.ContainsValue(i))
        sortedList1.RemoveAt(sortedList1.IndexOfValue(i));
}

static int List_toInt()
{
    int time = 0;
    int keys = 0;
    bool modifier = false;
    foreach (KeyValuePair<int, int> i in sortedList1)
    {
        if (i.Value > 90) modifier = true;
        if (i.Key - time > 200 | modifier | keys > 1000)
        {
            keys = keys * 1000 + i.Value;
            time = i.Key;
        }
    }
    return keys;
}

【问题讨论】:

    标签: c++ sorting keyvaluepair


    【解决方案1】:

    您似乎做错了事,因为通常事情是使用键排序的,而查询是使用键而不是使用值来完成的。但是,似乎std::map&lt;int,int&gt; 会在这里为您提供帮助。只需将您的值用作地图的键,并将您的键用作值(以便您可以使用该值进行查询)。如果允许重复,请使用多图。

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      这样:

      #include <map>
      #include "Winbase.h"
      
      std::map<int, int> sortedList1;
      
      void List_Add(int i) // 0 < i < 1000
      {
          if (sortedList1.find(i) == sortedList1.end())
              sortedList1.insert(std::make_pair<int, int>(GetTickCount(), i));
      }
      
      void List_Remove(int i) // 0 < i < 1000
      {
          if (sortedList1.find(i) != sortedList1.end())
              sortedList1.erase(sortedList1.find(i));
      }
      
      int List_toInt()
      {
          int time = 0;
          int keys = 0;
          bool modifier = false;
          for (std::map<int, int>::const_iterator it = sortedList1.cbegin(); 
              it != sortedList1.cend(); it++)
          {
              if (it->second > 90) modifier = true;
              if (it->first - time > 200 || modifier || keys > 1000)
              {
                  keys = keys * 1000 + it->second;
                  time = it->first;
              }
          }
          return keys;
      }
      

      【讨论】:

      • 非常感谢! List_Remove如何运作?因为似乎地图没有内置按值查找?
      • List_Add,检查是否有key,不要改变它的值!
      • 如果 sortedList1 有对 (1, 1000) 你的List_Remove(1000) 找到键 1000,没有找到值 1000。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多