Recently in Programming Category

Replace me!

| | Comments (2)
A friend of mine asked me how to replace a string with some other string in stl. How hard can it be? I immediately got a bad feeling in the stomack, remembering struggeling with this problem myself before. It's hard to try to persuade people to use stl when such simple matters don't have a clean solution with stl. I finally found something similar to this in a usenet post. It's about as clean as I can come up with. Any ideas? [cpp] #include "string" #include "algorithm" #include "iostream" /*****************************************************************************/ static void Replace( std::string& source, const std::string& find, const std::string& replacement) { size_t len = find.length(); std::string::size_type pos = 0; while( (pos = source.find( find, pos )) != std::string::npos ) { source.replace( pos, len, replacement ); } } int main() { std::string Source = "I once_had a dog named Harry and a dog named Noodles"; std::string FindStr = "dog"; std::string ReplaceStr = "cat"; std::cout < < Source < < std::endl; Replace( Source, FindStr, ReplaceStr); std::cout < < Source < < std::endl; return 0; } [/cpp]

Class or Struct?

| | Comments (0)
I stumbled over an interview with Bjarne Stroustrup and he said something clever: "My rule of thumb is that you should have a real class with an interface and a hidden representation if and only if you can consider an invariant for the class." Bjarne Stroustrup I find this a very good rule of thumb.

STL: Bad Behaviour

| | Comments (0)
We've been arguing at work about whether it's ok to use the & operator while indexing an STL vector. I'm currently working with a compiler that is throwing errors at me for doing it, so I finally has backup for my arguments *sigh*. It's quite easy to learn the 'right' way: Never do: [cpp] // Bad m_vecSound.erase( &m_vecSound[i] ); [/cpp] Do: [cpp] // Good m_vecSound.erase( m_vecSound.begin() + i ); [/cpp] May be obvious to some but apparently not to all. :o
I think it's handy to use my favourite IDE Visual Studio .Net 2003 even when I do gcc development. It's quite easy to do a makefile project, and add the relevant paths to the IDE so it can find the necessary binaries for compiling and such. But I found it rather annoying that I don't have clickable errors and warnings since I'm quite used to that (cough lazy cough). How nice there is an easy hack you can do though. Look! Open up cc1.exe (and cc1plus.exe if you use c++) in your favourite hex editor. Then search for the string "%s:%d: " (don't forget the space) and replace with "%s(%d):". Then save the files and you're done.

About this Archive

This page is a archive of recent entries in the Programming category.

PlayStation 3 is the previous category.

Web design is the next category.

Find recent content on the main index or look in the archives to find all content.