I’m trying to avoid reimplementing my own clumsy versions of standard algorithms, and thus am playing with the standard library versions. Since I’m no expert in C++, I proceed with caution and full debug options switched on.
Specifically, I’m using a binary search on a valarray container. The following code block seems to produce correct results, and valgrind does not complain. Still, I do feel I’m on a slippery slope as I’m not sure if what I’m doing is really allowed or am I just being let out by the compiler.
A representative piece of code:
#include <iostream>
#include <valarray>
#include <algorithm>
#include <typeinfo>
using namespace std;
int main(){
valarray<double> v(10);
for (int i=0 ; i<10 ; ++i){
v[i]=2. *i ;
cout<<v[i]<<" ";
}
cout << "\n";
double what=17;
double* it=lower_bound(&v[0], &v[10],what) ;
cout<<it-&v[0]<<" "<<typeid(&v[0]).name()<<" ";
cout<<typeid(it).name()<<" "<<typeid(it-&v[0]).name()<<"\n"; // ???
int idx=it-&v[0];
cout<<"v["<<idx<<"]="<<v[idx]<<"\n";
}
Questions:
- Is what I’m doing here really legal?
- How come the difference between two pointers to double becomes an int? (in the line with the
???comment) What is the overhead for the type conversion? — I am concerned with efficiency as this sort of functionality is going to sit in the part of the code which takes more than 90% of the computation time.
You’re using an
intto index into thevalarray. That’s valid for the example, but not in general. Use anstd::size_tto index into avalarray. (The same goes forstd::vectorand ordinary arrays.)The difference between two pointers to any type is of an unspecified integer type, likely
intorlongand always small enough to fit in anstd::ptrdiff_t.Which conversion?