[Dune] another little c++ question that bugs me

Markus Blatt markus at dr-blatt.de
Wed Aug 13 11:17:14 CEST 2014


Hi,

On Wed, Aug 13, 2014 at 11:02:48AM +0200, Aleksejs Fomins wrote:
> I have a little c++ question that bugs me.
>

You really should grep yourself a C++ book and study that.
 
> [...]
>
> rez += norm2sq<dim>(xVec1[i], xVec2[i]);
> norm2sq<dim>(xVec1[i], xVec2[i]);
> 
> by simply calling the function norm2sq twice for no reason, the function
> norm2sqVector returns the correct result.
> 
> I have no idea why is this happening, but it must be sth trivial that I
> can't see.
> 
> Could someone please take a look?
> 
> Thanks,
> Aleksejs
> 
> 
> 
> --------------------------------------------------------------
> 
> 
> 
> // Finds the 2-norm distance between two coordinates
> template<int dim>
> double norm2sq(
>   FieldVector< double, dim > x1,
>   FieldVector< double, dim > x2

I would use constant references for the function arguments, here. Like
this the vectors are copied.
> ) {
> 	double rez;
> 	for (int i = 0; i < x1.size(); i++)
> 	{
> 		rez += pow(x1[i] - x2[i],2);
> 	}
> 	return rez;
> }


pods (Plain old datatypes like int, float, double, std::array, etc.)
are never default initialized. That means that

double rez;

leaves rez undefined. It basically contains what was written to the
memory that rez owns before. That might be any value.


Are you aware that what you are trying to do is already present in
dune-istl, if you use a BlockVector instead of std::vector?

typedef Dune::BlockVector<Dune::FieldVector<double, dim> > V;
V tmp=xVec1;
tmp-=xVec2;
double rez=tmp.two_norm();

-- 
Do you need more support with DUNE or HPC in general? 

Dr. Markus Blatt - HPC-Simulation-Software & Services http://www.dr-blatt.de
Hans-Bunte-Str. 8-10, 69123 Heidelberg, Germany
Tel.: +49 (0) 160 97590858
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: Digital signature
URL: <https://lists.dune-project.org/pipermail/dune/attachments/20140813/42914fa0/attachment.sig>


More information about the Dune mailing list