Monthly ArchiveJanuary 2010
C++ 31 Jan 2010 23:46:43
Snippet: Sort Unique Vector
//tinodidriksen.com/uploads/code/cpp/sort-unique-vector.cpp
#include <vector> #include <iostream> #include <algorithm> int main() { std::vector<int> vec1; vec1.push_back(1); vec1.push_back(2); vec1.push_back(3); vec1.push_back(1); vec1.push_back(2); vec1.push_back(3); vec1.push_back(1); std::sort(vec1.begin(), vec1.end()); vec1.erase(std::unique(vec1.begin(), vec1.end()), vec1.end()); std::cout << vec1.size() << std::endl; std::cout << vec1[0] << vec1[1] << vec1[2] << std::endl; }
C++ 31 Jan 2010 23:37:58
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 23:35:20
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 23:31:34
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 23:29:24
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; }