我希望能够展示一段 C++ 代码片段。我希望这段代码片段带有标题、引用,并包含在包生成的算法表中algorithm2e
。我希望它能发挥作用:
\begin{algorithm}
\caption{Hello.}
\label{alg:cbscppapi}
\begin{lstlisting}
[si, SB, qq, kk] = cbs_{grad,div}(kk);
[si, SB, qq, kk] = cbs_{grad,div}(kk, tau);
\end{lstlisting}
\end{algorithm}
但相反,我得到了奇怪的结果:
有什么提示吗?
答案1
将 存储lstlisting
在一个盒子里,然后使用 里面的盒子algorithm
:
\documentclass{article}
\usepackage{algorithm2e,listings}
\newsavebox{\codebox}
\begin{document}
\begin{lrbox}{\codebox}
\begin{lstlisting}
[si, SB, qq, kk] = cbs_{grad,div}(kk);
[si, SB, qq, kk] = cbs_{grad,div}(kk, tau);
\end{lstlisting}
\end{lrbox}
\begin{algorithm}
\caption{Hello.}\label{alg:cbscppapi}
\usebox{\codebox}
\end{algorithm}
\end{document}
答案2
有关的:algorithm2e 中的 verbatim 环境
将代码列表放入框中怎么样?
\documentclass{article}
\usepackage{listings}
\usepackage{algorithm2e}
\newsavebox{\mycode}
\begin{document}
\begin{lrbox}{\mycode}
\begin{lstlisting}
[si, SB, qq, kk] = cbs_{grad,div}(kk);
[si, SB, qq, kk] = cbs_{grad,div}(kk, tau);
\end{lstlisting}
\end{lrbox}
\begin{algorithm}
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e}
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section and \usebox{\mycode}\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\caption{How to write algorithms}
\end{algorithm}
\end{document}