0

I am doing some sample programs in C++. I have 100,000 single column data in a Text File. I loaded that all data into a std::vector. Now I need to check the first character of every data whether it is '#' or '%' or '$'. The data are in Sorted manner in the way of '#','$','%'. I can do programming for this like Below.

for ( i = 0; i < myArray.size(); i++)
{
  if(mrarray[i][0]=='#')
  {
    // do some process for '#' values
  }
 else if(mrarray[i][0]=='$')
  {
    // do some process for '$' values
  }
 else if(mrarray[i][0]=='%')
  {
    // do some process for '%' values
  }

}

My Question is " Is it a best way to do this ? . Is there any other way to do this program with better efficiency ? " ???

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75
  • maybe a `switch` statement? – Sourav Ghosh Nov 19 '14 at 07:33
  • If you're using std::vector then this can't be C code. – Paul R Nov 19 '14 at 07:35
  • at() member function can also be an alternative to get character and yes switch statement would be better instead of if/else pair. – Ali Kazmi Nov 19 '14 at 07:43
  • Can't you do it beforehand, load data into 3 seperate arrays based on first character? find first occurance line. no for each char i.e. #,$,% and then from that line to next char put all rows in an array. do it for 3 chars. Finally you can perform same action on a complete array which of single start char. – Nachiket Kate Nov 19 '14 at 08:02

2 Answers2

1

That's about as efficient as it gets, the only thing that will make it a bit faster is using a switch statement.

for ( i = 0; i < myArray.size(); i++)
{
  switch(myArray[i][0]){
    case '#':
      // Do stuff
      break;
    case '$':
      // Do stuff
      break;
    case '%':
      // Do stuff
      break;
  }
}

I'm also assuming you're only doing this once. If you're doing it more than once with the same data, then it can be made more efficient by sorting it. If that's the case, let me know and I will update my answer.

David
  • 4,744
  • 5
  • 33
  • 64
1

As state in why-is-processing-a-sorted-array-faster-than-an-unsorted-array, It may be more efficient to sort your lines first (based on first character) and then process your vector.

The switch statement proposed by David would be my choice.

But as alternative, you may try an array of function pointer, something like:

using my_function_pointer = void (*)(const std::string&/*, other required stuff*/);
const my_function_pointer funs[256] = { dummy_f, dummy_f, .., f_charp, f_dollar, f_mod, dummy_f, ..};

for ( i = 0; i < myArray.size(); i++) {
    funs[myArray[i][0]](myArray[i] /*, other required stuff*/);
}

And anyway, you need to benchmark your change as for any optimization.

Community
  • 1
  • 1
Jarod42
  • 203,559
  • 14
  • 181
  • 302