std::string length() and size() member functions

As per the documentation, these are just synonyms. size() is there to be consistent with other STL containers (like vector, map, etc.) and length() is to be consistent with most peoples’ intuitive notion of character strings. People usually talk about a word, sentence or paragraph’s length, not its size, so length() is there to make … Read more

What’s the most efficient way to erase duplicates and sort a vector?

I agree with R. Pate and Todd Gardner; a std::set might be a good idea here. Even if you’re stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work. Let’s compare three approaches: Just using vector, sort + unique sort( vec.begin(), vec.end() ); vec.erase( … Read more

Sorting a vector in descending order

Actually, the first one is a bad idea. Use either the second one, or this: struct greater { template<class T> bool operator()(T const &a, T const &b) const { return a > b; } }; std::sort(numbers.begin(), numbers.end(), greater()); That way your code won’t silently break when someone decides numbers should hold long or long long … Read more

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 … Read more

Iteration over std::vector: unsigned vs signed index variable

For iterating backwards see this answer. Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use std::size_t as the index variable type. However, that is not portable. Always use the size_type typedef of the container (While you could get away with … 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

Initializing a static std::map in C++

Using C++11: #include <map> using namespace std; map<int, char> m = {{1, ‘a’}, {3, ‘b’}, {5, ‘c’}, {7, ‘d’}}; Using Boost.Assign: #include <map> #include “boost/assign.hpp” using namespace std; using namespace boost::assign; map<int, char> m = map_list_of (1, ‘a’) (3, ‘b’) (5, ‘c’) (7, ‘d’);

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)