What would be a “Hello, World!” example for “std::ref”?

You should think of using std::ref when a function: takes a template parameter by value copies/moves a template parameter, such as std::bind or the constructor for std::thread. std::ref creates a copyable value type that behaves like a reference. This example makes demonstrable use of std::ref. #include <iostream> #include <functional> #include <thread> void increment( int &x … Read more

Obtaining list of keys and values from unordered_map

Okay, here you go: std::vector<Key> keys; keys.reserve(map.size()); std::vector<Val> vals; vals.reserve(map.size()); for(auto kv : map) { keys.push_back(kv.first); vals.push_back(kv.second); } Efficiency can probably be improved, but there it is. You’re operating on two containers though, so there’s not really any STL magic that can hide that fact. As Louis said, this will work for any of the … Read more

How can I insert element into beginning of vector?

Use the std::vector::insert function accepting an iterator to the first element as a target position (iterator before which to insert the element): #include <vector> int main() { std::vector<int> v{ 1, 2, 3, 4, 5 }; v.insert(v.begin(), 6); } Alternatively, append the element and perform the rotation to the right: #include <vector> #include <algorithm> int main() … Read more

Append an int to a std::string [duplicate]

The std::string::append() method expects its argument to be a NULL terminated string (char*). There are several approaches for producing a string containg an int: std::ostringstream #include <sstream> std::ostringstream s; s << “select logged from login where id = ” << ClientID; std::string query(s.str()); std::to_string (C++11) std::string query(“select logged from login where id = ” + … Read more

Sorting std::map using value

Even though correct answers have already been posted, I thought I’d add a demo of how you can do this cleanly: template<typename A, typename B> std::pair<B,A> flip_pair(const std::pair<A,B> &p) { return std::pair<B,A>(p.second, p.first); } template<typename A, typename B> std::multimap<B,A> flip_map(const std::map<A,B> &src) { std::multimap<B,A> dst; std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), flip_pair<A,B>); return dst; } int main(void) … Read more

Converting std::__cxx11::string to std::string

Is it possible that you are using GCC 5? If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly … Read more