可以直接在命令行中定义函数,通过使用declare命令来打印出来,使用shell函数,只需要在命令行中输入函数名称。一旦不再需要某个shell函数,可以使用unset命令来删除它。

[root cplusplus]#foo() { echo "Inside function"; }
[root cplusplus]#foo
Inside function
[root cplusplus]#declare -f foo
foo ()
{
    echo "Inside function"
}
[root cplusplus]#unset foo
[root cplusplus]#declare -f foo

向子进程传入一个函数

当shell进程新建一个子进程并在子进程中运行一个shell命令时,该函数定义就会被传给子shell进程。这种方式只是用于父进程也是shell的情况。

[root cplusplus]#foo() { echo "Inside function"; }
[root cplusplus]#export -f foo
[root cplusplus]#declare -f foo
foo ()
{
    echo "Inside function"
}
[root cplusplus]#bash
[root cplusplus]#declare -f foo
foo ()
{
    echo "Inside function"
}
[root cplusplus]#

C++合并两个vector

Concatenating two std::vectors
If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator along with insert (or copy):

#include <vector>
#include <iostream>
#include <iterator>

int main(int argc, char** argv) {
  std::vector<int> dest{1,2,3,4,5};
  std::vector<int> src{6,7,8,9,10};

  // Move elements from src to dest.
  // src is left in undefined but safe-to-destruct state.
  dest.insert(
      dest.end(),
      std::make_move_iterator(src.begin()),
      std::make_move_iterator(src.end())
    );

  // Print out concatenated vector.
  std::copy(
      dest.begin(),
      dest.end(),
      std::ostream_iterator<int>(std::cout, "\n")
    );

  return 0;
}

使用google benchmark验证,使用make_move_iterator性能上会好一些。

[root benchmark]#./a.out
2021-12-25T11:52:00+08:00
Running ./a.out
Run on (4 X 1900 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x2)
  L1 Instruction 32 KiB (x2)
  L2 Unified 256 KiB (x2)
  L3 Unified 3072 KiB (x1)
Load Average: 0.00, 0.01, 0.05
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
---------------------------------------------------------------------
Benchmark                           Time             CPU   Iterations
---------------------------------------------------------------------
bench_vector_insert           3362466 ns      3362789 ns          206
bench_vector_move_iterator    3294766 ns      3295113 ns          212