Wednesday, December 16, 2015

Remove a single character from std::string

This  might probably be one of the oldest tricks for 2015 for std::string but still blogging about it anyways.

To remove all instances of a single character from a std::string, you can use std::remove and string::erase.

#include // include for remove()

std::string str = "This is a test";
str.erase( std::remove( str.begin(), str.end(), 'e' ), str.end() );

This would remove the character e from string, and will provide result of "This is a tst"

If you want to remove quotes from the string,

std::string str = "This \" is a test \"";
str.erase( std::remove( str.begin(), str.end(), '\"' ), str.end() );

result str will have "This is a test" without the quotes. 

Thursday, December 10, 2015

C++ and aggregate initialization

There is an easier way to initialize a char array with all 0s instead of using the traditional memset

So this code

char array1[1024];
memset(array1, 0, sizeof(array1));

can be replaced with

char array[1024] = {0};
char array[1024] = {}; //same as {0}

Which is basically the same but on a single line implementation.

Section 8.5.1 of the ISO Spec states

"An aggregate is an array or a class with  no user declared constructors, no private or protected non static data members, no base classes, and no virtual functions"

If you want to initialize such an aggregate you can use {}.

This is not only  used to set everything to 0, but to also initialize class members.

For e.g.

struct ExampleStruct
{
   int x;
   int y;
   int z;
};

If you have a simple struct like this with no constructors, all public members, then you can initialize its members in a single line like this

ExampleStruct Object = { 2, 3, 6 };

Which would set x = 2, y = 3 and z = 6.

Also as per C++11, = {0} is required to set the padding bytes to 0 by the standards. For e.g

struct ExampleStruct
{
   char x;
   int y;
}

ExampleStruct Object = {0}
will set x = 0 and y = 0 , and the padded bytes between x and y will be 0.