使用相同的算法两次,没有新的标题编号

使用相同的算法两次,没有新的标题编号

我正在尝试做类似的事情“两次使用相同的数字,没有新的数字“,但随着算法2e包。
因此我写了下面的代码。

\newcommand{\repeatAlgoCaption}[2]{%
    \renewcommand{\thealgocf}{\ref{#1}}% modify the displayed label
    \captionsetup{list=no}% not displayed in the list of algorithms
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the original algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}

使用此代码会hyperref产生以下错误

! Argument of \reserved@a has an extra }.
<inserted text>
              \par

我不知道如何让它工作,任何建议都值得感激。

这是我的工作 MWE(没有 hyperref

\documentclass{article}
    
\usepackage{caption}
\usepackage{algorithm2e}
    
% from https://tex.stackexchange.com/questions/200211/
\newcommand{\repeatAlgoCaption}[2]{%
    \renewcommand{\thealgocf}{\ref{#1}}% modify the displayed label
    \captionsetup{list=no}% not displayed in the list of algorithms
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the repeted algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}
    
% \usepackage{hyperref}% The one guilty
    
% arara: pdflatex
% arara: pdflatex
\begin{document}
    
\begin{algorithm}[H]
\caption{my caption}\label{alg:mylabel}
\end{algorithm}
    
\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}
    
\begin{algorithm}[H]
\repeatAlgoCaption{alg:mylabel}{my caption}
\end{algorithm}
    
\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}
    
\end{document}

输出为

正确输出

答案1

\thealgoc可以保存(使用额外的宏)的内容,而不是使用\ref(或\ref*),例如:

\documentclass{article}

\usepackage{caption}
\usepackage{algorithm2e}

\makeatletter
\newcommand\saveAlgoCounter[1]{%
    \expandafter\xdef\csname saveAlgoCounter@#1\endcsname{\thealgocf}}% save \thealgocf
\newcommand{\repeatAlgoCaption}[2]{%
    \expandafter\let\expandafter\thealgocf\csname saveAlgoCounter@#1\endcsname% use saved \thealgocf
    \captionsetup{list=no}%
    \caption{#2 (repeated from page~\pageref{#1})}% page reference of the repeted algorithm
    \addtocounter{algocf}{-1}% the next figure after the repeat gets the right number
}
\makeatother

\usepackage[hypertexnames=false]{hyperref}% The one guilty
% "hypertexnames=false" prevents the warning "destination with the same identifier (name{algocf.1}) has been already used, duplicate ignored"

% arara: pdflatex
% arara: pdflatex
\begin{document}

\begin{algorithm}[H]
\caption{my caption}\label{alg:mylabel}
\saveAlgoCounter{alg:mylabel}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\begin{algorithm}[H]
\repeatAlgoCaption{alg:mylabel}{my caption}
\end{algorithm}

\begin{algorithm}[H]
\caption{my other caption}
\end{algorithm}

\end{document}

相关内容