- Return a substring using
substring(start_position, length)
// (quoting Alfred N. Whitehead)
std::string str="We think in generalities, but we live in details.";
std::string str2 = str.substr(3,5); // "think"- Find a substring using
find(sub_string)
std::size_t pos = str.find("live"); - Inititalize a
setfrom avector
vector<string> words{"one", "two"};
set<string> words_set(words.begin(), words.end());- Using
unordered_map
unordered_map<string, string> umap = {
{"RED", "#FF0000"},
{"GREEN", "#00FF00"}
};
// Output the key and value of map
for (auto color: umap) {
cout<<color.first<<" "<<color.second<<endl;
}- Using
iterator
map<int, string> my_map;
my_map[1] = "first";
my_map[2] = "second";
for (map<int, string>::iterator it=my_map.begin(); it!= my_map.end(); it++) {
cout<<(*it).first<<" "<<(*it).second<<endl;
}- Initialize a standard
priority queue
vector<int> input{1, 8, 5, 4, 6, 7};
// Create a max heap
priority_queue<int> maxQueue(input.begin(), input.end());
print_queue(maxQueue);
// Create a min heap
priority_queue<int, vector<int>, greater<int>> minQueue(input.begin(), input.end());
print_queue(minQueue);- Create customer sort function
struct CustomComparator{
bool operator()(int a, int b) {
return a>b;
}
};
int main() {
vector<int> input{1, 8, 5, 4, 6, 7};
// Create a custom sort heap
priority_queue<int, vector<int>, CustomComparator> customQueue(input.begin(), input.end());
print_queue(customQueue);
}- Print a
priority queue
template<typename T>
void print_queue(T &q) {
while (!q.empty()) {
cout << q.top() << " ";
q.pop();
}
cout<<endl;
}- Sort a
vector
vector<int> nums{1,3,4,5,6};
// Sort ascending
sort(nums.begin(), nums.end());
for (int i=0; i<nums.size(); i++) {
cout<<nums[i]<<" ";
}
cout<<endl;
// Sort decending
sort(nums.begin(), nums.end(), greater<int>());
for (int i=0; i<nums.size(); i++) {
cout<<nums[i]<<" ";
}- Custom
sort