2

I would like to be able to present a C++ code snippet. I would like for this snippet to be captioned, referenced, and included in the Table of Algorithms generated by the algorithm2e package. This is what I wish would work:

\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}

But instead I get funky results:

Results I get. Notice the bad box.

Any hints?

2 Answers 2

4

Store the lstlisting inside a box and then use the box inside an algorithm:

enter image description here

\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}
5

Related: verbatim environment inside algorithm2e

How about putting the code listing in a box?

\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}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .