我需要使用 listings 包逐行注释源代码。下面是我要查找的示例(使用 MS Word 制作):
这些特定示例显示了执行每行的价格(左列)以及被调用的次数(右列)。
这是我目前所做的事情(没有做任何注释,因为我不确定从哪里开始):
\documentclass[fleqn]{article}
\usepackage{listings}
\usepackage{color}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\begin{document}
\begin{lstlisting}[language=c++,caption=Insertion sort realizacija masyve]
std::vector<int> insertion_sort_array::sort(const std::vector<int> &in) {
std::vector<int> res(in);
for (std::vector<int>::size_type i = 1; i < res.size(); i++) {
for (std::size_t j = i; j > 0 && res[j - 1] > res[j]; j--) {
int tmp = res[j - 1];
res[j - 1] = res[j];
res[j] = tmp;
}
}
return res;
}
\end{lstlisting}
\end{document}
答案1
这是对 tikzmark 和 listings 链接答案的后续内容。在示例的序言中,添加
\usepackage[left=.5in,width=5.5in]{geometry}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\usetikzmarklibrary{listings}
\usepackage{tikzpagenodes}
\newcommand{\annot}[3]{
\node at ( {pic cs:line-texcode-#1-end} -| {current page marginpar area.east}) [left] {#2};
\node at ( {pic cs:line-texcode-#1-end} -| {current page marginpar area.east}) [right] {#3};
}
% usage: \annot{line-number}{left remark}{right remark}
然后列出环境之后:
\begin{tikzpicture}[remember picture,overlay]
% draw the vertical line
\draw ( {pic cs:line-texcode-1-start} -| {current page marginpar area.east})
-- ( {pic cs:line-texcode-13-end} -| {current page marginpar area.east});
\annot{1}{Kaine}{Kartai}
\annot{2}{$c_1$}{$1$}
\annot{4}{$T_L(\mathrm{res})$}{$1$}
\annot{6}{$c_2$}{$\mathrm{res.length}+1$}
\annot{7}{$c_3$}{$\sum_{i=1}^{\mathrm{res.length}}\sum_{j=0}^i 1$}
\end{tikzpicture}
导致:
我对间距不是完全满意,但我对几何、列表和 tikz 了解不够。