【问题标题】:lua array into c++ arraylua数组转换成c++数组
【发布时间】:2016-07-05 23:11:31
【问题描述】:
 local pricetagColors = {
    [3242] = {255, 0, 255},
    [6712] = {255, 255, 0}
 }

 function getPricetagColor(itemnumber)
    local r, g, b = 0, 0, 0

    if pricetagColors[itemnumber] then
        r, g, b = pricetagColors[itemnumber][1], pricetagColors[itemnumber][2], pricetagColors[itemnumber[3]
    end

    return {r, g, b}
 end

好的,所以我现在正尝试逐步进入 C++。 现在我正试图弄清楚 C++ 中的(复杂的?)数组是如何创建的。 因为我不知道如何用另一种方式解释它,所以我在 LUA 中做到了,因为这是我最了解的。 函数并不重要,重要的是数组,因为我已经搜索了几个小时,但我不知道如何在 C++ 中完成你在 lua 中看到的数组。

【问题讨论】:

  • 代码中的 id1 和 id2 是什么?
  • 基本上只是一个代表项目的数字,例如第1234章
  • 我稍微编辑了我的代码,这样可能会更清晰一些

标签: c++ arrays lua


【解决方案1】:

看起来您在问题中的内容等同于std::map<int, std::array<int, 3>>。

std::map<int, std::array<int, 3>> pricetagColors;
pricetagColors[3242] = {255, 0, 255};
pricetagColors[6712] = {255, 255, 0};

int itemnumber = 3242, r, g, b;
if (pricetagColors.find(itemnumber) != pricetagColors.end())
{
    r = pricetagColors[itemnumber][0];
    g = pricetagColors[itemnumber][1];
    b = pricetagColors[itemnumber][2]; //Note that the comma operator could be used here, 
                                       //but it isn't really an idiomatic C++ use
}

【讨论】:

  • 谢谢,这正是我想要的。但是有一个问题,我在 pricetagColors 上收到错误消息,说“表达式必须是指向完整对象类型的指针”
  • @RamRick 应该被修复。
【解决方案2】:

欢迎使用 C++,基本上我认为可以通过使用 C++ 的 MAP 功能来实现。 MUlti-Map也可以参考。

示例片段可能是这样的:(只是为了理解与您的示例相关的@D 思维方式)

例如:

输入:

//Declare Map

std::map <int, std::string> stdBindList;
std::map <int, std::string>::iterator pos;

//Add Elements

stdBindList.insert (std::pair<int,std::string>(15,”a”)); // 1
stdBindList.insert (std::pair<int,std::string>(22,”b”)); // 2

stdBindList.insert (std::pair<int,std::string>(12,”c”)); // 3
stdBindList.insert (std::pair<int,std::string>(15,”d”)); // 4
stdBindList.insert (std::pair<int,std::string>(5,”e”)); // 5
stdBindList.insert (std::pair<int,std::string>(5,”f”)); // 6
stdBindList.insert (std::pair<int,std::string>(2,”g”)); // 7

stdBindList.insert (std::pair<int,std::string>(5,”h”)); // 8
stdBindList.insert (std::pair<int,std::string>(5,”i”)); // 9

//iterate and print

for (pos = stdBindList.begin();pos!=stdBindList.end();pos++)
{

}

输出:

+–g
|  2
+–e
|  5
+–c
|  12
+–a
|  15
+–b
|  22

【讨论】:

  • 我遇到的问题(甚至可能不是问题,只是在我的脑海中)是每个数组键的值也是一个数组,而不是简单的字符串或整数或其他任何东西。我想不出在这种情况下我会怎么做。
  • 试试地图(MultiMap)ram的映射!!
猜你喜欢
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多