What is the easiest way to initialize a std::vector with hardcoded elements?

If your compiler supports C++11, you can simply do: std::vector<int> v = {1, 2, 3, 4}; This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect. Alternatively, the Boost.Assign library uses non-macro magic to allow the following: #include <boost/assign/list_of.hpp> … std::vector<int> v = boost::assign::list_of(1)(2)(3)(4); Or: … Read more

Reading a password from std::cin

@wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like: #ifdef WIN32 #include <windows.h> #else #include <termios.h> #include <unistd.h> #endif void SetStdinEcho(bool enable = true) { #ifdef WIN32 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD mode; GetConsoleMode(hStdin, &mode); if( !enable ) mode &= … Read more

push_back vs emplace_back

In addition to what visitor said : The function void emplace_back(Type&& _Val) provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val). But the real C++0x form of emplace_back is really useful: void emplace_back(Args&&…); Instead of taking a value_type it takes a variadic list of arguments, … Read more

Erasing elements from a vector

Use the remove/erase idiom: std::vector<int>& vec = myNumbers; // use shorter name vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements … Read more

What’s the difference between “STL” and “C++ Standard Library”?

The “STL” was written by Alexander Stepanov in the days long before C++ was standardised. C++ existed through the 80s, but what we now call “C++” is the language standardised in ISO/IEC 14882:2014 (and earlier versions, such as ISO/IEC 14882:2011). The STL was already widely used as a library for C++, giving programmers access to … Read more