~/grimoire/cpp-one-liners
../

cpp one-liners

237 words

C++ One-Liners

std::count()

// count() - find number of occurrences of an element in the given range of any STL container or an array
std::vector<int> v{1, 2, 3, 4, 5};
cout << count(v.begin(), v.end(), 2);

string s = "10101010101111";
cout << count(s.begin(), s.end(), 1);

std::multiset<int> m= {1, 1, 2, 3, 2, 2, 2, 1};
cout << count(m.begin(), m.end(), 2);
 

string_view()

{
// string_view() - a lightweight, non-owning view into a sequence of characters
// essentially a const char* pointer to the first character and a size_t for the length

std::string owner = "Hello, world!";
std::string_view view = owner;
}

// Example:
int prefixConnected(vector<string>& words, int k) {
        unordered_map<string_view, int> count;

        for (const string& word : words) {
            if (word.size() >= k) {
                // instead of using substr, use string_view that does not allocate memory 
                count[string_view(word.data(), k)]++;
            }
        }

        int groups = 0;
        for(const auto&[_, freq] : count) {
            if(freq >= 2) {
                groups++;
            }
        }

        return groups;
}

Lambda Functions

// Sort with lambda
std::sort(v.begin(), v.end(), [](int a, int b) {
    return a > b;
});

Smart Pointers

// Unique pointer
auto ptr = std::make_unique<int>(42);

// Shared pointer
auto shared = std::make_shared<int>(42);

vector::insert()

// insert function can have a few forms:
v.insert(v.end(), value);             // single value
v.insert(v.end(), count, value);      // count copies of value
v.insert(v.end(), other.begin(), other.end()); // insert another vector