I would like to get some help with c++.
Im trying to change the array name using value from variable. something like this:
global variables:
string array1[5][5];
string array2[5][5];
in a function:
string var;
if (option1) { var = "array1"; }
if (option2) { var = "array2"; }
var[1][1]="some data";
unfortunately this does not work. is there any way to manage the arrays like this?
Yes, you can use a pointer:
decltype(array1) *ptr{};
if ( option1 ) ptr = &array1;
else if ( option2 ) ptr = &array2;
if ( ptr )
(*ptr)[1][1] = "some data";
No, you can't. You should
string array1[5][5];
string array2[5][5];
string (*var)[5];
if (option1) { var = array1; }
if (option2) { var = array2; }
var[1][1]="some data";
No, there isn't.
You could use another level of array indexing:
string array[2][5][5];
int var;
if(option1) {var = 0;}
if(option2) {var = 1;}
array[var][1][1] = "some data";
Related
I have a list with data that I pull from api. However, I need to make changes on this list (movieList). I need to swap the element at index 0 with the element at index 1. For example:
list[0] = movieA,
list[1] = movieB
then
list[0] = movieB,
list[1] = movieA
The class I intend to do these operations is below:
data class MovieListDto(
val docs: List<Movie>,
val limit: Int,
val offset: Int,
val page: Int,
val pages: Int,
val total: Int
)
fun MovieListDto.MovieListDtoToMovieList(): List<Movie> {
val movieList = mutableListOf<Movie>()
for (movie in docs) {
if (movie._id == "5cd95395de30eff6ebccde5c" ||
movie._id == "5cd95395de30eff6ebccde5b" ||
movie._id == "5cd95395de30eff6ebccde5d"
) {
movieList.add(movie)
}
}
return movieList
}
How can I do this?
You could use a simple extension function for that:
fun <T> MutableList<T>.swap(index1: Int, index2: Int){
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
it can be use like this:
list.swap(0, 1)
val temp = movieList[0]
movieList[0] = movieList[1]
movieList[1] = temp
I think you can use also scope function to swap
movieList[0] = movieList[1].also { movieList[1] = movieList[0] }
use Collections.swap() method in JDK
see https://developer.android.com/reference/java/util/Collections#swap(java.util.List%3C?%3E,%20int,%20int)
I do not know how to pass the value asynchronously to EM_ASM, here's how I try to do it (but JS says it's not a function):
const auto testFunc = [] (const char* data)
{
printf("data: %s\n", data);
}
EM_ASM_(
{
var funcResult = ($0);
var text = "data";
var lengthBytes = lengthBytesUTF8(text) + 1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToUTF8(text, stringOnWasmHeap, lengthBytes);
// exception thrown: TypeError: funcResult is not a function
funcResult(stringOnWasmHeap);
}, testFunc);
The documentation says that you can use a function (em_str_callback_func) of the em_str_callback_func type. But it doesn't say how to use it.
https://emscripten.org/docs/api_reference/emscripten.h.html
I don't know about passing callbacks, but if what you want to do is to return a value from JS, then the docs have such an example: you have to use EM_ASM_INT instead:
int x = EM_ASM_INT({
console.log('I received: ' + $0);
return $0 + 1;
}, 100);
printf("%d\n", x);
The API reference has another example for returning a string:
char *str = (char*)EM_ASM_INT({
var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.';
var lengthBytes = lengthBytesUTF8(jsString)+1;
// 'jsString.length' would return the length of the string as UTF-16
// units, but Emscripten C strings operate as UTF-8.
var stringOnWasmHeap = _malloc(lengthBytes);
stringToUTF8(jsString, stringOnWasmHeap, lengthBytes);
return stringOnWasmHeap;
});
printf("UTF8 string says: %s\n", str);
free(str); // Each call to _malloc() must be paired with free(), or heap memory will leak!
Once you have the value in C you can just call your testfunc directly.
I just started using haxe(moving from AS3).
I'm trying to cast to Array, but it doesn't work, namely I get Cast type parameters must be Dynamic error when I try to compile. Below is the code I use:
var result: Array<String> = cast(["sometext"], Array<String>);
var arr: Array<Int> = new Array<Int>();
arr.push(1);
var vect : Array<Int> = cast(arr, Array<Int>);
var arr1: Array<Int> = [1, 2 ,3];
var vect1 : Array<Int> = cast(arr1, Array<Int>);
var arr2 = [1, 2 ,3];
var vect2 : Array<Int> = cast(arr2, Array<Int>);
Each of these 4 casts doesn't compile and gives the same error "Cast type parameters must be Dynamic". If I change the type parameter to Dynamic it won't work either. It fails with a different error.
Could someone explain why this way of casting is not working and how I can cast to Array?
Other casts:
var i: Int = 1;
var j: Int = cast(i, Int);
var str: String = "str";
var str1: String = cast(str, String);
var instance: CastToArrayTest = new CastToArrayTest();
var instance1: CastToArrayTest = cast(instance, CastToArrayTest);
Work just fine.
I think it's perhaps easier to explain with some sample code:
class Test {
static function main() {
var a = ["foo", "bar"];
$type(a); // Warning : Array<String>
// no need to cast or type simple assignments
var b = a;
$type(b); // Warning : Array<String>
// but lets define `x` as `Dynamic` (or something that we don't know what it is)
var x:Dynamic = ["foo", "bar"];
$type(x); // Warning: Dynamic
// we can simply assign it to an `Array<Dynamic>` variable (but we don't get any runtime checks!)
var c:Array<Dynamic> = x;
$type(c); // Warning: Array<Dynamic>
// we can also simply assign it to an `Array<String>` variable (but we don't runtime checks either!!)
var d:Array<String> = x;
$type(d); // Warning: Array<String>
// (if we want runtime checks, we need to code them with the `Type` apis)
// now, let's say we want to do
// var e:Array<String> = c;
// but that fails with `Type parameters are invariant`...
// we can instead use an unsafe cast
var e:Array<String> = cast c;
$type(e); // Warning: Array<String>
// type parameters are a compile time only feature
trace(showType(a), showType([1,2]));
trace(Std.is(a, Array), Std.is([1,2], Array));
// safe casts only check the current object (not its children), so we need to use them with `Dynamic` parameters
var f = cast(x, Array<Dynamic>);
$type(f); // Warning: Array<Dynamic>
// however, due to variance, we can't assign a the safe cast result of type `Array<Dynamic` to a `Array<String>` variable without an unsafe cast...
// which makes sense: our safe cast only checks that the object is an array, but the array doesn't know its own type nor has the safe cast checked the types of the children
}
static function showType(v:Dynamic)
{
switch Type.typeof(v) {
case TClass(cl):
return Type.getClassName(cl);
case other: // TODO handle other types
return Std.string(other);
}
}
}
You can play with this live at Try Haxe #CCaD5.
Putting in another way, here's how your "cast" examples would usually work and look like:
var result: Array<String> = cast ["sometext"];
var arr: Array<Int> = new Array<Int>();
arr.push(1);
var vect : Array<Int> = arr;
var arr1: Array<Int> = [1, 2 ,3];
var vect1 = arr1;
var arr2 = [1, 2 ,3];
var vect2 = arr2;
var i: Int = 1;
var j: Int = i;
var k = j;
var str: String = "str";
var str1: String = str;
var str2 = str1;
var instance: CastToArrayTest = new CastToArrayTest();
var instance1: CastToArrayTest = instance;
var instance2 = instance1;
You can see this live (with some additional info) at Try Haxe #97ADc.
I don't know if my title is right but I am trying to eliminate duplicate so I think I should put this definitions in an array. Can someone suggest me how I could put the pButtons in array? I am thinking something like pButton[EButtonHost], pButton[EButtonUsername] etc.
#define pButtonHost static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonHost])
#define pButtonUsername static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonUsername])
#define pButtonPassword static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonPassword])
I have a method below like this.
XIniFile readIniFile;
readIniFile.open(k_systemIniFile, EIniReadOnly);
string data;
readIniFile.readString("Server", "host", data);
pButtonHost->setString(data);
m_host = pButtonHost->getString();
readIniFile.readString("Server", "username", data);
pButtonUsername->setString(data);
m_username = pButtonUsername->getString();
readIniFile.readString("Server", "password", data);
pButtonPassword->setString(data);
m_password = pButtonPassword->getString();
They look like duplicates so I am trying to optimize it. Thanks!
Update:
I have something like this now. Would this be right? or do you have any better suggestions?
for (int i = 0; i < 3; ++i) {
readIniFile.readString("Server", k_dataList[i], data);
static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->setString(data);
m_pData[i] = static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->getString();
}
A below code looks clear by using auto and `lambda',
auto GetConfigInfo = [&](string section_name, ButtonType btn_type)-> string
{
readIniFile.readString("Server", section_name, data);
m_pButtonList[btn_type_]->setString(data);
return m_pButtonList->getString();
};
m_host = GetConfigInfo("host", EButtonHost);
m_username = GetConfigInfo("username", EButtonUserName);
m_password = GetConfigInfo("password", EButtonPassword);
and a define data type by using struct can be other method.
struct ConfigDefine
{
string section_;
ButtonType btn_type_; //your enum button type, such as EButtonHost, EButtonUserName
string& result_;
}configs[] =
{
{"host", EButtonHost, m_host},
{"username", EButtonUserName, m_username},
{"password", EButtonPassword, m_password}
};
for_each(std::begin(configs), std::end(configs), [&](ConfigDefine& config)
{
readIniFile.readString("Server", config.section_, data);
m_pButtonList[config.btn_type_]->setString(data);
config.result_ = pButtonHost->getString();
});
Do you intend to have something like this one?
#define ASIZE 3
int indx[ASIZE] = {EButtonHost, EButtonUsername, EButtonPassword};
string s[ASIZE] = {"host", "username", "password"};
string *m[ASIZE] = {&m_host, &m_username, &m_password};
for (int i = 0; i < ASIZE; i++) {
readIniFile.readString("Server", s[i].c_str(), data);
pButtonHost->setString(data);
*m[i] = pButtonHost->getString();
}
i'd like to "define" 2 variables as 1 new variable, which then contains the contents/data of both previous variables.
Let's say the first variable is called 'var A' and the second 'var B',
can i combine those 2 in a new variable simply like this?
var ALL = var A + var B;
..or how is the correct syntax for this?
I hope this isn't too abstract? ;)
var A and B are both variables defining external geojson files, and I'd like to be able to "combine" these 2 in 1 new variable.
I would recommend using a function to handle combining them.
function combine(A,B) {
var C = {};
C.stuff_from_A = A.some_info;
C.stuff_from_B = B.some_info;
return C;
}
now you can perform what you ask.
var C = combine(A,B);
EDIT:
An example involving location data:
function combine(A,B) {
var C = {};
C.position_of_A = A.coordinate_info;
C.position_of_B = B.coordinate_info;
return C;
}
or to store the midpoint between them:
function combine(A,B) {
var C = {};
C.midpoint = average(A.location,B.location);
return C;
}
or more generally:
function combine() {
var C = {}; // Initialize
// Logic to combine and store info
return C; // Return the new object
}
EDIT 2
C.totalMarkers = [];
for (var i = 0; i < numberOfMarkersInA; i++) {
C.push(A.getMarker(i));
}
for (var i = 0; i < numberOfMarkersInB; i++) {
C.push(B.getMarker(i));
}
That is pseudo-code, those variable names will need to changed of course.
If there are the objects - serialize they and add with separator. If there is simple string, number, bool or something else, add with separator directly.
Sounds like you want to merge 2 geojson files into one. According to this answer, the concat method should do it for you:
var finalObj = json1.concat(json2); // Merge the 2 files together.