Some STL one-liners

Copy elements from one container to another.

std::copy( source.begin(), source.end(), std::back_inserter( container ) );

copying containers to the output: And copying the input stream into a container

std::vector<int>   data;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),std::back_inserter(data));

vector erase and remove

vector<int> v;
v.erase(remove(v.begin(), v.end(), 42), v.end());


// will call a->func(v[i])
for_each(v.begin(), v.end(), bind1st(mem_fun(&A::func), &a));
// will call w[i]->func(72)
for_each(w.begin(), w.end(), bind2nd(mem_fun(&A::func), 72));

One for looping over each line in a file. From a Andrew Koenig column in Dr. Dobbs.

for (string s; getline(stream,s); ) {
  // Process line

Fill an array with random numbers

std::generate(V.begin(), V.end(), rand);

Reading entire file in one go.

std::istreambuf_iterator < char > begin(std::cin), end;
std::string str(begin, end);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s