Showing posts with label cpp. Show all posts
Showing posts with label cpp. Show all posts

Friday, March 01, 2013

Nifty Trick of the Day: cpp loop over enum

So I was trying to figure out a quick hack to loop over an enum so that I could write a simple unit test to achieve complete coverage. So google returned the following link with this solution:

http://stackoverflow.com/questions/2479746/loop-on-enumeration-values

My slightly modified solution

for(SAID_ENUM i = value1; i < static_cast<SAID_ENUM>(LAST_ENTRY+1); i = static_cast<SAID_ENUM>(i+1)){}

of course this assumes you have an extra last "end" member  to your enum
 
 

Tuesday, October 30, 2012

C++: Tuple my new friend

So I've always been a fan of C/C++. At my previous position I was almost strictly using C only for my part of the project (we also used quite a bit of Java). Towards the end I got really involved with Python (which I wish I was using more of now), but by current job is 99% C++.
One of the things I liked about Python was the ability to return more than 1 value/object from a function. And late last week I ran into a situation where that is exactly what I wanted in CPP. Boost tuple provided just that.


#include <boost/tuple/tuple.hpp> 
using boost::make_tuple;
boost::tuples::tuple<float, float, int, float> getStuff()
{
     return make_tuple<0.1,0.2,3,0.4>;


main()

     boost::tuples::tuple<float, float, int, float> tup = getStuff(); 
     if(tup<0>.get() == 0.1) /* cheer */ ;
     if(tup<1>.get() == 0.2) /* cheer */ ;
     if(tup<2>.get() == 3) /* cheer */ ;
     if(tup<3>.get() == 0.4) /* cheer */ ;


While not as pretty as Python, but it works.
Nick

Thursday, March 15, 2012

boost::assign my new friend

On my current project we do a lot of unit testing sometimes with ‘random’ data. No biggie right… well when you consider the fact that a lot of the attributes being tested are very large arrays and vectors…. coming up with random values can be time consuming and tedious… but luckily I found:
      boost::assign

Being able to set a vector quickly with the ‘+=’ operator is amazing, plus toss in the ‘repeat’ and ‘repeat_fun’ command and I’m golden.
#include <boost/assign/std/vector.hpp>
#include <cstdlib> // for ‘rand()’
// bring ‘operator+=()’ into scope
using namespace boost::assign;
const int LARGE_ARRAY_SIZE = 4200;

std::vector<double> largeV;
largeV += 0.1, repeat_fun(LARGE_ARRAY_SIZE - 1, &rand);
simple as that… not I’ve got a vector containing 4200 items. plus using boost::multi_array and some reshaping and I can massage that into a 2x2100 matrix or any size.