Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace: Now the algorithm itself can’t change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container: We … 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, so that means that you can now perfectly … Read more

What is the difference between set and hashset in C++ STL?

hash_set is an extension that is not part of the C++ standard. Lookups should be O(1) rather than O(log n) for set, so it will be faster in most circumstances. Another difference will be seen when you iterate through the containers. set will deliver the contents in sorted order, while hash_set will be essentially random (Thanks Lou Franco). Edit: The C++11 … Read more

How to ensure that a std::map is ordered?

You don’t have to do anything. The map will be in ascending order according to the values of the key. Internally, the map performs a comparison between keys to order its elements. By default, it uses std::less<KEY>, which is equivalent to bool operator<(int, int) for integers. For user defined types, you have to options: Implement a bool operator<(const MyType&, … 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, so that means that you can now perfectly … Read more

How to remove all the occurrences of a char in c++ string

Basically, replace replaces a character with another and ” is not a character. What you’re looking for is erase. See this question which answers the same problem. In your case: Or use boost if that’s an option for you, like: All of this is well-documented on reference websites. But if you didn’t know of these functions, you could easily do this kind of things by hand:

Why does the C++ STL not provide any “tree” containers?

There are two reasons you could want to use a tree: You want to mirror the problem using a tree-like structure:For this we have boost graph library Or you want a container that has tree like access characteristics For this we have std::map (and std::multimap) std::set (and std::multiset) Basically the characteristics of these two containers is such that they practically … Read more