我是c ++正则表达式的新手.我有一个字符串"{1,2,3}",我想提取数字1 2 3.我认为我应该使用regex_search但它失败了.
#include<iostream>
#include<regex>
#include<string>
using namespace std;
int main()
{
string s1("{1,2,3}");
string s2("{}");
smatch sm;
regex e(R"(\d+)");
cout << s1 << endl;
if (regex_search(s1,sm,e)){
cout << "size: " << sm.size() << endl;
for (int i = 0 ; i < sm.size(); ++i){
cout << "the " << i+1 << "th match" <<": "<< sm[i] << endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
{1,2,3}
size: 1
the 1th match: 1
Run Code Online (Sandbox Code Playgroud) 据我了解,关键字constexpr告诉编译器表达式的计算可以在编译时发生。具体来说,constexpr在变量上意味着可以在编译时评估变量的值,而constexpr在函数上意味着可以在编译时调用该函数并评估其返回值。如果函数在运行时被调用,它只是作为一个普通函数。
今天,我写了一段代码来尝试使用constexpr:
#include <iostream>
using namespace std;
constexpr long int fib(int n)
{
return (n <= 1)? n : fib(n-1) + fib(n-2);
}
int main ()
{
constexpr long int res = fib(32);
// const long int res = fib(32);
cout << res << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我原以为代码的编译会花费很多时间,但我错了。编译只用了0.0290s:
$ time g++ test.cpp
real 0m0.290s
user 0m0.252s
sys 0m0.035s
Run Code Online (Sandbox Code Playgroud)
但是如果我constexpr long int res = fib(32);换成const long int res = …