diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..bf55233 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 2.6) +project(cpp_study) +set(CMAKE_CXX_STANDARD 14) + +include_directories("${PROJECT_BINARY_DIR}") + +include_directories("${PROJECT_SOURCE_DIR}/section0") +include_directories("${PROJECT_SOURCE_DIR}/section1") +include_directories("${PROJECT_SOURCE_DIR}/section2") +include_directories("${PROJECT_SOURCE_DIR}/section3") +include_directories("${PROJECT_SOURCE_DIR}/section4") +include_directories("${PROJECT_SOURCE_DIR}/section5") +add_subdirectory(section0) +add_subdirectory(section1) +add_subdirectory(section2) +add_subdirectory(section3) +add_subdirectory(section4) +add_subdirectory(section5) +set(EXTRA_LIBS ${EXTRA_LIBS} section0) +set(EXTRA_LIBS ${EXTRA_LIBS} section1) +set(EXTRA_LIBS ${EXTRA_LIBS} section2) +set(EXTRA_LIBS ${EXTRA_LIBS} section3) +set(EXTRA_LIBS ${EXTRA_LIBS} section4) +set(EXTRA_LIBS ${EXTRA_LIBS} section5) diff --git a/README-CN.md b/README-CN.md new file mode 100644 index 0000000..9d11473 --- /dev/null +++ b/README-CN.md @@ -0,0 +1,77 @@ +# cpp_study + +[《C++实战笔记》](https://time.geekbang.org/column/intro/309) + +> 跟着我学习现代 `C++ `. + +欢迎 pull request make/cmake 文件! + +## 必要条件 + +- `Linux` : Ubuntu, Debian, CentOS, and others +- `macOS(OS X)` : 可能有效,但未经测试 + + +## 参考书目 + +* [ISO C++](http://www.open-std.org/jtc1/sc22/wg21/) +* [cppreference](https://en.cppreference.com/w/) + + +## 资源 + +* [VirtualBox](https://www.virtualbox.org) +* [Ubuntu](https://ubuntu.com/) +* [GCC](http://gcc.gnu.org/) +* [Clang](http://clang.llvm.org/) + + +## 文档 + +* [Bjarne Stroustrup's FAQ](http://www.stroustrup.com/bs_faq.html) +* [Bjarne Stroustrup's C++11 FAQ](http://www.stroustrup.com/C++11FAQ.html) +* [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines) +* [OpenResty Code Style Guide(zh-cn)](http://openresty.org/cn/c-coding-style-guide.html) +* [Google Code Style Guide](https://google.github.io/styleguide/cppguide.html) + + +## 研发参考链接 + +* [Boost](https://www.boost.org/) +* [tbb](https://github.com/intel/tbb) +* [JSON](https://www.json.org/json-zh.html) +* [JSON for Modern C++](https://github.com/nlohmann/json) +* [MessagePack](https://msgpack.org/) +* [msgpack-c](https://github.com/msgpack/msgpack-c) +* [ProtoBuf](https://github.com/protocolbuffers/protobuf) +* [protobuf-c](https://github.com/protobuf-c/protobuf-c) +* [gRPC](https://grpc.io) +* [Thrift](https://thrift.apache.org/) +* [libcurl](https://curl.haxx.se/libcurl/) +* [cpr](https://github.com/whoshuu/cpr) +* [ZMQ](https://zeromq.org/) +* [pybind11](https://github.com/pybind/pybind11) +* [lua](https://www.lua.org/) +* [luajit](http://luajit.org/) +* [luajit-openresty](https://github.com/openresty/luajit2) +* [LuaBridge](https://github.com/vinniefalco/LuaBridge) +* [gperftools](https://github.com/gperftools/gperftools) +* [FlameGraph](https://github.com/brendangregg/FlameGraph) +* [OpenResty XRay](https://openresty.com.cn/cn/xray/) + +## 很棒的合集 + +* [Awesome C++](https://github.com/fffaraz/awesome-cpp) +* [Awesome Mordern C++](https://github.com/rigtorp/awesome-modern-cpp) + +## 另见 + +* [透视HTTP协议](https://time.geekbang.org/column/intro/189) +* [http_study](https://github.com/chronolaw/http_study) - http service for pratice and more +* [boost guide](https://github.com/chronolaw/boost_guide.git) - Sample code for Boost library Guide +* [professional_boost](https://github.com/chronolaw/professional_boost.git) - Professional boost development +* [annotated_nginx](https://github.com/chronolaw/annotated_nginx) - 注释nginx,学习研究源码 +* [ngx_cpp_dev](https://github.com/chronolaw/ngx_cpp_dev) - Nginx C++ development kit, with the power of C++11 and Boost Library +* [ngx_ansic_dev](https://github.com/chronolaw/ngx_ansic_dev) - Nginx ANSI C Development +* [openresty_dev](https://github.com/chronolaw/openresty_dev) - OpenResty/Lua Programming +* [favorite-nginx](https://github.com/chronolaw/favorite-nginx) - Selected favorite nginx modules and resources diff --git a/README.md b/README.md index 7d4391e..6b1547c 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,20 @@ Pull requests of make/cmake are welcome! * Linux : Ubuntu, Debian, CentOS, and others * macOS(OS X) : may work but not be tested +## Docker + +You can also use this in docker, it bases on gcc 7.5.0: + +```docker +docker pull chronolaw/cpp_study +docker run -it --rm chronolaw/cpp_study +``` ## Reference * [ISO C++](http://www.open-std.org/jtc1/sc22/wg21/) -* [cppreference](https://en.cppreference.com/w/) +* [cppreference(en)](https://en.cppreference.com/w/) +* [cppreference(zh)](https://zh.cppreference.com/w/) ## Resource @@ -28,13 +37,16 @@ Pull requests of make/cmake are welcome! * [Bjarne Stroustrup's FAQ](http://www.stroustrup.com/bs_faq.html) * [Bjarne Stroustrup's C++11 FAQ](http://www.stroustrup.com/C++11FAQ.html) +* [Bjarne Stroustrup's C++ HOPL4 (zh-cn)](https://github.com/Cpp-Club/Cxx_HOPL4_zh) * [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines) * [OpenResty Code Style Guide(zh-cn)](http://openresty.org/cn/c-coding-style-guide.html) * [Google Code Style Guide](https://google.github.io/styleguide/cppguide.html) +* [ProtoBuffer C++ Doc](https://developers.google.com/protocol-buffers/docs/reference/cpp-generated) ## Dev Links +* [PCRE](http://www.pcre.org/) * [Boost](https://www.boost.org/) * [tbb](https://github.com/intel/tbb) * [JSON](https://www.json.org/json-zh.html) @@ -48,6 +60,7 @@ Pull requests of make/cmake are welcome! * [libcurl](https://curl.haxx.se/libcurl/) * [cpr](https://github.com/whoshuu/cpr) * [ZMQ](https://zeromq.org/) +* [cppzmq](https://github.com/zeromq/cppzmq) * [pybind11](https://github.com/pybind/pybind11) * [lua](https://www.lua.org/) * [luajit](http://luajit.org/) diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..e141919 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,79 @@ +# Dockerfile +# chrono@2020-09 + +# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun +# sudo service docker start +# sudo usermod -aG docker ${USER} + +# docker build -t chronolaw/cpp_study . + +# docker run -it chronolaw/cpp_study +# docker run -it --rm chronolaw/cpp_study + +# check for http server in http_study +# docker inspect bridge +# curl 172.17.0.3/11-1 -v + +# docker login +# docker push chronolaw/cpp_study +# docker pull chronolaw/cpp_study + +ARG SRC_IMAGE="gcc:7" + +FROM ${SRC_IMAGE} + +#LABEL version="2020-09" + +# gcc-multilib g++-multilib +# linux-tools-common +# linux-tools-4.4.0-31-generic linux-cloud-tools-4.4.0-31-generic linux-tools-generic linux-cloud-tools-generic + +ARG JSON_VERSION="3.9.1" +ARG CPR_VERSION="1.4.0" +ARG LUAJIT_VERSION="2.1-20200102" +ARG LUABRIDAGE_VERSION="2.6" +ARG GPERF_VERSION="2.8" + +RUN DEBIAN_FRONTEND=noninteractive apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y \ + vim cmake gdb pstack strace \ + libmsgpack-dev protobuf-compiler libprotobuf-dev libprotoc-dev \ + libcurl4-openssl-dev libzmq3-dev \ + python3-dev python3-pip \ + google-perftools libgoogle-perftools-dev \ + && pip3 install pybind11 \ + && cd \ + && git clone https://github.com/chronolaw/cpp_study --depth=1 \ + && cp ~/cpp_study/env/vimrc ~/.vimrc \ + && cp ~/cpp_study/env/bashrc ~/.bashrc \ + && cp ~/cpp_study/env/gitconfig ~/.gitconfig \ + && mkdir github \ + && cd github \ + && curl -fsL https://github.com/nlohmann/json/releases/download/v${JSON_VERSION}/json.hpp -o json.hpp \ + && ln -s ~/github/json.hpp ~/cpp_study/common/ \ + && curl -fsL https://github.com/whoshuu/cpr/archive/${CPR_VERSION}.tar.gz -o cpr.tgz \ + && tar xfz cpr.tgz \ + && cd cpr-${CPR_VERSION} \ + && cmake . -DUSE_SYSTEM_CURL=ON -DBUILD_CPR_TESTS=OFF \ + && make && make install && make clean \ + && cd .. \ + && curl -fsL https://github.com/openresty/luajit2/archive/v${LUAJIT_VERSION}.tar.gz -o luajit.tgz \ + && tar xfz luajit.tgz \ + && cd luajit2-${LUAJIT_VERSION} \ + && make && make install && make clean \ + && ln -s /usr/local/lib/libluajit-5.1.so.2 /lib/x86_64-linux-gnu/ \ + && cd .. \ + && curl -fsL https://github.com/vinniefalco/LuaBridge/archive/${LUABRIDAGE_VERSION}.tar.gz -o LuaBridge.tgz \ + && tar xfz LuaBridge.tgz \ + && ln -s ~/github/LuaBridge-${LUABRIDAGE_VERSION}/Source/LuaBridge/ ~/cpp_study/common/ \ + && curl -fsL https://github.com/gperftools/gperftools/releases/download/gperftools-${GPERF_VERSION}/gperftools-${GPERF_VERSION}.tar.gz -o gperf.tgz \ + && tar xfz gperf.tgz \ + && ln -s ~/github/gperftools-${GPERF_VERSION}/pprof-symbolize /bin/pprof \ + && git clone https://github.com/brendangregg/FlameGraph.git --depth=1 \ + && ln -s ~/github/FlameGraph/flamegraph.pl ~/cpp_study/section4/ \ + && rm *.tgz \ + && DEBIAN_FRONTEND=noninteractive apt-get autoremove -y + + +#CMD ["/bin/bash"] +CMD ["/bin/bash", "-c", "cd ~/cpp_study;/bin/bash"] diff --git a/docker/Dockerfile.new b/docker/Dockerfile.new new file mode 100644 index 0000000..85b1bf1 --- /dev/null +++ b/docker/Dockerfile.new @@ -0,0 +1,22 @@ +# Dockerfile +# chrono@2021-03 + +# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun +# sudo service docker start +# sudo usermod -aG docker ${USER} + +# docker build -t chronolaw/cpp_study . + +# docker run -it --rm chronolaw/cpp_study + +ARG SRC_IMAGE="gcc:7" + +FROM ${SRC_IMAGE} + +WORKDIR /root + +COPY setup.sh ./ + +RUN ./setup.sh && rm ./setup.sh + +CMD ["/bin/bash"] diff --git a/docker/cpp-study-pod.yml b/docker/cpp-study-pod.yml new file mode 100644 index 0000000..0d627b8 --- /dev/null +++ b/docker/cpp-study-pod.yml @@ -0,0 +1,32 @@ +# kubernetes pod yaml for cpp study +# you could run it in k8s/minikube/kind/... +# chrono @ 2021-03 + +# kubectl apply -f cpp-study-pod.yml +# kubectl delete -f cpp-study-pod.yml +# +# kubectl get pods +# kubectl exec -it k8s-cpp-study -- bash +# kubectl attach -it k8s-cpp-study + +apiVersion: v1 +kind: Pod + +metadata: + name: k8s-cpp-study + labels: + author: chrono + env: study + +spec: + + containers: + + - name: cpp-study + image: chronolaw/cpp_study + workingDir: /root/cpp_study + + # exec or attach into this container + stdin: true + tty: true + diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..4466347 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,24 @@ +# chrono 2021-03 +# +# docker-compose run --rm cpp_study +# +# docker ps +# docker exec -it xxx bash + +version: "3" + +services: + + cpp_study: + + image: chronolaw/cpp_study + + container_name: cpp_study + + working_dir: /root/cpp_study + + stdin_open: true + tty: true + + command: /bin/bash + diff --git a/docker/setup.sh b/docker/setup.sh new file mode 100755 index 0000000..35121d6 --- /dev/null +++ b/docker/setup.sh @@ -0,0 +1,82 @@ +#!/bin/sh + +# chrono @ 2021-03 + +# apt-get +DEBIAN_FRONTEND=noninteractive apt-get install -y \ + vim cmake gdb pstack strace \ + libmsgpack-dev protobuf-compiler libprotobuf-dev libprotoc-dev \ + libcurl4-openssl-dev libzmq3-dev \ + python3-dev python3-pip \ + google-perftools libgoogle-perftools-dev + +DEBIAN_FRONTEND=noninteractive apt-get autoremove -y + +# python3 pybind11 +pip3 install pybind11 + +#WORKDIR='/root/' +#HOME='/root' + +# git source code +git clone https://github.com/chronolaw/cpp_study --depth=1 + +# setup env +cp ${HOME}/cpp_study/env/vimrc ${HOME}/.vimrc \ +cp ${HOME}/cpp_study/env/bashrc ${HOME}/.bashrc \ +cp ${HOME}/cpp_study/env/gitconfig ${HOME}/.gitconfig \ + +# source + +JSON_VERSION="3.9.1" +CPR_VERSION="1.4.0" +LUAJIT_VERSION="2.1-20200102" +LUABRIDAGE_VERSION="2.6" +GPERF_VERSION="2.8" + +#echo ${JSON_VERSION} +#echo ${HOME} + +mkdir ${HOME}/github +cd ${HOME}/github + +# test +#exit + +# json +curl -fsL https://github.com/nlohmann/json/releases/download/v${JSON_VERSION}/json.hpp -o json.hpp +ln -s ~/github/json.hpp ~/cpp_study/common/ + +# curl/cpr +curl -fsL https://github.com/whoshuu/cpr/archive/${CPR_VERSION}.tar.gz -o cpr.tgz +tar xfz cpr.tgz +cd cpr-${CPR_VERSION} +cmake . -DUSE_SYSTEM_CURL=ON -DBUILD_CPR_TESTS=OFF +make && make install && make clean +cd .. + +# luajit +curl -fsL https://github.com/openresty/luajit2/archive/v${LUAJIT_VERSION}.tar.gz -o luajit.tgz +tar xfz luajit.tgz +cd luajit2-${LUAJIT_VERSION} +make && make install && make clean +ln -s /usr/local/lib/libluajit-5.1.so.2 /lib/x86_64-linux-gnu/ +cd .. + +# luabridge +curl -fsL https://github.com/vinniefalco/LuaBridge/archive/${LUABRIDAGE_VERSION}.tar.gz -o LuaBridge.tgz +tar xfz LuaBridge.tgz +ln -s ~/github/LuaBridge-${LUABRIDAGE_VERSION}/Source/LuaBridge/ ~/cpp_study/common/ + +# gperftools +curl -fsL https://github.com/gperftools/gperftools/releases/download/gperftools-${GPERF_VERSION}/gperftools-${GPERF_VERSION}.tar.gz -o gperf.tgz +tar xfz gperf.tgz +ln -s ~/github/gperftools-${GPERF_VERSION}/pprof-symbolize /bin/pprof + +# flame graph +git clone https://github.com/brendangregg/FlameGraph.git --depth=1 +ln -s ~/github/FlameGraph/flamegraph.pl ~/cpp_study/section4/ + +# clean +rm *.tgz + diff --git a/env/bashrc b/env/bashrc index f542d7e..14383f0 100644 --- a/env/bashrc +++ b/env/bashrc @@ -1,7 +1,9 @@ # Copyright (c) 2020 by Chrono set -o vi +alias ll='ls -l' alias l='ls -lh' +alias vi='vim' function set-title() { if [[ -z "$ORIG" ]]; then diff --git a/env/vimrc b/env/vimrc index 4f8ede6..ee6fcbb 100644 --- a/env/vimrc +++ b/env/vimrc @@ -1,5 +1,6 @@ set nu sy on +set mouse= set ruler set smartindent shiftwidth=4 set tabstop=4 diff --git a/extra/etcd.hpp b/extra/etcd.hpp new file mode 100644 index 0000000..3ded3ed --- /dev/null +++ b/extra/etcd.hpp @@ -0,0 +1,175 @@ +// Copyright (c) 2020 by Chrono +// +// docker pull quay.io/coreos/etcd +// docker pull quay.io/coreos/etcd:v3.3.25 +// +// https://etcd.io/docs/v2/api/ +// +// docker-compose -f etcd.yml -p etcd up -d +// docker-compose -f etcd.yml -p etcd down +// +// curl 127.0.0.1:2379/version +// {"etcdserver":"3.3.8","etcdcluster":"3.3.0"} +// {"etcdserver":"3.3.25","etcdcluster":"3.3.0"} +// +// curl http://127.0.0.1:2379/v2/keys/foo -XPUT -d value="Hello xxx" +// curl http://127.0.0.1:2379/v2/keys/foo + +#ifndef _UTILITY_ETCD_HPP_ +#define _UTILITY_ETCD_HPP_ + +#include +#include +#include + +namespace etcd::v2 { + +// sample output +// Version: +// { +// "etcdcluster": "3.3.0", +// "etcdserver": "3.3.8", +// "statusCode": 200 +// } +// Get: +// { +// "action": "get", +// "node": { +// "createdIndex": 29, +// "key": "/test/xxx", +// "modifiedIndex": 29, +// "value": "etcd" +// }, +// "statusCode": 200 +// } +class Client final { +public: + using string_type = std::string; + using string_ref_type = const std::string&; + + using json_type = nlohmann::json; +public: + Client(string_ref_type addr, int port) noexcept { + + m_url = fmt::format("http://{}:{}", addr, port); + //m_url = "http://" + addr + std::to_string(port); + + m_prefix = m_url + "/v2/keys"; + } + + ~Client() noexcept = default; +public: + json_type Version() noexcept { + + auto res = cpr::Get( + m_url + "/version" + ); + + return wrap_reply(res); + } + + // statusCode=2xx => OK + json_type Set(string_ref_type key, + string_ref_type value) noexcept { + + auto res = cpr::Put( + m_prefix + key, + cpr::Body("value=" + value) + ); + + return wrap_reply(res); + } + + // statusCode=200 => OK + json_type Get(string_ref_type key) noexcept { + + auto res = cpr::Get( + m_prefix + key + ); + + return wrap_reply(res); + } + + // statusCode=200 => OK + json_type Delete(string_ref_type key) noexcept { + + auto res = cpr::Delete( + m_prefix + key + ); + + return wrap_reply(res); + } + +public: + // statusCode=2xx => OK + json_type Set(string_ref_type key, + string_ref_type value, int ttl) noexcept { + + auto res = cpr::Put( + m_prefix + key, + cpr::Body(fmt::format("value={};ttl={}", value, ttl)) + ); + + return wrap_reply(res); + } + +public: + // It will block the thread until event happens + json_type Watch(string_ref_type key) noexcept { + + auto watch_url = m_prefix + key + "?wait=true"; + + // waiting for event + auto res = cpr::Get(watch_url); + + // fatal error + if (res.error.code != cpr::ErrorCode::OK) { + + return json_type { + {"error", res.error.message} + }; + } + + // http ok but timed out + if (res.text.empty()) { + + return json_type { + {"error", "timedout"} + }; + } + + return wrap_reply(res); + } + +private: + template + json_type wrap_reply(const T& res) noexcept { + + //std::cout << res.status_code << std::endl; + + //json_type j; + //j["code"] = res.status_code; + //j["value"] = json_type::parse(res.text); + + if (res.error.code != cpr::ErrorCode::OK) { + + return json_type { + //{"status_code", res.error.code}, + {"error", res.error.message} + }; + } + + auto j = json_type::parse(res.text); + j["statusCode"] = res.status_code; + + return j; + } +private: + string_type m_url; + string_type m_prefix; +}; + +} // namespace etcd::v2 + +#endif //_UTILITY_ETCD_HPP_ + diff --git a/section0/CMakeLists.txt b/section0/CMakeLists.txt new file mode 100644 index 0000000..add6203 --- /dev/null +++ b/section0/CMakeLists.txt @@ -0,0 +1,9 @@ + +add_executable(test test.cpp) + +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +add_library(section0 test.cpp) + +install (TARGETS section0 DESTINATION bin) +install (FILES test.cpp DESTINATION include) diff --git a/section0/sort.cpp b/section0/sort.cpp new file mode 100644 index 0000000..2b1a4df --- /dev/null +++ b/section0/sort.cpp @@ -0,0 +1,187 @@ +// Copyright (c) 2020 by Chrono +// +// g++ sort.cpp -std=c++11 -o a.out;./a.out +// g++ sort.cpp -std=c++14 -o a.out;./a.out +// g++ sort.cpp -std=c++14 -I../common -o a.out;./a.out + +#include +#include +#include +#include + +using namespace std; + +/* +template +void quick_sort_impl(T& v, int left, int right) +{ + auto quick_partition = [](decltype(v)& arr, int left, int right) + { + // key => value type => int + decltype(v.front()) key = arr[right]; + + int i = left - 1; + int j = left; + + for (; j < right; j++) + { + if (arr[j] < key) + { + std::swap(arr[j], arr[++i]); + } + } + + std::swap(arr[right], arr[++i]); + + return i; + }; + + if (left > right) + { + return; + } + + int mid = quick_partition(v, left, right); + + quick_sort_impl(v, left, mid - 1); + quick_sort_impl(v, mid + 1, right); +} +*/ + +int main() +{ + std::vector v = {42,9,4,2,5,10,1,0}; + int len = v.size(); + + // ----------------------------- + + auto bubble_sort = [=]() mutable + { + for(int i = 0;i < len - 1; i++) + { + for(int j = 0; j < len - i - 1; j++) + { + if (v[j] > v[j + 1]) + { + std::swap(v[j], v[j + 1]); + } + } + } + + for(auto& x : v) + { + cout << x << ','; + } + + cout << endl; + }; + + bubble_sort(); + + // ----------------------------- + + auto select_sort = [=]() mutable + { + for (int i = 0; i < len - 1; i++) + { + int min = i; + for(int j = i + 1; j < len; j ++) + { + if (v[min] > v[j]) + { + min = j; + } + + swap(v[i], v[min]); + } + } + + for(auto& x : v) + { + cout << x << ','; + } + + cout << endl; + }; + + select_sort(); + + // ----------------------------- + + auto insert_sort = [=]() mutable + { + int i, j; + for(i = 0;i < len; i++) + { + int tmp = v[i]; + for(j = i; j > 0 && v[j - 1] > tmp; j--) + { + v[j] = v[j - 1]; + } + + v[j] = tmp; + } + + for(auto& x : v) + { + cout << x << ','; + } + + cout << endl; + }; + + insert_sort(); + + // ----------------------------- + + auto quick_partition = [](decltype(v)& arr, int left, int right) + { + // key => value type => int + decltype(v.front()) key = arr[right]; + + int i = left - 1; + int j = left; + + for (; j < right; j++) + { + if (arr[j] < key) + { + std::swap(arr[j], arr[++i]); + } + } + + std::swap(arr[right], arr[++i]); + + return i; + }; + + std::function quick_sort_impl; + + quick_sort_impl = + [&quick_sort_impl, &quick_partition](decltype(v)& v,int left, int right) + { + if (left > right) + { + return; + } + + int mid = quick_partition(v, left, right); + + quick_sort_impl(v, left, mid - 1); + quick_sort_impl(v, mid + 1, right); + }; + + auto quick_sort = [=]() mutable + { + quick_sort_impl(v, 0, len - 1); + + for(auto& x : v) + { + cout << x << ','; + } + + cout << endl; + }; + + quick_sort(); +} diff --git a/section0/test.cpp b/section0/test.cpp index 56c7b93..1dbcc54 100644 --- a/section0/test.cpp +++ b/section0/test.cpp @@ -20,5 +20,10 @@ int main() cout << "gcc minor = " << __GNUC_MINOR__ << endl; cout << "gcc patch = " << __GNUC_PATCHLEVEL__ << endl; + // check __GLIBCXX__ for macos +#ifndef __GLIBCXX__ +# define __GLIBCXX__ "unkown version,please check or config your gcc path,or your OS not surpport." +#endif + cout << "libstdc++ = " << __GLIBCXX__ << endl; } diff --git a/section1/CMakeLists.txt b/section1/CMakeLists.txt new file mode 100644 index 0000000..e42088a --- /dev/null +++ b/section1/CMakeLists.txt @@ -0,0 +1,9 @@ +add_executable(codestyle codestyle.cpp) +add_executable(compile compile.cpp) +add_executable(oop oop.cpp) +add_executable(preprocess preprocess.cpp) + +add_library(section1 codestyle.cpp compile.cpp oop.cpp preprocess.cpp) + +install (TARGETS section1 DESTINATION bin) +install (FILES codestyle.cpp compile.cpp oop.cpp preprocess.cpp DESTINATION include) diff --git a/section1/compile.cpp b/section1/compile.cpp index 64c97f0..3b41d90 100644 --- a/section1/compile.cpp +++ b/section1/compile.cpp @@ -7,7 +7,10 @@ // // gcc -E -dM - < /dev/null +#include + #include +#include #include #include #include @@ -33,6 +36,22 @@ struct fib<1> static const int value = 1; }; +#if __cplusplus >= 201402 +constexpr int const_fib(int n) +{ + if (n <= 1) { + return 1; + } + + return const_fib(n - 1) + const_fib(n - 2); +} +#else // C++11 +int const_fib(int n) +{ + return 42; +} +#endif + //[[deprecated("deadline:2020-12-31")]] // c++14 or later [[gnu::deprecated]] // c+11 or later int old_func() @@ -107,6 +126,18 @@ void check_type(T v) cout << is_void::value << endl; } +void case5() +{ + int i = 10; + int *p = &i; + + assert(i > 0 && "i must be greater than zero"); + assert(p != nullptr); + + std::string str = "hello"; + assert(!str.empty()); +} + int main() { using namespace std; @@ -116,6 +147,8 @@ int main() cout << fib<4>::value << endl; cout << fib<5>::value << endl; + cout << const_fib(10) << endl; + old_func(); get_num(); @@ -123,6 +156,7 @@ int main() case3(); case4(); + case5(); check_type(10); //check_type((void*)0); diff --git a/section1/oop.cpp b/section1/oop.cpp index 13a8ca8..9ad4968 100644 --- a/section1/oop.cpp +++ b/section1/oop.cpp @@ -1,7 +1,7 @@ -// Copyright (c) 2050 by Chrono +// Copyright (c) 2020 by Chrono // -// g++ test05.cpp -std=c++11 -o a.out;./a.out -// g++ test05.cpp -std=c++14 -o a.out;./a.out +// g++ oop.cpp -std=c++11 -o a.out;./a.out +// g++ oop.cpp -std=c++14 -o a.out;./a.out // #include @@ -9,6 +9,10 @@ #include #include +#if(defined (__MINGW64__) || (defined __MINGW32__)) +#include +#endif + #if 1 class Interface {}; diff --git a/section1/preprocess.cpp b/section1/preprocess.cpp index bbf19f3..20c6c35 100644 --- a/section1/preprocess.cpp +++ b/section1/preprocess.cpp @@ -26,6 +26,8 @@ void case1() # #if __linux__ # define HAS_LINUX 1 +#else +# define HAS_LINUX 0 #endif # cout << "linux is " << HAS_LINUX << endl; diff --git a/section2/CMakeLists.txt b/section2/CMakeLists.txt new file mode 100644 index 0000000..ee42c0a --- /dev/null +++ b/section2/CMakeLists.txt @@ -0,0 +1,10 @@ +add_executable(auto auto.cpp) +add_executable(const const.cpp) +add_executable(exception exception.cpp) +add_executable(lambda lambda.cpp) +add_executable(smart_ptr smart_ptr.cpp) + +add_library(section2 auto.cpp const.cpp exception.cpp lambda.cpp smart_ptr.cpp) + +install (TARGETS section2 DESTINATION bin) +install (FILES auto.cpp const.cpp exception.cpp lambda.cpp smart_ptr.cpp DESTINATION include) diff --git a/section2/auto.cpp b/section2/auto.cpp index 903b04d..4bc872e 100644 --- a/section2/auto.cpp +++ b/section2/auto.cpp @@ -4,12 +4,16 @@ // g++ auto.cpp -std=c++14 -o a.out;./a.out // g++ auto.cpp -std=c++14 -I../common -o a.out;./a.out +#include + #include #include #include #include #include +#include + #include void case1() @@ -97,6 +101,10 @@ void case6() decltype(auto) x1 = (x); decltype(auto) x2 = &x; decltype(auto) x3 = x1; + + assert(std::is_lvalue_reference::value); + assert(std::is_pointer::value); + assert(std::is_lvalue_reference::value); } auto get_a_set() diff --git a/section2/lambda.cpp b/section2/lambda.cpp index a64813b..d46305e 100644 --- a/section2/lambda.cpp +++ b/section2/lambda.cpp @@ -21,6 +21,7 @@ void case1() auto pfunc = &my_square; (*pfunc)(3); + pfunc(3); auto func = [](int x) { @@ -144,6 +145,21 @@ void case6() cout << f(str) << endl; } +// demo for function + lambda +class Demo final +{ +public: + using func_type = std::function; +public: + func_type print = [this]() + { + cout << "value = " << m_value << endl; + cout << "hello function+lambda" << endl; + }; +private: + int m_value = 10; +}; + int main() { case1(); @@ -153,5 +169,8 @@ int main() case5(); case6(); + Demo d; + d.print(); + cout << "lambda demo" << endl; } diff --git a/section2/smart_ptr.cpp b/section2/smart_ptr.cpp index b752796..af2b947 100644 --- a/section2/smart_ptr.cpp +++ b/section2/smart_ptr.cpp @@ -23,7 +23,7 @@ void case1() using namespace std; unique_ptr ptr1(new int(10)); - assert(*ptr1 = 10); + assert(*ptr1 == 10); assert(ptr1 != nullptr); unique_ptr ptr2(new string("hello")); diff --git a/section3/CMakeLists.txt b/section3/CMakeLists.txt new file mode 100644 index 0000000..e689c36 --- /dev/null +++ b/section3/CMakeLists.txt @@ -0,0 +1,9 @@ +add_executable(algo algo.cpp) +add_executable(container container.cpp) +add_executable(string string.cpp) +add_executable(thread thread.cpp) + +add_library(section3 algo.cpp container.cpp string.cpp thread.cpp) + +install (TARGETS section3 DESTINATION bin) +install (FILES algo.cpp container.cpp string.cpp thread.cpp DESTINATION include) diff --git a/section4/CMakeLists.txt b/section4/CMakeLists.txt new file mode 100644 index 0000000..dbe1af8 --- /dev/null +++ b/section4/CMakeLists.txt @@ -0,0 +1,15 @@ +add_executable(cpr cpr.cpp) +add_executable(curl curl.cpp) +add_executable(gperf gperf.cpp) +add_executable(json json.cpp) +add_executable(lua_shared lua_shared.cpp) +add_executable(luajit luajit.cpp) +add_executable(msgpack msgpack.cpp) +add_executable(protobuf protobuf.cpp) +add_executable(pybind pybind.cpp) +add_executable(zmq zmq.cpp) + +add_library(section4 cpr.cpp curl.cpp demo.py embedded.lua flame.svg gperf.cpp icicle.svg json.cpp lua_shared.cpp luajit.cpp msgpack.cpp protobuf.cpp pybind.cpp sample.proto setup.sh shared.lua zmq.cpp json.hpp sample_v3.proto) + +install (TARGETS section4 DESTINATION bin) +install (FILES cpr.cpp curl.cpp demo.py embedded.lua flame.svg gperf.cpp icicle.svg json.cpp lua_shared.cpp luajit.cpp msgpack.cpp protobuf.cpp pybind.cpp sample.proto setup.sh shared.lua zmq.cpp json.hpp sample_v3.proto DESTINATION include) diff --git a/section4/demo.py b/section4/demo.py index 435be03..c2b2855 100755 --- a/section4/demo.py +++ b/section4/demo.py @@ -20,4 +20,4 @@ print(p.get()) p.set(1984) -assert(p.get() == 1984); +assert(p.get() == 1984) diff --git a/section4/msgpack.cpp b/section4/msgpack.cpp index dc47b9d..7bc83c1 100644 --- a/section4/msgpack.cpp +++ b/section4/msgpack.cpp @@ -97,7 +97,11 @@ void case3() msgpack::sbuffer sbuf; msgpack::pack(sbuf, book1); - auto obj = msgpack::unpack(sbuf.data(), sbuf.size()).get(); + // may cause std::bad_cast error + //auto obj = msgpack::unpack(sbuf.data(), sbuf.size()).get(); + + auto handle = msgpack::unpack(sbuf.data(), sbuf.size()); + auto obj = handle.get(); Book book2; obj.convert(book2); diff --git a/section4/protobuf.cpp b/section4/protobuf.cpp index 4aa0b5e..8ba938f 100644 --- a/section4/protobuf.cpp +++ b/section4/protobuf.cpp @@ -6,8 +6,8 @@ // // protoc --cpp_out=. sample.proto // -// g++ protobuf.cpp -std=c++11 -lprotobuf -o a.out;./a.out -// g++ protobuf.cpp -std=c++14 -lprotobuf -o a.out;./a.out +// g++ protobuf.cpp -std=c++11 -lprotobuf -lpthread -o a.out;./a.out +// g++ protobuf.cpp -std=c++14 -lprotobuf -lpthread -o a.out;./a.out #include diff --git a/section4/sample_v3.proto b/section4/sample_v3.proto new file mode 100644 index 0000000..96a314b --- /dev/null +++ b/section4/sample_v3.proto @@ -0,0 +1,25 @@ +// Copyright (c) 2020 by Chrono +// +// protoc --cpp_out=. sample_v3.proto + +syntax = "proto3"; + +package sample; + +message Vendor +{ + uint32 id = 1; + string name = 2; + bool valid = 3; + string tel = 4; +} + +message Product +{ + int32 id = 1; + string name = 2; + + string tag = 3; + + Vendor vendor = 10; +} diff --git a/section5/CMakeLists.txt b/section5/CMakeLists.txt new file mode 100644 index 0000000..7254f25 --- /dev/null +++ b/section5/CMakeLists.txt @@ -0,0 +1,8 @@ +add_executable(client client.cpp) + +add_executable(srv srv.cpp) + +add_library(section5 client.cpp conf.lua Config.hpp cpplang.hpp hello.hpp SalesData.hpp SpinLock.hpp srv.cpp Summary.hpp Zmq.hpp) +install (TARGETS section5 DESTINATION bin) + +install (FILES client.cpp conf.lua Config.hpp cpplang.hpp hello.hpp SalesData.hpp SpinLock.hpp srv.cpp Summary.hpp Zmq.hpp DESTINATION include) diff --git a/section5/SpinLock.hpp b/section5/SpinLock.hpp index 3bb3891..5a2aa50 100644 --- a/section5/SpinLock.hpp +++ b/section5/SpinLock.hpp @@ -24,7 +24,7 @@ class SpinLock final void lock() noexcept { for(;;) { - if (m_lock.test_and_set()) { + if (!m_lock.test_and_set()) { return; } @@ -34,7 +34,7 @@ class SpinLock final bool try_lock() noexcept { - return m_lock.test_and_set(); + return !m_lock.test_and_set(); } void unlock() noexcept diff --git a/section5/srv.cpp b/section5/srv.cpp index cea962a..d33bee8 100644 --- a/section5/srv.cpp +++ b/section5/srv.cpp @@ -73,7 +73,8 @@ try // async process msg // todo: try-catch - std::async(std::launch::async, + //auto f = std::async(std::launch::async, + std::thread( [&sum, msg_ptr]() //[&sum, &count](decltype(msg_ptr) ptr) { @@ -90,7 +91,7 @@ try //debug_print(book); sum.add_sales(book); - }); // async + }).detach(); // async } // for(;;) }; // recv_cycle lambda @@ -126,13 +127,13 @@ try } // for(;;) }; // log_cycle lambda - // launch recv_cycle then wait - auto fu = std::async(std::launch::async, recv_cycle); - // launch log_cycle - std::async(std::launch::async, log_cycle); + auto fu1 = std::async(std::launch::async, log_cycle); + + // launch recv_cycle then wait + auto fu2 = std::async(std::launch::async, recv_cycle); - fu.wait(); + fu2.wait(); } catch(std::exception& e) {