2D array literals in C++ - c++

I'm trying to construct a 2D array in the form of pointers-to-pointers. This doesn't work:
bool** data = {
new bool[4] {true, true, true, true},
new bool[4] {true, false, false, true},
new bool[4] {true, false, false, true},
new bool[4] {true, true, true, true}
};
Is it possible? How should I be doing it?
EDIT:
Looks like I might be trying to do the wrong thing. I have a function that takes a 2D array of bools of an unknown size, along with integer width and height, as arguments. At present, the signature is:
foo(bool** data, int width, int height)
I want to be able to construct a literal for data, but I also need this function to work for any size of array.

You could have an array of arrays (sometimes referred to as a multi-dimensional array):
bool data[][4] = {
{true, true, true, true},
{true, false, false, true},
{true, false, false, true},
{true, true, true, true}
};
However, that isn't convertible to bool**, so if you need that conversion then this won't work.
Alternatively, an array of pointers to static arrays (which is convertible to bool**):
bool data0 = {true, true, true, true};
bool data1 = {true, false, false, true};
bool data2 = {true, false, false, true};
bool data3 = {true, true, true, true};
bool * data[] = {data0, data1, data2, data3};
or if you really want dynamic arrays (which is almost certainly a bad idea):
bool * make_array(bool a, bool b, bool c, bool d) {
bool * array = new bool[4];
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
return array;
}
bool * data[] = {
make_array(true, true, true, true),
make_array(true, false, false, true),
make_array(true, false, false, true),
make_array(true, true, true, true)
};
or, perhaps, you could stick with arrays, and modify your functions to take references to arrays rather than pointers, inferring the dimensions as template parameters if you need to support different dimensions. This is only possible if the dimensions are always known at compile time.
template <size_t N, size_t M>
void do_something(bool (&array)[N][M]);
do_something(data);

bool data_[][4] = {
{true, true, true, true},
{true, false, false, true},
{true, false, false, true},
{true, true, true, true}
};
bool *data[4] = { data_[0], data_[1], data_[2], data_[3] };

bool *data[] = {
(bool []){true, true, true, true}
,(bool[]) {true, false, false, true}
,(bool[]) {true, false, false, true}
,(bool[]) {true, true, true, true}
};
This is convertible to bool** as you wish. This is not an array of arrays. This is an array of pointers.
By prefacing each row with (bool []) we enable it to decay to a pointer. Each row is therefore a pointer, and can then be brought together into an array of four pointers.
Edit: You can drop the explicit 4 inside the [braces], as it can be deduced by the compiler.

Related

Why with BasedOnStyle: Google every time I copy/paste it "adds" a indentation?

Here's my settings:
{
"C_Cpp.errorSquiggles": "Enabled",
"C_Cpp.intelliSenseEngine": "Default",
"C_Cpp.intelliSenseEngineFallback": "Disabled",
"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}",
"workbench.sideBar.location": "right",
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
},
"editor.formatOnPaste": true,
"editor.formatOnType": true,
"terminal.integrated.shell.windows": "C:/msys64/usr/bin/bash.exe",
"terminal.integrated.shellArgs.windows": [ "-i" ],
"terminal.integrated.env.windows": {
"MSYSTEM": "MINGW64",
"PATH" : "/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/"
}
}
It correctly format braces as:
void myCode() {
}
and not:
void myCode()
{
}
but when I copy/paste, it also add a new indention, such as:
void myCode() {
}
Expecially when there are some code before this.
Why? How can i fix it?
EDIT: here's a practical example. This is the code I have:
struct Test : Module
{
enum ParamIds {
TRIGGER_PARAM,
CYCLE_PARAM,
RATE_PARAM,
RATE_FINE_PARAM,
RISE_LENGTH_PARAM,
NUM_PARAMS
};
enum InputIds
{
TRIGGER_INPUT,
TAIL_LENGTH_CV_INPUT,
NUM_INPUTS
};
enum OutputIds {
EOR_OUTPUT,
EOF_OUTPUT,
EOC_OUTPUT,
RISING_OUTPUT,
FALLING_OUTPUT,
OUT_OUTPUT,
NUM_OUTPUTS
};
};
If now within InputIds I paste a value in that empty space, that's the result:
struct Test : Module
{
enum ParamIds {
TRIGGER_PARAM,
CYCLE_PARAM,
RATE_PARAM,
RATE_FINE_PARAM,
RISE_LENGTH_PARAM,
NUM_PARAMS
};
enum InputIds {
TRIGGER_INPUT,
ASD_PARAM,
TAIL_LENGTH_CV_INPUT,
NUM_INPUTS
};
enum OutputIds {
EOR_OUTPUT,
EOF_OUTPUT,
EOC_OUTPUT,
RISING_OUTPUT,
FALLING_OUTPUT,
OUT_OUTPUT,
NUM_OUTPUTS
};
};
As you can see, it adds a tab and mess the whole code.

Break after braces in initializer

I am looking on how to make clang-format allowing this format:
std::vector<MyStruct> data =
{
{
0,
true
},
{
1,
false
}
}

regular expression not between alphanumeric

