RamRick
RamRick

Reputation: 51

lua array into c++ array

 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

Alright, so I am trying to get into C++ right now step by step. Right now I am trying to figure out how (complicated?) arrays in C++ are created. As I have no idea how to explain it in another way, I did it in LUA as that is what I know best. The function is not the important thing, the important thing is the array because I have searched around for a few hours now but I can not figure out how to get the array you see in lua done in C++.

Upvotes: 4

Views: 796

Answers (2)

IllusiveBrian
IllusiveBrian

Reputation: 3224

It looks like what you have in the question is equivalent to 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
}

Upvotes: 2

Ragav
Ragav

Reputation: 325

Welcome to C++, Basically i think it can be achieved by using the MAP functionality of the C++. MUlti-Map Also Can be referred.

Sample Snippet May be Goes like this:(Just for understanding the @D Way of Thinking to correlate in your example )

eg:

INPUT:

//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++)
{

}

OUTPUT:

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

Upvotes: 1

Related Questions