I have a code where I am inserting a struct in a unordered_map.
INFO Info( v1, UINT_MAX, v3, v4, v5 );
hmap_.insert( std::pair< key,INFO >( v1, Info ) );
at the above line I put a break point using gdb and Print the value of all the variables: All are fine gets printed as expected.
(gdb) p Info
$4 = {v1_ = valid_value, v2 = valid_value, v3 = , v4 = valid_value, v4 = valid_value}
Now when I go into the insert function of hash map using
(gdb) s
I get
(gdb) s
std::pair<unsigned long, namespace::class::Info>::pair<unsigned long&, namespace::class::Info&, true> (this=0x7fffffffd7e0, __x=#0x7fffffffd768: 1100000000000549, __y=...) at /usr/include/c++/7/bits/stl_pair.h:331
331 : first(std::forward<_U1>(__x)), second(std::forward<_U2>(__y)) { }
(gdb) n
Thread 1 "test_1" received signal SIGFPE, Arithmetic exception.
0x000055555556b105 in std::__detail::_Mod_range_hashing::operator() (this=0x555555e09ec0, __num=1100000000000549, __den=0) at /usr/include/c++/7/bits/hashtable_policy.h:448
448 { return __num % __den; }
As it can be seen in the gdb: while hashing it makes the denominator, which it produces from the second variable whose value I have printed and its correct, Zero (__den =0 ) !
I have a struct Info in another file with a normal constructor:
struct INFO
{
Info():
v1_( 0 ), v2_( UINT_MAX ), v_3( INVALID ),
v4_( 0 ), v5_( 0 )
{}
Info( value_type1 v1, const value_type2& v2,
value_type3 v3, value_type4 v4, value_type5 v5 ):
v1_( v1 ), v2_( v2 ),
v3_( side ), v4_( v4 ), v5_( v5 )
{}
value_type1 v1_ ;
value_type2 v2_ ;
value_type3 v3_ ;
value_type4 v4_ ;
value_type5 v5_ ;
};
Why would while hashing the denomator which is I guess is getting created from the second value of the pair which is a valid value will become zero and generate an arithmetic exception.
Thanks
Related
I'm using std::array<array<float, 4,3> = . . . to in
I'm having trouble understand how to format the following code so I don't get the following error:
g++ array2d_colors.cpp -o array2dcolors.o
array2d_colors.cpp: In function ‘void arrayStart()’:
array2d_colors.cpp:36:7: error: too many initializers for
‘std::array<std::array<float, 4ul>, 3ul>’ };
^
using namespace;
array<array<float,4>,3> color = {
{ 0.0 , 0.1686 , 0.2117 },
{ 0.0274 , 0.2117 , 0.2588},
{ 0.3450 , 0.4313 , 0.4588},
{ 0.3960 , 0.4823, 0.5137}
};
This code worked in another study:
using namespace;
array<array<float, 2>, 2> a1 = {{{5,6},{7,8}}};
That is a lot of "{'s" . What if a want to create a 16x3?
I'd appreciate some help.
When you're doing
array<array<float,4>,3> color
you're saying that the inner array has 4 elements and the outer one has 3. So it becomes a 4*3 matrix while you're defining a 3*4 matrix.
Try doing :
array<array<float,3>,4> color = {{
{ 0.0 , 0.1686 , 0.2117 },
{ 0.0274 , 0.2117 , 0.2588},
{ 0.3450 , 0.4313 , 0.4588},
{ 0.3960 , 0.4823, 0.5137}
}};
and remember to add {{ - two braces before defining the array of inner arrays and you'll be good to go!
You have the initializer arrays transposed to a 4 x 3 array. Hence, it does not match the declaration of color.
You can use:
array<array<float, 3>, 4> color =
{
{ 0.0 , 0.1686 , 0.2117 }, // 1st of four of the outer array
{ 0.0274 , 0.2117 , 0.2588},
{ 0.3450 , 0.4313 , 0.4588},
{ 0.3960 , 0.4823, 0.5137} // 4th of four of the outer array
};
If you need to have a 3 x 4 array, you have to change the initializer array.
Ex:
array<array<float, 4>, 3> color =
{
{ 0.0 , 0.1686 , 0.2117, 1 }, // 1st of three of the outer array
{ 0.0274 , 0.2117 , 0.2588, 2},
{ 0.3960 , 0.4823, 0.5137, 3} // 3rd of three of the outer array
};
Issue 1: Dimensions are swtitched
array<array<float,3>,4> color = {
// ^ ^
Issue 2: Explicitly mention the type of array in initializer. Compiler can't deduce it.
array<float,3>{ 0.0 , 0.1686 , 0.2117 },
// ^^^^^^^^^^^^
{ 0.0274 , 0.2117 , 0.2588},
{ 0.3450 , 0.4313 , 0.4588},
{ 0.3960 , 0.4823, 0.5137}
Related to my previous question, I have tried to make a function present() for checking the presence of an optional argument. However, the following code
proc present( x ) { return x.type != void; }
proc test( a: ?T = _void )
{
writeln();
writeln( "test| a = ", a );
writeln( "test| condition = ", a.type != void );
writeln( "test| present( a ) = ", present( a ) );
if present( a ) // error (Line 1)
// if a.type != void // works (Line 2)
{
a = 10;
}
}
// no optional arg
test();
// pass an optional array
var arr: [1..5] int;
test( a = arr );
writeln();
writeln( "main| arr = ", arr );
gives a compile-time error
mytest.chpl:3: In function 'test':
mytest.chpl:13: error: illegal lvalue in assignment
mytest.chpl:13: error: a void variable cannot be assigned
which says that the line a = 10; is problematic. On the other hand, if I use Line 2 instead of Line 1, the code works as expected:
test| a =
test| condition = false
test| present( a ) = false
test| a = 0 0 0 0 0
test| condition = true
test| present( a ) = true
main| arr = 10 10 10 10 10
Also, if I replace Line 1 or 2 by if isArray( a ), the code also works. Does this mean that we need to let the compiler explicitly know that the line a = 10; is not reached when a is _void? (In other words, is present() not sufficient to let the compiler know it because the test condition is "hidden" inside present()?)
Does this mean that we need to let the compiler explicitly know that
the line a = 10; is not reached when a is _void? (In other words, is
present() not sufficient to let the compiler know it because the test
condition is "hidden" inside present()?)
Yes, that's right. The compiler needs to know at compile-time that the body of that if should be compiled only in the case that the argument not void. Putting the x.type != void check in that conditional is a reasonable solution but if you want to have a function to compute if that conditional should be evaluated, you can do so. Just mark present as a param function - which means that it returns a value that should be known at compile-time. Here is the complete example:
proc present( x ) param { return x.type != void; }
proc test( a: ?T = _void )
{
writeln();
writeln( "test| a = ", a );
writeln( "test| condition = ", a.type != void );
writeln( "test| present( a ) = ", present( a ) );
if present( a )
{
a = 10;
}
}
// no optional arg
test();
// pass an optional array
var arr: [1..5] int;
test( a = arr );
writeln();
writeln( "main| arr = ", arr );
If you would like to read more about the language design in this area, see "The Param Return Intent" subsection in "Procedures" chapter section "Return Intents" of the language specification.
Given some mock function which takes at least one parameter:
MOCK_METHOD1(fun, void(int p));
How can i EXPECT_CALL two identical calls in terms of the value of parameter p? I don't care what the value of p actually is, as long as it is the same for both calls to the function fun. I have no way to predict the value of p in the test case.
Option #1
EXPECT_CALL( mock, fun( testing::Truly( []( int p ) {
static int initial = p;
return initial == p;
} ) ) )
.Times( 2 );
Option #2
int p = 0;
testing::Sequence seq;
EXPECT_CALL( mock, fun( _ ) )
.InSequence( seq )
.WillOnce( testing::SaveArg< 0 >( &p ) );
EXPECT_CALL( mock, fun( testing::Eq( testing::ByRef( p ) ) ) )
.Times( 1 )
.InSequence( seq );
What I find really interesting is Fortrans's capability of stencil updates: instead of looping
t2 = v(1)
do i=2, n-1
t1 = v(i)
v(i) = 0.5 * (t2 + v(i+1))
t2 = t1
enddo
one can use a one-liner, without an explicit loop
v(2:n-1) = 0.5 * (v(1:n-2) + v(3:n))
(For this, and other examples see this slideshow)
I haven't anything similar in any other programming language. Is there any other language which supports a similar syntax?
It may be interesting to check the wiki page for Array programming, which says
Modern programming languages that support array programming are commonly used in scientific and engineering settings; these include Fortran 90, Mata, MATLAB, Analytica, TK Solver (as lists), Octave, R, Cilk Plus, Julia, and the NumPy extension to Python...
and also pages for array slicing and a list of array languages. So, several languages seem to have a similar syntax (which goes back to as old as ALGOL68 ?!)
Here are some examples (there may be mistakes so please check by yourself..):
Fortran :
program main
implicit none
real, allocatable :: v(:)
integer i, n
n = 8
v = [( real(i)**2, i=1,n )]
print *, "v = ", v
v(2:n-1) = 0.5 * ( v(1:n-2) + v(3:n) )
print *, "v = ", v
end
$ gfortran test.f90 && ./a.out
v = 1.00000000 4.00000000 9.00000000 16.0000000 25.0000000 36.0000000 49.0000000 64.0000000
v = 1.00000000 5.00000000 10.0000000 17.0000000 26.0000000 37.0000000 50.0000000 64.0000000
Python:
import numpy as np
n = 8
v = np.array( [ float(i+1)**2 for i in range( n ) ] )
print( "v = ", v )
v[1:n-1] = 0.5 * ( v[0:n-2] + v[2:n] )
print( "v = ", v )
$ python3 test.py
v = [ 1. 4. 9. 16. 25. 36. 49. 64.]
v = [ 1. 5. 10. 17. 26. 37. 50. 64.]
Julia:
n = 8
v = Float64[ i^2 for i = 1 : n ]
println( "v = ", v )
v[2:n-1] = 0.5 * ( v[1:n-2] + v[3:n] )
println( "v = ", v )
$ julia test.jl
v = [1.0,4.0,9.0,16.0,25.0,36.0,49.0,64.0]
v = [1.0,5.0,10.0,17.0,26.0,37.0,50.0,64.0]
Chapel:
var n = 8;
var v = ( for i in 1..n do (i:real)**2 );
writeln( "v = ", v );
var vtmp = 0.5 * ( v[1..n-2] + v[3..n] );
v[2..n-1] = vtmp;
writeln( "v = ", v );
$ chpl test.chpl && ./a.out
v = 1.0 4.0 9.0 16.0 25.0 36.0 49.0 64.0
v = 1.0 5.0 10.0 17.0 26.0 37.0 50.0 64.0
(please see wiki pages etc for other languages).
I think the array notation such as : or .. is very convenient, but it can give unexpected results (if not used properly, e.g., the meaning of indices, or a possible overlap of LHS/RHS) or cause run-time overhead (because of temporary arrays), depending on cases. So please take care when actually using it...
I am interested in using Rcpp to create a data frame with a variable number of columns. By that, I mean that the number of columns will be known only at runtime. Some of the columns will be standard, but others will be repeated n times where n is the number of features I am considering in a particular run.
I am aware that I can create a data frame as follows:
IntegerVector i1(3); i1[0]=4;i1[1]=2134;i1[2]=3453;
IntegerVector i2(3); i2[0]=4123;i2[1]=343;i2[2]=99123;
DataFrame df = DataFrame::create(Named("V1")=i1,Named("V2")=i2);
but in this case it is assumed that the number of columns is 2.
To simplify the explanation of what I need, assume that I would like pass a SEXP variable specifying the number of columns to create in the variable part. Something like:
RcppExport SEXP myFunc(SEXP n, SEXP <other stuff>)
IntegerVector i1(3); <compute i1>
IntegerVector i2(3); <compute i2>
for(int i=0;i<n;i++){compute vi}
DataFrame df = DataFrame::create(Named("Num")=i1,Named("ID")=i2,...,other columns v1 to vn);
where n is passed as an argument. The final data frame in R would look like
Num ID V1 ... Vn
1 2 5 'aasda'
...
(In reality, the column names will not be of the form "Vx", but they will be known at runtime.) In other words, I cannot use a static list of
Named()=...
since the number will change.
I have tried skipping the "Named()" part of the constructor and then naming the columns at the end, but the results are junk.
Can this be done?
If I understand your question correctly, it seems like it would be easiest to take advantage of the DataFrame constructor that takes a List as an argument (since the size of a List can be specified directly), and set the names of your columns via .attr("names") and a CharacterVector:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::DataFrame myFunc(int n, Rcpp::List lst,
Rcpp::CharacterVector Names = Rcpp::CharacterVector::create()) {
Rcpp::List tmp(n + 2);
tmp[0] = Rcpp::IntegerVector(3);
tmp[1] = Rcpp::IntegerVector(3);
Rcpp::CharacterVector lnames = Names.size() < lst.size() ?
lst.attr("names") : Names;
Rcpp::CharacterVector names(n + 2);
names[0] = "Num";
names[1] = "ID";
for (std::size_t i = 0; i < n; i++) {
// tmp[i + 2] = do_something(lst[i]);
tmp[i + 2] = lst[i];
if (std::string(lnames[i]).compare("") != 0) {
names[i + 2] = lnames[i];
} else {
names[i + 2] = "V" + std::to_string(i);
}
}
Rcpp::DataFrame result(tmp);
result.attr("names") = names;
return result;
}
There's a little extra going on there to allow the Names vector to be optional - e.g. if you just use a named list you can omit the third argument.
lst1 <- list(1L:3L, 1:3 + .25, letters[1:3])
##
> myFunc(length(lst1), lst1, c("V1", "V2", "V3"))
# Num ID V1 V2 V3
#1 0 0 1 1.25 a
#2 0 0 2 2.25 b
#3 0 0 3 3.25 c
lst2 <- list(
Column1 = 1L:3L,
Column2 = 1:3 + .25,
Column3 = letters[1:3],
Column4 = LETTERS[1:3])
##
> myFunc(length(lst2), lst2)
# Num ID Column1 Column2 Column3 Column4
#1 0 0 1 1.25 a A
#2 0 0 2 2.25 b B
#3 0 0 3 3.25 c C
Just be aware of the 20-length limit for this signature of the DataFrame constructor, as pointed out by #hrbrmstr.
It's an old question, but I think more people are struggling with this, like me. Starting from the other answers here, I arrived at a solution that isn't limited by the 20 column limit of the DataFrame constructor:
// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <string>
#include <iostream>
using namespace Rcpp;
// [[Rcpp::export]]
List variableColumnList(int numColumns=30) {
List retval;
for (int i=0; i<numColumns; i++) {
std::ostringstream colName;
colName << "V" << i+1;
retval.push_back( IntegerVector::create(100*i, 100*i + 1),colName.str());
}
return retval;
}
// [[Rcpp::export]]
DataFrame variableColumnListAsDF(int numColumns=30) {
Function asDF("as.data.frame");
return asDF(variableColumnList(numColumns));
}
// [[Rcpp::export]]
DataFrame variableColumnListAsTibble(int numColumns=30) {
Function asTibble("tbl_df");
return asTibble(variableColumnList(numColumns));
}
So build a C++ List first by pushing columns onto an empty List. (I generate the values and the column names on the fly here.) Then, either return that as an R list, or use one of two helper functions to convert them into a data.frame or tbl_df. One could do the latter from R, but I find this cleaner.