I would like to identify the string "mystring" in a text (actually a R code), but ensuring that it is a variable name:
it should not be part of a longer variable such as "thisismystring" or "mystringisnice". I guess this can be done by excluding (?!([[:alnum:]]){1}) before and after "mystring"?
It can however be at the beginning of a line (such as "\nmystring") so we have to be careful about this type of exception
What is the best approach for that?
Edit: unit test
pattern = "\\bmystring\\b"
identical(grepl(pattern = pattern,
x = c("thisismystring","mystringisnice","\nmystring", "mystring", "mystring=", "mystring(", " mystring","mystring\n", "6mystring", "mystring0", "= mystring(", "=mystring",
"hop
mystring")),
c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE))
Just use the \b (word boundary) token:
\\bmystring\\b
unit test
pattern = "\\bmystring\\b"
`==`(grepl(pattern = pattern,
x = c("thisismystring","mystringisnice","\nmystring", "mystring", "mystring=", "mystring(", " mystring","mystring\n", "6mystring", "mystring0", "= mystring(", "=mystring",
"hop
mystring")),
c(FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE))
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Table tests for multi-return value function

I'm cutting my teeth on Go and after digging into table driven tests I ran into the following problem:
I have a function that returns multiple values
// Halves an integer and and returns true if it was even or false if it was odd.
func half(n int) (int, bool) {
h := n / 2
e := n%2 == 0
return h, e
}
I know that for half(1) the return value should be 0, false and for half(2) it should match 1, true, but I can't seem to figure out how to put this on a table.
How would one go to have something that resembles the following?
var halfTests = []struct {
in int
out string
}{
{1, <0, false>},
{3, <1, true>},
}
Is there any other, more idiomatic way of doing this?
For reference, here's a test for something that resembles a FizzBuzz function, using tables:
var fizzbuzzTests = []struct {
in int
out string
}{
{1, "1"},
{3, "Fizz"},
{5, "Buzz"},
{75, "FizzBuzz"},
}
func TestFizzBuzz(t *testing.T) {
for _, tt := range fizzbuzzTests {
s := FizzBuzz(tt.in)
if s != tt.out {
t.Errorf("Fizzbuzz(%d) => %s, want %s", tt.in, s, tt.out)
}
}
}
Just add another field to your struct that holds the second return value. Example:
var halfTests = []struct {
in int
out1 int
out2 bool
}{
{1, 0, false},
{3, 1, true},
}
Your testing function would look like the following:
func TestHalf(t *testing.T) {
for _, tt := range halfTests {
s, t := half(tt.in)
if s != tt.out1 || t != tt.out2 {
t.Errorf("half(%d) => %d, %v, want %d, %v", tt.in, s, t, tt.out1, tt.out2)
}
}
}

Converting Mathematica list of values into boolean list

First of all, sorry for the confused title.
What I want to do is to convert {1, 4, 9} to:
{True, False, False, True, False, False, False, False, True}
That is, only the indexes from the first list will have value True, the rest will be False.
I sense there is some really simple solution, but I am quite new to both Mathematica and functional programming. I could do it iteratively, in a loop, but there has to be something that works with the list as a whole. Right? :)
Thanks for your help.
EDIT: to show that I tried to do something before I asked, here's my progress so far:
first={1,4,9}
ReplacePart[Table[False, {x, Max[first]}], {1} -> True]
(* gives {True, False, False, False, False, False, False, False, False} *)
Unfortunately, it doesn't work with {1,4,9} -> True, but would work with {1 -> True, 4 -> True, 9 -> True}. But I don't know how to get to that...
EDIT 2: got it.
ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]
I'd still love to see your solutions! This one seems like an ugly hack to me ... :)
Here's a simple approach:
first = {1, 4, 9};
list = ConstantArray[False, Max#first];
list[[first]] = True;
list
Out[1]= {True, False, False, True, False, False, False, False, True}
Here's the above solution written as a convenient function:
Clear[convertIndices]
convertIndices[index_List] :=
Module[{list = ConstantArray[False, Max#index]},
list[[index]] = True; list]
Usage:
convertIndices#{1, 4, 9}
Out[2]= {True, False, False, True, False, False, False, False, True}
I would use SparseArray for this operation. In my opinion it is very easy to understand, and it is also efficient, especially when a low percentage of indices are True.
true = {1, 4, 9};
SparseArray[(List /# true) -> True, Automatic, False]
Alternatively with Transpose (which looks better when pasted into Mathematica):
SparseArray[{true}\[Transpose] -> True, Automatic, False]
You can use Normal if you must convert the output to a normal array, but most operations will not require that.
Also, sacrificing practicality for terseness:
#==1 & /# SparseArray[List /# true -> 1]
Actually, I would have used Yoda's answer myself, but here's an alternative:
first = {1, 4, 9};
MemberQ[first, #] & /# Range[Max[first]]
(* ===> {True, False, False, True, False, False, False, False, True}*)
Or this one:
Or ### Outer[Equal, Range[Max[first]], first]
(* ===> {True, False, False, True, False, False, False, False, True}*)
Both have the advantage that they skip Yoda's ConstantArray initialization step.