在下面的程序中,递归调用辅助函数,以便从由数组表示的前序和后序遍历创建二叉树.运行时很快,并且在Leetcode上超过所有提交的100%.
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int,int> m;
for(int i=0; i<inorder.size();i++){
m[inorder[i]]=i;
}
return helper(preorder, inorder, 0,preorder.size()-1,0, inorder.size()-1, m);
}
TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int pStart, int pEnd, int inStart, int inEnd,unordered_map<int,int>& m){
if(pStart>pEnd || inStart>inEnd) return NULL;
TreeNode* root= new TreeNode(preorder[pStart]);
int pivLoc=m[root->val];
int numsLeft=pivLoc-inStart;
root->left=helper(preorder, inorder, pStart+1, pStart+numsLeft,inStart, pivLoc-1,m);
root->right=helper(preorder, inorder, pStart+numsLeft+1, pEnd,pivLoc+1, inEnd,m);
return root;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我更改辅助函数使得最后一个参数(unordered_map)按值传递,则会获得运行时超出的错误.我想知道为什么.地图本身永远不会被重新分配,它的价值也不会被重新分配.由于映射是通过值传递的,这意味着每次调用函数时都会调用复制构造函数.这是通过常数因子增加函数运行时还是实际上会改变渐近复杂度?我相信复制构造函数导致大幅增加,但只是一个常数因子,因为副本是与输入相关的恒定时间操作.
如果经常使用索引.at()
而不是[]
访问向量或字符串中的元素,则经常会出现索引超出范围的错误,这很容易捕获。但是,at()
由于进行边界检查,会使我的程序速度降低5倍。
我试图写一个宏来代替.at(someVariable)
用[someVariable]
这样我就可以取消对宏观的而不是取代每.at()
一个[]
手动。我已经阅读了cppreference.com上有关宏的文档,但似乎无法设计一种获得此功能的方法。
在下面的代码中,我尝试使其能够进行最小程度的验证,并且可以正常运行并执行应执行的操作(无论我在线程中传递的顺序如何,均按顺序打印1,2,3)。但是,如果我在函数三中注释的行中将m1更改为m2,则此代码将崩溃,并显示消息“在没有活动异常的情况下终止”。为什么不能使用相同的条件变量同时锁定两个不同的互斥锁?
#include <functional>
#include <mutex>
#include <condition_variable>
#include <future>
#include <iostream>
void printFirst() {
cout << "1";
}
void printSecond() {
cout << "2";
}
void printThird() {
cout << "3";
}
struct test {
condition_variable c, c2;
int count = 0;
mutex m1,m2;
void first(function<void()> printFirst) {
printFirst();
count++;
c.notify_all();
}
void second(function<void()> printSecond) {
unique_lock<mutex> sL1(m1);
c.wait(sL1,[&]{return count>=1;});
printSecond();
count+=1;
c.notify_all();
}
void third(function<void()> printThird) {
unique_lock<mutex> sL2(m1); //If I make m1, m2, this code crashes
c.wait(sL2,[&]{return count>=2;}); …
Run Code Online (Sandbox Code Playgroud) 我要匹配代码中从第一个g到第一个括号的字符串。我不知道为什么不这样做,因为我使用了转义字符。例如,在此字符串上:
你好测试g55_2(cnn
我打算匹配g55_2 // g ++ 5.4.0
#include <iostream>
#include<regex>
#include<string>
int main()
{
std::string s("g.*\(");
std::regex re(s);
}
Run Code Online (Sandbox Code Playgroud)
我在这里https://regex101.com/尝试过我的正则表达式,它可以工作,但是由于标题错误,我的c ++无法编译。
是否有一个排序集实现允许在 O(1) 中获取第一个元素?C++ 的 std::set 可以做到这一点,所以我不明白为什么我们不能在 Java 中做到这一点。谢谢!
=>在C++中不可重载.我一直想知道这是否只是一个纯粹的巧合,或者是否有一个特定的原因,这两个字符的序列不能重载.比较运算符<=>的出现让我相信前者.
我认为它是重载的主要候选者,因为它看起来像一个箭头,这在函数式编程语法和数学中非常常见.当然 - >已经存在但是有另一个箭头可能有助于消除两者之间的歧义.我也看不出它是如何破坏向后兼容性的.