Category ArchiveC++



C++ 31 Jan 2010 11:37 pm

Snippet: Vector to Output Stream

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

#include <ostream>
#include <iostream>
#include <vector>

template<typename T>
std::ostream& operator<<(std::ostream& stm, const std::vector<T>& obj) {
    stm << "[";
    if (!obj.empty()) {
        for (size_t i = 0 ; i<obj.size()-1 ; ++i) {
            stm << obj[i] << ",";
        }
        stm << obj.back();
    }
    stm << "]";
    return stm;
}

int main() {
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(2);
    vec.push_back(5);
    vec.push_back(6);
    vec.push_back(1);
    std::cout << vec << std::endl;
}

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: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 »