我写了一个函数来确定两个单词是否是字谜.单词A是单词B的字谜,如果你可以通过重新排列字母来构建单词B,例如:
lead is anagram of deal
Run Code Online (Sandbox Code Playgroud)
这是我的功能:
bool is_anagram(std::string const & s1, std::string const & s2)
{
auto check = [](std::string const & x)
{
std::map<char, unsigned> counter;
for(auto const & c : x)
{
auto it = counter.find(c);
if(it == counter.end())
counter[c] = 1;
else
++counter[c];
}
return counter;
};
return check(s1) == check(s2);
}
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,但随着单词数量的增加(这个函数在我的应用程序中使用了数百万次),很快就成了我应用程序的主要瓶颈.
有没有人知道如何加快这个功能?
在求职面试中,我被要求编写一个确定某个类型是否为指针的元函数.这是我提出的:
template <typename T>
struct is_pointer
{ static const bool value = false; }
template <typename T>
struct is_pointer<T *>
{ static const bool value = true; }
Run Code Online (Sandbox Code Playgroud)
然后我被要求编写一个元断言,如果我的is_pointer函数没有做正确的事情,它将在编译期间失败.
当我使用时static_assert,他明确地告诉我,我可能只使用C++ 98标准.我怎样才能做到这一点?
我偶然发现了这个typedef:
typedef char (&small)[1];
typedef char (&large)[2];
Run Code Online (Sandbox Code Playgroud)
我知道&作为参考限定符或运算符地址.既然我们在这里处理类型,我猜它是一个参考,但括号有特殊用途吗?
在上下文中,我从中获取它用于执行类型的可转换性的编译时间检查,这种typedef如何帮助解决这个问题?
我的问题很简单:我有一个动态的对象数组,它有一个返回字符串的方法.我想将所有这些字符串连接在一起.
如果我有一个字符串数组而不是一个方法返回一个字符串的对象,这将是一个简单的任务:
std::vector<std::string> v{ "f", "o", "o" };
std::string const x = std::accumulate(v.begin(), v.end(), std::string());
Run Code Online (Sandbox Code Playgroud)
但就我而言,它看起来像这样:
struct foo
{
foo(std::string const & name) : name_(name) {}
std::string const & name() const { return name_; }
private:
std::string const name_;
};
std::vector<foo> v{ foo("f"), foo("o"), foo("o") };
Run Code Online (Sandbox Code Playgroud)
我想使用标准库算法,因为我确信这些算法是有效的,而且我不需要调试,但这很难阅读和理解:
std::vector<std::string> transformed(v.size());
std::transform(v.begin(), v.end(), transformed.begin(),
[](foo const & f) { return f.name(); });
std::string const x = std::accumulate(transformed.begin(), transformed.end(),
std::string());
Run Code Online (Sandbox Code Playgroud)
未来的维护人员可能(并且理所当然地)帮助我打击我,因为不必要地使一项简单的任务复杂化,这可以通过以下方式完成:
std::string x;
for(auto const & f : v)
x += f.name();
Run Code Online (Sandbox Code Playgroud)
这里有什么比我更容易看到的东西,或者确实是这样的情况下应该让标准库休息,并使用for循环(无论如何积累归结为什么)?