如何获得C ++中的下一个前缀? [英] How to get the next prefix in C++?

查看:385
本文介绍了如何获得C ++中的下一个前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个序列(例如字符串Xa),我想按照词典(即Xb)获得下一个前缀。 aZ的下一个应为b

Given a sequence (for example a string "Xa"), I want to get the next prefix in order lexicographic (i.e "Xb"). The next of "aZ" should be "b"

此功能很有用的激励用例描述此处

A motivating use case where this function is useful is described here.

由于我不想重塑,我想知道是否有任何函数在C ++ STL或boost,可以帮助定义这个泛型函数很容易?
如果没有,您认为此功能可能有用吗?

As I don't want to reinvent the wheel, I'm wondering if there is any function in C++ STL or boost that can help to define this generic function easily? If not, do you think that this function can be useful?

注意


  • 即使示例是字符串,函数也应该适用于任何序列。

  • 词典顺序应该是函数的模板参数。

C ++ / Boost没有什么可以帮助定义这个泛型函数,并且这个函数太具体,不能免费提出。我将实现一个通用的next_prefix,然后我将请求您是否觉得有用。

From the answers I conclude that there is nothing on C++/Boost that can help to define this generic function easily and also that this function is too specific to be proposed for free. I will implement a generic next_prefix and after that I will request if you find it useful.

我已经接受了单一的答案,给出了一些提示,建议的实现不是通用的。

I have accepted the single answer that gives some hints on how to do that even if the proposed implementation is not generic.

推荐答案

我不知道我理解你希望字符串转换的语义,但也许像下面这样的事情可以作为你的起点。

I'm not sure I understand the semantics by which you wish the string to transform, but maybe something like the following can be a starting point for you. The code will increment the sequence, as if it was a sequence of digits representing a number.

template<typename Bi, typename I>
bool increment(Bi first, Bi last, I minval, I maxval)
{
    if( last == first ) return false;
    while( --last != first && *last == maxval ) *last = minval;
    if( last == first && *last == maxval ) {
        *last = minval;
        return false;
    }
    ++*last;
    return true;
}

也许你想添加一个重载函数对象,原语的专业化。几个示例:

Maybe you wish to add an overload with a function object, or an overload or specialization for primitives. A couple of examples:

string s1("aaz");
increment(s1.begin(), s1.end(), 'a', 'z');
cout << s1 << endl;     // aba

string s2("95");
do {
    cout << s2 << ' ';  // 95 96 97 98 99
} while( increment(s2.begin(), s2.end(), '0', '9') );
cout << endl;

这篇关于如何获得C ++中的下一个前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