C++ sorting and keeping track of indexes

Using C++ 11 lambdas: #include <iostream> #include <vector> #include <numeric> // std::iota #include <algorithm> // std::sort, std::stable_sort using namespace std; template <typename T> vector<size_t> sort_indexes(const vector<T> &v) { // initialize original index locations vector<size_t> idx(v.size()); iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in v // using std::stable_sort instead of std::sort // to … Read more

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr: vec.push_back(std::move(ptr2x)); unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can’t make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it. Note, however, that your current use of unique_ptr is incorrect. You cannot … Read more

Is std::unique_ptr required to know the full definition of T?

Adopted from here. Most templates in the C++ standard library require that they be instantiated with complete types. However shared_ptr and unique_ptr are partial exceptions. Some, but not all of their members can be instantiated with incomplete types. The motivation for this is to support idioms such as pimpl using smart pointers, and without risking … Read more

vector vs. list in STL

vector: Contiguous memory. Pre-allocates space for future elements, so extra space required beyond what’s necessary for the elements themselves. Each element only requires the space for the element type itself (no extra pointers). Can re-allocate memory for the entire vector any time that you add an element. Insertions at the end are constant, amortized time, … Read more

Sorting a vector of custom objects

A simple example using std::sort struct MyStruct { int key; std::string stringValue; MyStruct(int k, const std::string& s) : key(k), stringValue(s) {} }; struct less_than_key { inline bool operator() (const MyStruct& struct1, const MyStruct& struct2) { return (struct1.key < struct2.key); } }; std::vector < MyStruct > vec; vec.push_back(MyStruct(4, “test”)); vec.push_back(MyStruct(3, “a”)); vec.push_back(MyStruct(2, “is”)); vec.push_back(MyStruct(1, “this”)); std::sort(vec.begin(), … Read more

How to sum up elements of a C++ vector?

Actually there are quite a few methods. int sum_of_elems = 0; C++03 Classic for loop: for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it; Using a standard algorithm: #include <numeric> sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0); Important Note: The last argument’s type is used not just for the initial value, but for the type … Read more

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