用于查找一系列等长字符串的惯用C++,给定字符串向量(按长度排序)

Ale*_*son 4 c++ string stl

给定a std::vector< std::string >,矢量按字符串长度排序,如何找到等长强度的范围?

我期待着C++中的惯用解决方案.

我找到了这个解决方案:

// any idea for a better name? (English is not my mother tongue)
bool less_length( const std::string& lhs, const std::string& rhs )
{
    return lhs.length() < rhs.length();
}

std::vector< std::string > words;
words.push_back("ape");
words.push_back("cat");
words.push_back("dog");
words.push_back("camel");
size_t length = 3;
// this will give a range from "ape" to "dog" (included):
std::equal_range( words.begin(), words.end(), std::string( length, 'a' ), less_length );
Run Code Online (Sandbox Code Playgroud)

有没有一种标准的方法(漂亮)?

Ste*_*sop 5

我希望您可以按如下方式编写比较器:

struct LengthComparator {
    bool operator()(const std::string &lhs, std::string::size_type rhs) {
        return lhs.size() < rhs;
    }
    bool operator()(std::string::size_type lhs, const std::string &rhs) {
        return lhs < rhs.size();
    }
    bool operator()(const std::string &lhs, const std::string &rhs) {
        return lhs.size() < rhs.size();
    }
};
Run Code Online (Sandbox Code Playgroud)

然后使用它:

std::equal_range(words.begin(), words.end(), length, LengthComparator());
Run Code Online (Sandbox Code Playgroud)

我希望operator()永远不会使用第三个重载,因为它提供的信息是多余的.范围必须预先排序,因此算法比较范围中的两个项目是没有意义的,应该将范围中的项目与您提供的目标进行比较.但标准并不保证.[编辑:并定义所有三个意味着您可以使用相同的比较器类将矢量按顺序排列,这可能很方便].

这适用于我(gcc 4.3.4),虽然我认为这也适用于你的实现,但我不太确定它实际上是有效的.它实现了比较说明结果的描述equal_range是正确的,25.3.3/1不要求模板参数T必须完全是迭代器引用的对象的类型.但是可能会有一些我错过的文字增加了更多的限制,所以在使用它之前我会做更多的标准拖网操作.