STL Usage - abhijeetk/chromium-development GitHub Wiki

priority_queue

// default
std::priority_queue<int> q;
const auto data = {1,8,5,6,3,4,0,9,7,2};
for(int n : data)
q.push(n);
 
// Using comparator
std::priority_queue<int, std::vector<int>, std::greater<int>>
  q2(data.begin(), data.end());
 
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);`

Sorting

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);

Binary search

// default
std::binary_search(haystack.begin(), haystack.end(), needle)

// Using comparator
Bool myfunction (int i,int j) { return (i>j); }
std::sort (v.begin(), v.end(), myfunction);
std::binary_search (v.begin(), v.end(), 2, myfunction)

How to split a string

std::vector<std::string> split(const std::string& s, char delimiter)
{
   std::vector<std::string> tokens;
   std::string token;
   std::istringstream tokenStream(s);
   while (std::getline(tokenStream, token, delimiter))
   {
      tokens.push_back(token);
   }
   return tokens;
}
⚠️ **GitHub.com Fallback** ⚠️