Efficient way of reading a file into an std::vector?

The canonical form is this: #include<iterator> // … std::ifstream testFile(“testfile”, std::ios::binary); std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)), std::istreambuf_iterator<char>()); If you are worried about reallocations then reserve space in the vector: #include<iterator> // … std::ifstream testFile(“testfile”, std::ios::binary); std::vector<char> fileContents; fileContents.reserve(fileSize); fileContents.assign(std::istreambuf_iterator<char>(testFile), std::istreambuf_iterator<char>());

How to return a std::string.c_str()

What happens in this code is: const char * returnCharPtr() { std::string someString(“something”); return someString.c_str(); } instance of std::string is created – it is an object with automatic storage duration pointer to the internal memory of this string is returned object someString is destructed and the its internal memory is cleaned up caller of this … Read more

Non-blocking console input C++

Example using C++11: #include <iostream> #include <future> #include <thread> #include <chrono> static std::string getAnswer() { std::string answer; std::cin >> answer; return answer; } int main() { std::chrono::seconds timeout(5); std::cout << “Do you even lift?” << std::endl << std::flush; std::string answer = “maybe”; //default to maybe std::future<std::string> future = std::async(getAnswer); if (future.wait_for(timeout) == std::future_status::ready) answer = … Read more

Include header files using command line option?

I found the -include option. Does this what you want? -include file Process file as if “#include “file”” appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor’s working directory instead of the directory containing the main source file. If not found there, it is … Read more

Is there any reason to use this->

The only place where it really makes a difference is in templates in derived classes: template<typename T> class A { protected: T x; }; template<typename T> class B : A<T> { public: T get() { return this->x; } }; Due to details in the name lookup in C++ compilers, it has to be made explicitly … Read more