In this post, I am going to write some common code fragments in C++ for future's quick complete some simple functions.

Container Usage

std::string

#include <cassert>
#include <iterator>
#include <string>
 
int main()
{
    std::string s("Exemplar");
    assert(8 == s.length());
    assert(8 == s.size());
    assert(s.size() == s.length());
    assert(s.size() == static_cast<std::string::size_type>(
        std::distance(s.begin(), s.end())));
}
  • empty return true if this string is empty, false otherwise
#include <cassert>
#include <string>

int main()
{
    // an empty string
    std::string s("");
    assert(s.empty());
}
  • stoi/stol/stoll parse string to int/long/long long , throw exception "std::invalid_argument" if input string is not start with digit
  • stof/stod/stold parse string to float/double/long doble
  • to_string from int, double ... to std::string

std::vector

  • init
std::vector<int> v {1,2,3};
  • size return size of string. don't get it in loop if the size of your vector doesn't change

std::map

const std::map<std::string, int> m {
    {"this", 100},
    {"can", 100},
    {"be", 100},
    {"const", 100},
};
  • iterate all elements
template<typename Map>
void print_map(Map& m)
{
   std::cout << '{';
   for(auto& p: m)
        std::cout << p.first << ':' << p.second << ' ';
   std::cout << "}\n";
}

std::set

std::stack

std::multimap

std::priority_queue

Common Process

lambda function

Binary Index Tree

Segment Tree

Reference:

来自的你,很高兴你能看到这儿。若本文对你有所用处,或者内容有什么不足之处,敬请毫不犹豫给个回复。谢谢!