Category ArchiveCode



C++ 31 Jan 2010 11:35 pm

Snippet: Custom Type to Output Stream

//tinodidriksen.com/uploads/code/cpp/custom-to-ostream.cpp

#include <ostream>
#include <iostream>
#include <string>

struct Custom {
    std::string m_str;
    friend std::ostream& operator<<(std::ostream& stm,
        const Custom& obj);
};

std::ostream& operator<<(std::ostream& stm, const Custom& obj) {
    stm << obj.m_str;
    return stm;
}

int main() {
    Custom cst;
    cst.m_str = "waffles";
    std::cout << cst << std::endl;
}

C++ 31 Jan 2010 11:31 pm

Snippet: Convert String to Hex

//tinodidriksen.com/uploads/code/cpp/string-to-hex.cpp

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

int main() {
    std::string str("abcABC123\xff\x01");
    std::stringstream ss;
    for (size_t i=0 ; i<str.length() ; ++i) {
        ss << std::setw(2) << std::setfill('0')
            << std::hex << (int(str[i])&0xFF);
    }
    std::cout << ss.str();
}

C 31 Jan 2010 11:29 pm

Snippet: Convert Hex to Text

//tinodidriksen.com/uploads/code/c/hex-to-text.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char buf[] = "54657374";
    size_t len = strlen(buf);

    if (len & 1) {
        printf("Cannot take hex from odd length string.\n");
        exit(1);
    }

    char *result = (char*)malloc(len/2 + 1);
    memset(result, 0, len/2 + 1);
    for (size_t i = 0 ; i < len/2 ; ++i) {
        char tmp[3] = {buf[i*2], buf[i*2+1], 0};
        result[i] = (char)strtol(tmp, NULL, 16);
    }

    printf("%s converted to %s\n", buf, result);
    free(result);

    return 0;
}

C++ 31 Jan 2010 11:23 pm

Snippet: Pointer Usage: Polymorphism

//tinodidriksen.com/uploads/code/cpp/pointer-polymorphism.cpp

#include <iostream>

struct A {
    virtual void foo() {
        std::cout << "A::foo()" << std::endl;
    }
    virtual ~A() {
    }
};

struct B : public A {
    void foo() {
        std::cout << "B::foo()" << std::endl;
    }
};

int main() {
    A *a = new A;
    a->foo();
    delete a;

    a = new B;
    a->foo();
    delete a;
}

C++ 04 Oct 2009 03:21 pm

C++ Map Speeds, MSVC++ Edition

(There is also a GNU g++ Edition of these performance tests, and a newer std::set comparison.)

Here is a complete test of MSVC++ map speeds, using same code as my previous map speed test: timemap.cpp with cycle.h.

The compilers are Microsoft Visual C++ 2008 Express as VC9 and Microsoft Visual C++ 2010 Beta as VC10. The containers are std::map, stdext::hash_map, std::tr1::unordered_map, and boost::unordered_map, each with _SECURE_SCL enabled and disabled.

Continue Reading »

« Previous PageNext Page »