c++ vector<string*>和map<int,string*>的delete问题

#include《iostream》
#include《vector》
#include《map》
using namespace std;
int main()
{
vector《string*》 t ;

//向容器装入指针
for(int i=0;i {
string* p=news string("i");
t.push_back(p);
}
//释放指针
vector《string*》::iterator ite;
for(ite=t.begin();ite!=t.end();ite++)
delete *ite;
//以上代码我理解了,设ite指向一种指针x,则指针x指向string
//delete *ite既可释放new的内存
//问题是下面的map《int,string*》
map《int,string*》 m;
for(int i=0; i {
string *p=new string("123");
m.insert(pair《int,string*》(i , p));
}
map::iterator tt;
for(tt=m.begin(); tt!=m.end(); tt++)
{
delete tt->second;

//为什么是这样,按照vector例子,设tt->second应该是指向指针x,指针x指向string
//那么要释放内存的话,不应该是delete *(tt->second)
//tt->second指向假设的x指针,解除索引,再释放掉内存。我理解错了吗
}
}


1个回答

主要还是对应delete的对象是什么,vector中,它的元素就是要释放的,所以用delete *ite
而对于map,你需要释放的是它的value,所以用tt->second来获取value。然后再释放

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c++ vector<string*>和map<int,string*>的delete问题

#include《iostream》 #include《vector》 #include《map》 using namespace std; int main() { vector《string*》 t ; //向容器装入指针 for(int i=0;i<3;i++) { string* p=news string("i"); t.push_back(p); } //释放指针 vector《string*》::iterator ite; for(ite=t.begin();ite!=t.end();ite++) delete *ite; //以上代码我理解了,设ite指向一种指针x,则指针x指向string //delete *ite既可释放new的内存 //问题是下面的map《int,string*》 map《int,string*》 m; for(int i=0; i<3; i++) { string *p=new string("123"); m.insert(pair《int,string*》(i , p)); } map<int,string*>::iterator tt; for(tt=m.begin(); tt!=m.end(); tt++) { delete tt->second; //为什么是这样,按照vector例子,设tt->second应该是指向指针x,指针x指向string //那么要释放内存的话,不应该是delete *(tt->second) //tt->second指向假设的x指针,解除索引,再释放掉内存。我理解错了吗 } } ``` ```

Hadoop mapreduce传值问题

最近mapreduce编写遇到了问题。在step4中,reduce可以同时收到从map中传来的A和B两组数据。但是在step5中的reudce却无法同时收到A、B两组数据,出现了有A没B,有B没A的现象,即A和B无法在同一次循环中出现。 step5,我几乎是从step4复制过来的,很奇怪他们的执行步骤为什么不一样。 step4 ``` import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import org.apache.commons.net.telnet.EchoOptionHandler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter; //同现矩阵和用户偏好矩阵相乘 public class Step4 { public static boolean run(Configuration con, Map<String, String>map) { try { FileSystem fs = FileSystem.get(con); Job job = Job.getInstance(); job.setJobName("step4"); job.setJarByClass(App.class); job.setMapperClass(Step4_Mapper.class); job.setReducerClass(Step4_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path[] { new Path(map.get("Step4Input1")), new Path(map.get("Step4Input2")) }); Path outpath = new Path(map.get("Step4Output")); if(fs.exists(outpath)){ fs.delete(outpath,true); } FileOutputFormat.setOutputPath(job, outpath); boolean f = job.waitForCompletion(true); return f; }catch(Exception e) { e.printStackTrace(); } return false; } static class Step4_Mapper extends Mapper<LongWritable, Text, Text, Text>{ private String flag; //每次map时都会先判断一次 @Override protected void setup(Context context )throws IOException,InterruptedException{ FileSplit split = (FileSplit) context.getInputSplit(); flag = split.getPath().getParent().getName(); System.out.print(flag+ "*************************"); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ String[] tokens = Pattern.compile("[\t,]").split(value.toString()); //物品共现矩阵 if(flag.equals("step3")) { // i2:i3 1 // i2:i2 2 String[] v1 = tokens[0].split(":"); String itemID1 = v1[0]; String itemID2 = v1[1]; String num = tokens[1]; Text k = new Text(itemID1); Text v = new Text("A:"+itemID2+","+num); //A:i2,1 context.write(k,v); }else if(flag.equals("step2")) {//用户评价矩阵 // u2 i1:2,i3:4 String userID = tokens[0]; for(int i=1;i<tokens.length;i++) { String[] vector = tokens[i].split(":"); String itemID = vector[0]; //物品ID String pref = vector[1];//评分 Text k = new Text(itemID); Text v = new Text("B:"+userID+","+pref); context.write(k, v); } } } } static class Step4_Reducer extends Reducer<Text, Text, Text, Text>{ @Override protected void reduce(Text key, Iterable<Text>values, Context context) throws IOException,InterruptedException{ //A为同现矩阵,B为用户偏好矩阵 //某一个物品k,针对它和其他所有物品的同现次数v,都在mapA集合中 // Text k = new Text(itemID1); //Text v = new Text("A:"+itemID2+","+num); //A:i2,1 // context.write(k,v); //和该物品(key中的itemID)同现的其他物品的同现集合 //其他物品ID为map的key,同现数字为值 Map<String, Integer> mapA = new HashMap<String,Integer>(); //该物品(key中的itemID),所有用户的推荐权重分数 Map<String, Integer>mapB = new HashMap<String,Integer>(); for(Text line:values) { String val = line.toString(); if(val.startsWith("A:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); try { mapA.put(kv[0], Integer.parseInt(kv[1])); }catch(Exception e) { e.printStackTrace(); } }else if(val.startsWith("B:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); try { mapB.put(kv[0], Integer.parseInt(kv[1])); }catch(Exception e) { e.printStackTrace(); } } } double result = 0; Iterator<String>iter = mapA.keySet().iterator(); while(iter.hasNext()) { String mapk = iter.next(); //itemID int num =mapA.get(mapk).intValue(); // 获取同现值 Iterator<String>iterb = mapB.keySet().iterator(); while(iterb.hasNext()) { String mapkb = iterb.next(); int pref = mapB.get(mapkb).intValue(); result = num*pref; Text k = new Text(mapkb); Text v = new Text(mapk+ "," + result); context.write(k, v); } } } } } ``` step5 ``` import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import org.apache.commons.net.telnet.EchoOptionHandler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Mapper.Context; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter; //获得结果矩阵 public class Step5 { public static boolean run(Configuration con, Map<String, String>map) { try { FileSystem fs = FileSystem.get(con); Job job = Job.getInstance(); job.setJobName("step5"); job.setJarByClass(App.class); job.setMapperClass(Step5_Mapper.class); job.setReducerClass(Step5_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path[] { new Path(map.get("Step5Input1")), new Path(map.get("Step5Input2")) }); Path outpath = new Path(map.get("Step5Output")); if(fs.exists(outpath)){ fs.delete(outpath,true); } FileOutputFormat.setOutputPath(job, outpath); boolean f = job.waitForCompletion(true); return f; }catch(Exception e) { e.printStackTrace(); } return false; } static class Step5_Mapper extends Mapper<LongWritable, Text, Text, Text>{ private String flag; //每次map时都会先判断一次 @Override protected void setup(Context context )throws IOException,InterruptedException{ FileSplit split = (FileSplit) context.getInputSplit(); flag = split.getPath().getParent().getName(); System.out.print(flag+ "*************************"); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ String[] tokens = Pattern.compile("[\t,]").split(value.toString()); if(flag.equals("step4")) { // i2:i3 1 // i2:i2 2 Text k = new Text(tokens[0]); Text v = new Text("A:"+tokens[1]+","+tokens[2]); context.write(k, v); }else if(flag.equals("step2")) {//用户评价矩阵 // u2 i1:2,i3:4 String userID = tokens[0]; for(int i=1;i<tokens.length;i++) { String[] vector = tokens[i].split(":"); String itemID = vector[0]; //物品ID String pref = vector[1];//评分 Text k = new Text(itemID); Text v = new Text("B:"+userID+","+pref); context.write(k, v); } } } } //本reduce 负责累加结果 static class Step5_Reducer extends Reducer<Text, Text, Text, Text>{ protected void reduce(Text key, Iterable<Text>values, Context context) throws IOException,InterruptedException{ //其他物品ID为map的key,同现数字为值 Map<String, Double> mapA = new HashMap<String,Double>(); //该物品(key中的itemID),所有用户的推荐权重分数 Map<String, Integer>mapB = new HashMap<String,Integer>(); for(Text line : values) { String val = line.toString(); if(val.startsWith("A:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); String tokens = kv[1]; String itemID = kv[0];//物品id Double score = Double.parseDouble(tokens); //相乘结果 //相加计算 if(mapA.containsKey(itemID)) { mapA.put(itemID, mapA.get(itemID)+score); }else { mapA.put(itemID, score); } }else if(val.startsWith("B:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); try { mapB.put(kv[0], Integer.parseInt(kv[1])); }catch(Exception e) { e.printStackTrace(); } } } Iterator<String> iter = mapA.keySet().iterator(); while(iter.hasNext()) { String itemID = iter.next(); double score = mapA.get(itemID); Text v = new Text(itemID+","+score); Iterator<String>iterb = mapB.keySet().iterator(); while(iterb.hasNext()) { String mapkb = iterb.next(); Text k = new Text(mapkb); if(k.equals(key)) { continue; }else { context.write(key, v); } } } } } } ``` step4和step5配置 ![图片说明](https://img-ask.csdn.net/upload/201804/25/1524617462_994374.png) step4,在for循环中同时出现A和B ![step4,在for循环中同时出现A和B](https://img-ask.csdn.net/upload/201804/25/1524616391_511813.png) step5中,A和B无法出现在同一次循环 ![有A没B,此时mapB是无法点击开的](https://img-ask.csdn.net/upload/201804/25/1524616746_557066.png) 直接跳出了for循环进入下面的while循环,此时没有mapB,while无法正常进行 ![跳出了for循环](https://img-ask.csdn.net/upload/201804/25/1524616866_908151.png) 进行了多次step5后,输出完所有mapA之后,在下一次step5才进入mapB,此时轮到mapA是空的,而只有mapB ![mapA是空的,只有mapB](https://img-ask.csdn.net/upload/201804/25/1524617121_817431.png)

请教大神如下代码里那部分设置了最后的目标状态,也就是最后的结果是那部分控制的

#include <iostream> #include <vector> #include <algorithm> #include <list> #include <queue> #include <unordered_map> #include <string> #include <sstream> #include <stdexcept> #include <memory> #include <Windows.h> using namespace std; class Board; class Solver; class Board { friend class Solver; friend class compare_node; public: typedef enum { TL_SPACE, TL_1, TL_2, TL_3, TL_4, TL_5, TL_6, TL_7, TL_8, }TILE; Board() { for (int i = 0; i != 8; tiles.push_back(TILE(++i))); tiles.push_back(TL_SPACE); } Board(int t[3][3]) { for (int i = 0; i != 3; ++i) for (int j = 0; j != 3; ++j) tiles.push_back(TILE(t[i][j])); } int hamming() { int count = 0; for (int i = 0; i != tiles.size(); ++i) if (tiles[i] != TILE((i + 1)) && tiles[i] != TL_SPACE) ++count; return count; } int manhattan() { int count = 0; int num; for (int i = 0; i != tiles.size(); ++i) { if (tiles[i] == TL_SPACE) continue; num = (tiles[i] + 8) % 9; count = count + (abs(num / 3 - i / 3) + abs(num % 3 - i % 3)); } return count; } bool equals(const Board &b) const { bool ret = true; for (int i = 0; i != b.tiles.size(); ++i) { if (this->tiles[i] != b.tiles[i]) { ret = false; break; } } return ret; } void neighbors(vector<Board> &nghbrs) { nghbrs.clear(); int pos = 0; for (; pos != tiles.size() && tiles[pos] != TL_SPACE; ++pos); int row = pos / 3; int col = pos % 3; if (row > 0) { nghbrs.push_back(*this); nghbrs.back().swap(pos, (row - 1) * 3 + col); } if (row < 2) { nghbrs.push_back(*this); nghbrs.back().swap(pos, (row + 1) * 3 + col); } if (col > 0) { nghbrs.push_back(*this); nghbrs.back().swap(pos, row * 3 + col - 1); } if (col < 2) { nghbrs.push_back(*this); nghbrs.back().swap(pos, row * 3 + col + 1); } } string toString() { string s; ostringstream convert; for (int i = 0; i != tiles.size(); ++i) convert << static_cast<int>(tiles[i]) << " "; s = convert.str(); return s; } private: vector<TILE> tiles; Board *parent = nullptr; int f = 0; int g = 0; int h = 0; void swap(size_t pos1, size_t pos2) { if (pos1 >= tiles.size() || pos2 >= tiles.size()) throw runtime_error("position not match"); std::swap(tiles[pos1], tiles[pos2]); } }; // function used to compared board in heap class compare_node { public: bool operator()(Board *&l, Board *&r) { return l->f > r->f; } }; // vector for board pointers class bvector : public vector<Board*> { public: bvector() { make_heap(this->begin(), this->end(), compare_node()); } void push_node(Board *b) { this->push_back(b); push_heap(this->begin(), this->end(), compare_node()); } void pop_node() { pop_heap(this->begin(), this->end(), compare_node()); this->pop_back(); } }; class Solver { friend class Board; public: Solver() = default; Solver(Board *p) : initial(p) {} void init() { if (initial == nullptr) { cerr << "Solver not initialized" << endl; return; } if (!isSolvable()) { cerr << "No solution existed" << endl; return; } initial->g = 0; initial->h = initial->manhattan() + initial->hamming(); initial->f = initial->g + initial->h; open_ref[initial->toString()] = initial; open_set.push_node(initial); while (!open_set.empty()) { Board *closed_node = open_set.front(); open_ref.erase(closed_node->toString()); closed_ref[closed_node->toString()] = closed_node; open_set.pop_node(); if (closed_node->equals(*end)) { Board *p = closed_node; while (p->parent != nullptr) { solution.push_back(p->toString()); p = p->parent; } solution.push_back(initial->toString()); reverse(solution.begin(), solution.end()); return; } vector<Board> neighbors; closed_node->neighbors(neighbors); for (auto iter = neighbors.begin(); iter != neighbors.end(); ++iter) { Board *new_node = new Board(*iter); new_node->g = 0; new_node->h = new_node->manhattan() + new_node->hamming(); new_node->f = new_node->f + new_node->h; // ignore the neighbor which is already evaluated. if (closed_ref.find(new_node->toString()) != closed_ref.end()) { delete new_node; continue; } if (open_ref.find(new_node->toString()) != open_ref.end()) { delete new_node; continue; } new_node->parent = closed_node; open_set.push_node(new_node); open_ref[new_node->toString()] = new_node; } } return; } vector<string> getSolution() { return solution; } // http://www.geeksforgeeks.org/check-instance-8-puzzle-solvable/ // It is not possible to solve an instance of 8 puzzle if the number of inversions is odd // in the initial state bool isSolvable() { int count = 0; for (int i = 0; i != initial->tiles.size(); ++i) for (int j = i + 1; j != initial->tiles.size(); ++j) if (initial->tiles[i] != Board::TILE::TL_SPACE && initial->tiles[j] != Board::TILE::TL_SPACE && static_cast<int>(initial->tiles[i]) > static_cast<int>(initial->tiles[j])) ++count; return (count % 2 == 0); } ~Solver() { delete initial; delete end; for (auto iter = open_ref.begin(); iter != open_ref.end(); ++iter) delete iter->second; for (auto iter = closed_ref.begin(); iter != closed_ref.end(); ++iter) delete iter->second; } private: Board *initial = nullptr; Board *end = new Board(); bvector open_set; unordered_map<string, Board*> open_ref; unordered_map<string, Board*> closed_ref; vector<string> solution; }; int main() { int t1[3][3] = { { 1, 2, 3 },{ 4, 5, 6 },{ 8, 7, 0 } }; int t2[3][3] = { { 8, 1, 3 },{ 4, 0, 2 },{ 7, 6, 5 } }; Board *b1 = new Board(t1); Board *b2 = new Board(t2); Solver s1(b1); Solver s2(b2); s1.init(); s2.init(); auto ret2 = s2.getSolution(); cout << "The solution to " << b1->toString() << endl; for (auto str : ret2) cout << str << endl; system("PAUSE"); return 0; }

Hadoop 基于物品的协同过滤算法 从结果中去除用户已经评论过的数据

最近在弄这个算法时,发现网上的大多数教程对于 “从结果中去除用户已经评论过的数据”都只是提出,却没有实现,因此在最后推荐结果会出现用户已经评论过的数据。在自己实现时遇到了问题。以下step6是“从结果中去除用户已经评论过的数据”内容 ``` import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import org.apache.commons.net.telnet.EchoOptionHandler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Mapper.Context; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter; //获得结果矩阵 public class Step6 { public static boolean run(Configuration con, Map<String, String>map) { try { FileSystem fs = FileSystem.get(con); Job job = Job.getInstance(); job.setJobName("step6"); job.setJarByClass(App.class); job.setMapperClass(Step6_Mapper.class); job.setReducerClass(Step6_Reducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path[] { new Path(map.get("Step6Input1")), new Path(map.get("Step6Input2")) }); Path outpath = new Path(map.get("Step6Output")); if(fs.exists(outpath)){ fs.delete(outpath,true); } FileOutputFormat.setOutputPath(job, outpath); boolean f = job.waitForCompletion(true); return f; }catch(Exception e) { e.printStackTrace(); } return false; } static class Step6_Mapper extends Mapper<LongWritable, Text, Text, Text>{ private String flag; //每次map时都会先判断一次 @Override protected void setup(Context context )throws IOException,InterruptedException{ FileSplit split = (FileSplit) context.getInputSplit(); flag = split.getPath().getParent().getName(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ String[] tokens = Pattern.compile("[\t,]").split(value.toString()); if(flag.equals("step5")) { String userID = tokens[0]; Text itemID = new Text(tokens[1]); //tokens[1] 物品id tokens[2] 用户对物品评分 Text v = new Text("A:"+userID+","+tokens[1]+","+tokens[2]); //输出key为itemID context.write(itemID, v); }else if(flag.equals("step2")) {//用户评价矩阵 // u2 i1:2,i3:4 String userID = tokens[0]; for(int i=1;i<tokens.length;i++) { String[] vector = tokens[i].split(":"); String itemID = vector[0]; //物品ID // String pref = vector[1];//评分 Text k = new Text(itemID); Text v = new Text("B:"+userID+","+itemID); //输出key万为itemid context.write(k, v); } } } } static class Step6_Reducer extends Reducer<Text, Text, Text, Text>{ protected void reduce(Text key, Iterable<Text>values, Context context) throws IOException,InterruptedException{ //物品ID为map的key Map<String, String> mapA = new HashMap<String,String>(); //该物品(key中的itemID) Map<String, Integer>mapB = new HashMap<String,Integer>(); for(Text line : values) { String val = line.toString(); if(val.startsWith("A:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); String userID = kv[0];//用户ID String tokens = kv[2];//用户的对物品评分 String itemID = kv[1];//物品ID mapA.put(userID, itemID+","+tokens); }else if(val.startsWith("B:")) { String[] kv = Pattern.compile("[\t,]").split(val.substring(2)); //kv[0] = userID //kv[1] = itemID //kv[2] = price try { mapB.put(kv[0], Integer.parseInt(kv[1])); }catch(Exception e) { e.printStackTrace(); } } } Iterator<String> itera = mapA.keySet().iterator(); while(itera.hasNext()) { String userID = itera.next(); String score = mapA.get(userID); String[] kv = score.toString().split(","); Text v = new Text(kv[0]+","+kv[1]); Iterator<String>iterb = mapB.keySet().iterator(); while(iterb.hasNext()) { String mapkb = iterb.next();//用户ID String itemID = Integer.toString(mapB.get(mapkb));//物品ID //Text k = new Text(mapkb); //去除用户已评论过的数据 if(mapkb.equals(userID)&&itemID.equals(kv[0])) { continue; }else { Text ke = new Text(mapkb); context.write(ke, v); } } } } } ``` 其中step2的数据为 ![图片说明](https://img-ask.csdn.net/upload/201804/29/1525011667_546507.png) step5数据为 ![图片说明](https://img-ask.csdn.net/upload/201804/29/1525011891_562052.png) 按照自己写的step6的输出数据为 ![图片说明](https://img-ask.csdn.net/upload/201804/29/1525011910_722119.png) 显然数据中出现了许多重复数据。实在不了解怎么弄了,请各位提供个思路,或者帮看下哪里有问题。

DLL采用运行时库MDD提示出现内存泄漏,采用MTD不会出现内存泄漏

我编写了一个DLL,DLL中导出来了一个类,类里面定义了一个vector以及map,然后用exe去调用DLL,当DLL的运行时库使用MTD时,vs2010就不会报内存泄漏;DLL的运行时库使用MDD时,vs2010就会出现内存泄漏;另外,很奇怪的是,当DLL的运行时库使用MDD,exe调用DLL时,连接加载对应的DLL的lib,采用在代码中#pragma comment(lib,"../Debug/MemoryLeakDemo.lib")形式时,vs就不会提示内存泄漏,而在vs工程中的配置选项中连接的形式,就会提示出现内存泄漏; DLL中的代码: IncludeInc.h #pragma once #ifdef MEMORYLEAKDEMO_EXPORTS #define MEMORYLEAKDEMO_EXPORTS _declspec(dllexport) #else #define MEMORYLEAKDEMO_EXPORTS _declspec(dllimport) #endif #include "ITestDemo.h" MEMORYLEAKDEMO_EXPORTS ITestDemo* OPenSkinRes(); IncludeInc.cpp的代码: #include "IncludeInc.h" #include "TestDemo.h" MEMORYLEAKDEMO_EXPORTS ITestDemo* OPenSkinRes(){ ITestDemo* pTemp = CTestDemo::GetInstance(); return pTemp; } ITestDemo.h代码 #pragma once class ITestDemo{ public: virtual int GetUI() = 0; }; TestDemo.h中代码 #include "ITestDemo.h" #include <string> #include <vector> class CTestDemo :public ITestDemo { public: static CTestDemo* GetInstance(){ static CTestDemo g_res; return &g_res; } virtual int GetUI(); private: CTestDemo(void); ~CTestDemo(void); public: static int s_sDemo1; static std::string s_strDemo2; private: std::vector<int *> m_vecDynamic; std::vector<CTestDemo*> m_vecTest; }; TestDemo.cpp代码: #include "StdAfx.h" #include "TestDemo.h" int CTestDemo::s_sDemo1 =0; std::string CTestDemo::s_strDemo2 = "Test"; CTestDemo::CTestDemo(void) { for (int i = 0; i < 100 ; i++) { m_vecDynamic.push_back(new int(i)); } } CTestDemo::~CTestDemo(void) { std::vector<int*>::iterator it = m_vecDynamic.begin(); for (; it != m_vecDynamic.end(); ++it) { int * pTemp = *it; delete pTemp; } } int CTestDemo::GetUI(){ return 1; } exe中的代码: // CallMemoryLeak.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "CallMemoryLeak.h" #include "CallMemoryLeakDlg.h" #include "../MemoryLeakDemo/IncludeInc.h" #include "../MemoryLeakDemo/ITestDemo.h" #ifdef _DEBUG #define new DEBUG_NEW #endif //#pragma comment(lib,"../Debug/MemoryLeakDemo.lib") // CCallMemoryLeakApp BEGIN_MESSAGE_MAP(CCallMemoryLeakApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CCallMemoryLeakApp construction CCallMemoryLeakApp::CCallMemoryLeakApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CCallMemoryLeakApp object CCallMemoryLeakApp theApp; // CCallMemoryLeakApp initialization BOOL CCallMemoryLeakApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); //就这两行调用代码,其他的都是MFC默认生成的 ITestDemo* pTeset = OPenSkinRes(); int iRet = pTeset->GetUI(); CCallMemoryLeakDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }

为什么我看了这个关于高校人员信息管理系统设计的代码运行时总是会说找不到“common.h”这个文件,这个那里有错误呢?

#ifndef COMMON_H_INCLUDED #define COMMON_H_INCLUDED #include<string> #include<iostream> #include<iomanip> class COMMON { protected: std::string name; bool sex; int age; std::string id; static int person_sum; static int man_sum; static int woman_sum; public: COMMON(std::string a, bool b, int c, std::string d); virtual ~COMMON(); static int get_person_sum(); static int get_man_sum(); static int get_woman_sum(); virtual void show(){} virtual void show_row(){} virtual bool change(){} std::string get_name(){return name;} bool get_sex(){return sex;} int get_age(){return age;} std::string get_id(){return id;} }; int COMMON::person_sum = 0; int COMMON::man_sum = 0; int COMMON::woman_sum = 0; int COMMON::get_person_sum() { return person_sum; } int COMMON::get_man_sum() { return man_sum; } int COMMON::get_woman_sum() { return woman_sum; } COMMON::COMMON(std::string a, bool b, int c, std::string d): name(a), sex(b), age(c), id(d) { person_sum++; if(b) man_sum++; else woman_sum++; } COMMON::~COMMON() { person_sum--; if(sex) man_sum--; else woman_sum--; } #endif // COMMON_H_INCLUDED tester.h 实验员: #ifndef TESTER_H_INCLUDED #define TESTER_H_INCLUDED #include"common.h" class TESTER: public COMMON { private: std::string laboratory; std::string title; static int tester_sum; public: TESTER(std::string a = "haha", bool b = 1, int c = 19, std::string d = "1", std::string e = "tt", std::string f = "学生"); ~TESTER(); static int get_tester_sum(); virtual void show(); virtual void show_row(); virtual bool change(); std::string get_laboratory(){return laboratory;} std::string get_title(){return title;} }; int TESTER::tester_sum = 0; int TESTER::get_tester_sum() { return tester_sum; } TESTER::TESTER(std::string a, bool b, int c, std::string d, std::string e, std::string f): COMMON(a,b,c,d), laboratory(e), title(f) { tester_sum++; } TESTER::~TESTER() { tester_sum--; } void TESTER::show() { std::cout << "实验员:\n"; std::cout << "姓名:\t\t" << name << std::endl; std::cout << "姓别:\t\t"; if(sex) std::cout << "男\n"; else std::cout << "女\n"; std::cout << "年龄:\t\t" << age << std::endl; std::cout << "ID:\t\t" << id << std::endl; std::cout << "所属实验室:\t" << laboratory << std::endl; std::cout << "职务:\t\t" << title << std::endl; } void TESTER::show_row() { std::cout << std::left << std::setw(8) << name; if(sex) std::cout << std::left << std::setw(8) << "男"; else std::cout << std::left << std::setw(8) << "女"; std::cout << std::left << std::setw(8) << age; std::cout << std::left << std::setw(16) << id; std::cout << std::left << std::setw(16) << laboratory; std::cout << std::left << std::setw(16) << title; std::cout << std::endl; } bool TESTER::change() { std::cout << "姓名:\t\t" ; std::string new_name; std::cin >> new_name; for(unsigned int i = 0; i < new_name.length(); i++) { if(new_name[i] >= '0' && new_name[i] <= '9') { std::cout << "输入非法,输入任意键返回\n"; return 1; } } name = new_name; std::cout << "姓别:\t\t"; std::string a; std::cin >> a; if(sex) man_sum--; else woman_sum--; if(a == "男") sex = 1, man_sum++; else sex = 0, woman_sum++; std::cout << "年龄:\t\t"; std::cin >> age; std::cout << "所属实验室:\t"; std::cin >> laboratory; std::cout << "职务:\t\t"; std::cin >> title; return 0; } #endif // TESTER_H_INCLUDED teacher.h 教师: #ifndef TEACHER_H_INCLUDED #define TEACHER_H_INCLUDED #include"common.h" class TEACHER: virtual public COMMON { protected: std::string department; std::string profession; std::string title; static int teacher_sum; public: TEACHER(std::string a = "xixi", bool b = 1, int c = 30, std::string d = "213", std::string e = "计算机与信息工程学院", std::string f = "计算机科学与技术", std::string g = "教师"); ~TEACHER(); static int get_teacher_sum(); virtual void show(); virtual void show_row(); virtual bool change(); std::string get_department(){return department;} std::string get_profession(){return profession;} std::string get_title(){return title;} }; int TEACHER::teacher_sum = 0; int TEACHER::get_teacher_sum() { return teacher_sum; } TEACHER::TEACHER(std::string a, bool b, int c, std::string d, std::string e, std::string f, std::string g): COMMON(a,b,c,d), department(e), profession(f), title(g) { teacher_sum++; } TEACHER::~TEACHER() { teacher_sum--; } void TEACHER::show() { std::cout << "教师:\n"; std::cout << "姓名:\t\t" << name << std::endl; std::cout << "姓别:\t\t"; if(sex) std::cout << "男\n"; else std::cout << "女\n"; std::cout << "年龄:\t\t" << age << std::endl; std::cout << "ID:\t\t" << id << std::endl; std::cout << "院系:\t\t" << department << std::endl; std::cout << "专业:\t\t" << profession << std::endl; std::cout << "职务:\t\t" << title << std::endl; } void TEACHER::show_row() { std::cout << std::left << std::setw(8) << name; if(sex) std::cout << std::left << std::setw(8) << "男"; else std::cout << std::left << std::setw(8) << "女"; std::cout << std::left << std::setw(8) << age; std::cout << std::left << std::setw(16) << id; std::cout << std::left << std::setw(16) << department; std::cout << std::left << std::setw(16) << profession; std::cout << std::left << std::setw(16) << title; std::cout << std::endl; } bool TEACHER::change() { std::cout << "姓名:\t\t" ; std::string new_name; std::cin >> new_name; for(unsigned int i = 0; i < new_name.length(); i++) { if(new_name[i] >= '0' && new_name[i] <= '9') { std::cout << "输入非法,输入任意键返回\n"; return 1; } } name = new_name; std::cout << "姓别:\t\t"; std::string a; std::cin >> a; if(sex) man_sum--; else woman_sum--; if(a == "男") sex = 1, man_sum++; else sex = 0, woman_sum++; std::cout << "年龄:\t\t"; std::cin >> age; std::cout << "院系:\t\t"; std::cin >> department; std::cout << "专业:\t\t"; std::cin >> profession; std::cout << "职务:\t\t"; std::cin >> title; return 0; } #endif // TEACHER_H_INCLUDED administrator.h 行政人员: #ifndef ADMINISTRATOR_H_INCLUDED #define ADMINISTRATOR_H_INCLUDED #include"common.h" class ADMINISTRATOR: virtual public COMMON { protected: std::string politics; std::string position; static int administrator_sum; public: ADMINISTRATOR(std::string a = "huhu", bool b = 1, int c = 39, std::string d = "176", std::string e = "群众", std:: string f = "社会主义新青年"); ~ADMINISTRATOR(); static int get_administrator_sum(); virtual void show(); virtual void show_row(); virtual bool change(); std::string get_politics(){return politics;} std::string get_position(){return position;} }; int ADMINISTRATOR::administrator_sum = 0; int ADMINISTRATOR::get_administrator_sum() { return administrator_sum; } ADMINISTRATOR::ADMINISTRATOR(std::string a, bool b, int c, std::string d, std::string e, std::string f): COMMON(a,b,c,d), politics(e), position(f) { administrator_sum++; } ADMINISTRATOR::~ADMINISTRATOR() { administrator_sum--; } void ADMINISTRATOR::show() { std::cout << "行政人员:\n"; std::cout << "姓名:\t\t" << name << std::endl; std::cout << "姓别:\t\t"; if(sex) std::cout << "男\n"; else std::cout << "女\n"; std::cout << "年龄:\t\t" << age << std::endl; std::cout << "ID:\t\t" << id << std::endl; std::cout << "政治面貌:\t" << politics << std::endl; std::cout << "职称:\t\t" << position << std::endl; } void ADMINISTRATOR::show_row() { std::cout << std::left << std::setw(8) << name; if(sex) std::cout << std::left << std::setw(8) << "男"; else std::cout << std::left << std::setw(8) << "女"; std::cout << std::left << std::setw(8) << age; std::cout << std::left << std::setw(16) << id; std::cout << std::left << std::setw(16) << politics; std::cout << std::left << std::setw(16) << position; std::cout << std::endl; } bool ADMINISTRATOR::change() { std::cout << "姓名:\t\t" ; std::string new_name; std::cin >> new_name; for(unsigned int i = 0; i < new_name.length(); i++) { if(new_name[i] >= '0' && new_name[i] <= '9') { std::cout << "输入非法,输入任意键返回\n"; return 1; } } name = new_name; std::cout << "姓别:\t\t"; std::string a; std::cin >> a; if(sex) man_sum--; else woman_sum--; if(a == "男") sex = 1, man_sum++; else sex = 0, woman_sum++; std::cout << "年龄:\t\t"; std::cin >> age; std::cout << "政治面貌:\t"; std::cin >> politics; std::cout << "职称:\t\t"; std::cin >> position; return 0; } #endif // ADMINISTRATOR_H_INCLUDED tea&admi.h 教师及行政人员: #ifndef TEAADMI_H_INCLUDED #define TEAADMI_H_INCLUDED #include"teacher.h" #include"administrator.h" class TEAADMI: public TEACHER, public ADMINISTRATOR { private: static int teaadmi_sum; public: TEAADMI(std::string a = "maomao", bool b = 1, int c = 59, std::string d = "0", std::string e = "计算机与信息工程学院", std::string f = "计算机科学与技术", std::string g = "教师", std::string h = "群众", std:: string i = "社会主义新青年"); ~TEAADMI(); static int get_teaadmi_sum(); virtual void show(); virtual void show_row(); virtual bool change(); }; int TEAADMI::teaadmi_sum = 0; int TEAADMI::get_teaadmi_sum() { return teaadmi_sum; } TEAADMI::TEAADMI(std::string a, bool b, int c, std::string d, std::string e, std::string f, std::string g, std::string h, std::string i): COMMON(a,b,c,d), TEACHER(a,b,c,d,e,f,g), ADMINISTRATOR(a,b,c,d,h,i) { teaadmi_sum++; } TEAADMI::~TEAADMI() { teaadmi_sum--; } void TEAADMI::show() { std::cout << "教师及行政人员:\n"; std::cout << "姓名:\t\t" << name << std::endl; std::cout << "姓别:\t\t"; if(sex) std::cout << "男\n"; else std::cout << "女\n"; std::cout << "年龄:\t\t" << age << std::endl; std::cout << "ID:\t\t" << id << std::endl; std::cout << "院系:\t\t" << department << std::endl; std::cout << "专业:\t\t" << profession << std::endl; std::cout << "职务:\t\t" << title << std::endl; std::cout << "政治面貌:\t" << politics << std::endl; std::cout << "职称:\t\t" << position << std::endl; } void TEAADMI::show_row() { std::cout << std::left << std::setw(8) << name; if(sex) std::cout << std::left << std::setw(8) << "男"; else std::cout << std::left << std::setw(8) << "女"; std::cout << std::left << std::setw(8) << age; std::cout << std::left << std::setw(16) << id; std::cout << std::left << std::setw(16) << department; std::cout << std::left << std::setw(16) << profession; std::cout << std::left << std::setw(16) << title; std::cout << std::left << std::setw(16) << politics; std::cout << std::left << std::setw(16) << position; std::cout << std::endl; } bool TEAADMI::change() { std::cout << "姓名:\t\t" ; std::string new_name; std::cin >> new_name; for(unsigned int i = 0; i < new_name.length(); i++) { if(new_name[i] >= '0' && new_name[i] <= '9') { std::cout << "输入非法,输入任意键返回\n"; return 1; } } name = new_name; std::cout << "姓别:\t\t"; std::string a; std::cin >> a; if(sex) man_sum--; else woman_sum--; if(a == "男") sex = 1, man_sum++; else sex = 0, woman_sum++; std::cout << "年龄:\t\t"; std::cin >> age; std::cout << "院系:\t\t"; std::cin >> department; std::cout << "专业:\t\t"; std::cin >> profession; std::cout << "职务:\t\t"; std::cin >> title; std::cout << "政治面貌:\t"; std::cin >> politics; std::cout << "职称:\t\t"; std::cin >> position; return 0; } #endif // TEA&ADMI_H_INCLUDED interface.h 界面: #ifndef INTERFACE_H_INCLUDED #define INTERFACE_H_INCLUDED #include"teacher.h" #include"tester.h" #include"administrator.h" #include"tea&admi.h" #include<stdio.h> #include<stdlib.h> #include<conio.h> /*----------------函数声明-------------------*/ void interface_login(); //初始界面 void interface_Manager(); //管理者界面 void staff_list(); //管理者清单 #include"myfun.h" /*----------------函数定义-------------------*/ void interface_Manager() //管理界面 { int n=1; while(n) { system("cls"); std::cout << "------------欢迎来到只有神知道的领域 o(*≧▽≦)ツ----------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "------------- 输入1 添加信息 -------------\n"; std::cout << "------------- 输入2 查询信息 -------------\n"; std::cout << "------------- 输入3 浏览信息 -------------\n"; std::cout << "------------- 输入4 修改信息 -------------\n"; std::cout << "------------- 输入5 删除信息 -------------\n"; std::cout << "------------- 输入6 统计信息 -------------\n"; std::cout << "------------- 输入0 返回上一级 -------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cin >> n; switch(n) { case 1:Add_information();break; case 2: { int a = 1; if(!Query_information()) break; while(a) { std::cout << "输入1 修改信息\n"; std::cout << "输入2 删除信息\n"; std::cout << "输入0 返回上一级\n"; std::cin >> a; switch(a) { case 1:Edit_information(); a = 0; break; case 2:Delete_information(); a= 0; break; } } break; } case 3: { int a=1; while(a) { Browse_information(); std::cout << "输入1 修改信息\n"; std::cout << "输入2 删除信息\n"; std::cout << "输入0 返回上一级\n"; std::cin >> a; switch(a) { case 1:Edit_information(); break; case 2:Delete_information(); break; } } break; } case 4:Edit_information(); break; case 5:Delete_information(); break; case 6:count_information(); break; } } } void interface_login() //登入界面 { int n=1; while(n) { system("cls"); std::cout << "----------欢迎进入高校人员信息管理系统 o(*≧▽≦)ツ--------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "------------- 输入1 管理员账号登入 -------------\n"; std::cout << "------------- 输入2 查询信息 -------------\n"; std::cout << "------------- 输入3 浏览信息 -------------\n"; std::cout << "------------- 输入4 统计信息 -------------\n"; std::cout << "------------- 输入5 观看制作信息 -------------\n"; std::cout << "------------- 输入0 关闭系统 -------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cin >> n; switch(n) { case 1:login(); break; case 2:if(Query_information()) std::cout << "输入任意键,返回上一级\n", getch(); break; case 3:Browse_information(); std::cout << "输入任意键,返回上一级\n"; getch(); break; case 4:count_information(); break; case 5:staff_list(); break; } } } void staff_list() //制作人员名单 { system("cls"); std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "--------------Include the following members----------------\n"; std::cout << "-------------- wzy ----------------\n"; std::cout << "-------------- ToRe ----------------\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-----------------------------------------------------------\n\n\n"; std::cout << "\n输入任意键返回主菜单…\n"; getch(); } #endif // INTERFACE_H_INCLUDED myfun.h 主要功能实现: #ifndef MYFUN_H_INCLUDED #define MYFUN_H_INCLUDED #include<vector> #include<map> #include<fstream> /*----------------成员声明-------------------*/ std::multimap<std::string, COMMON *> sear; std::vector<TESTER*> tester; std::vector<TEACHER*> teacher; std::vector<ADMINISTRATOR*> administrator; std::vector<TEAADMI*> teaadmi; /*----------------函数声明-------------------*/ void Information_load(); //信息加载 void room_delete(); //释放空间 void login(); //登入函数 void Add_information(); //添加信息 bool Query_information(); //显示查询信息 void Browse_information(); //浏览信息 void Edit_information(); //修改信息 void Delete_information(); //删除信息 void count_information(); //统计信息 /*----------------函数定义-------------------*/ void Information_load() //信息加载 { std::ifstream in; in.open("实验员.txt", std::ios::in); std::string name, id; int age; bool sex; while(in >> name) { std::string laboratory, title; in >> sex >> age >> id >> laboratory >> title; TESTER *t = new TESTER(name,sex,age,id,laboratory,title); tester.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); } in.close(); in.open("教师.txt", std::ios::in); while(in >> name) { std::string department, profession, title; in >> sex >> age >> id >> department >> profession >> title; TEACHER *t = new TEACHER(name,sex,age,id,department,profession,title); teacher.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); } in.close(); in.open("行政人员.txt", std::ios::in); while(in >> name) { std::string politics, position; in >> sex >> age >> id >> politics >> position; ADMINISTRATOR *t = new ADMINISTRATOR(name,sex,age,id,politics,position); administrator.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); } in.close(); in.open("教师&行政人员.txt", std::ios::in); while(in >> name) { std::string department, profession, title, politics, position; in >> sex >> age >> id >> department >> profession >> title >> politics >> position; TEAADMI *t = new TEAADMI(name,sex,age,id,department,profession,title,politics,position); teaadmi.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); } } void room_delete() //释放空间 { for(auto iter:tester) delete iter; for(auto iter:teacher) delete iter; for(auto iter:administrator) delete iter; for(auto iter:teaadmi) delete iter; } void login() //登入函数 { std::string com; system("cls"); std::cout << "请输入密码\n"; getchar(); std::getline(std::cin,com); if(com == "bokuwasinnsekainokamitonaru") interface_Manager(); else { std::cout << "密码错误,输入任意键返回上一级\n"; getch(); } } void Add_information()//添加信息 { system("cls"); std::cout << "请输入添加类型\n1:实验员\t2:教师\t\t3:行政人员\t4:教师及行政人员\n"; int flag; std::cin >> flag; std::string name, se, id; int age; bool sex = 0; std::cout << "ID:\t\t"; std::cin >> id; for(unsigned int i = 0; i < id.length(); i++) { if(id[i] < '0' || id[i] > '9') { std::cout << "输入非法,输入任意键返回\n"; getch(); return; } } std::multimap<std::string, COMMON *>::iterator beg, en; beg = sear.lower_bound(id); en = sear.upper_bound(id); if(beg != en) { std::cout << "此ID已存在,输入任意键返回\n"; getch(); return; } std::cout << "姓名:\t\t"; std::cin >> name; for(unsigned int i = 0; i < name.length(); i++) { if(name[i] >= '0' && name[i] <= '9') { std::cout << "输入非法,输入任意键返回\n"; getch(); return; } } std::cout << "性别:\t\t"; std::cin >> se; if(se == "男") sex = 1; std::cout << "年龄:\t\t"; std::cin >> age; if(flag == 1) { std::string laboratory, title; std::cout << "实验室名称:\t"; std::cin >> laboratory; std::cout << "职务:\t\t"; std::cin >> title; TESTER *t = new TESTER(name,sex,age,id,laboratory,title); tester.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); std::ofstream out; out.open("实验员.txt", std::ios::app); out << name << " " << sex << " " << age << " " << id << " "; out << laboratory << " " << title << std::endl; out.close(); } if(flag == 2) { std::string department, profession, title; std::cout << "院系:\t\t"; std::cin >> department; std::cout << "专业:\t\t"; std::cin >> profession; std::cout << "职务:\t\t"; std::cin >> title; TEACHER *t = new TEACHER(name,sex,age,id,department,profession,title); teacher.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); std::ofstream out; out.open("教师.txt", std::ios::app); out << name << " " << sex << " " << age << " " << id << " "; out << department << " " << profession << " " << title << std::endl; out.close(); } if(flag == 3) { std::string politics, position; std::cout << "政治面貌:\t"; std::cin >> politics; std::cout << "职称:\t\t"; std::cin >> position; ADMINISTRATOR *t = new ADMINISTRATOR(name,sex,age,id,politics,position); administrator.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); std::ofstream out; out.open("行政人员.txt", std::ios::app); out << name << " " << sex << " " << age << " " << id << " "; out << politics << " " << position << std::endl; out.close(); } if(flag == 4) { std::string department, profession, title, politics, position; std::cout << "院系:\t\t"; std::cin >> department; std::cout << "专业:\t\t"; std::cin >> profession; std::cout << "职务:\t\t"; std::cin >> title; std::cout << "政治面貌:\t"; std::cin >> politics; std::cout << "职称:\t\t"; std::cin >> position; TEAADMI *t = new TEAADMI(name,sex,age,id,department,profession,title,politics,position); teaadmi.push_back(t); sear.insert(make_pair(name, t)); sear.insert(make_pair(id, t)); std::ofstream out; out.open("教师&行政人员.txt", std::ios::app); out << name << " " << sex << " " << age << " " << id << " "; out << department << " " << profession << " " << title << " "; out << politics << " " << position << std::endl; out.close(); } std::cout << "注册成功,输入任意键返回\n"; getch(); } void Delete_information() //删除信息 { std::cout << "输入目标ID以确认\n"; std::string aid; std::cin >> aid; for(unsigned int i = 0; i < aid.length(); i++) { if(aid[i] < '0' || aid[i] > '9') { std::cout << "输入非法,输入任意键返回\n"; getch(); return; } } std::multimap<std::string, COMMON *>::iterator beg, en, iter; beg = sear.lower_bound(aid); en = sear.upper_bound(aid); if(beg == en) { std::cout << "目标不存在,输入任意键返回\n"; getch(); return; } std::string aid_name = beg -> second -> get_name(); sear.erase(beg); beg = sear.lower_bound(aid_name); en = sear.upper_bound(aid_name); for(iter = beg; iter != en; ++iter) if(iter -> second -> get_id() == aid) {sear.erase(iter); break;} bool flag = 0; std::ofstream out; out.open("实验员.txt", std::ios::out); for(std::vector<TESTER*>::iterator it = tester.begin(); it != tester.end();) { if((*it) -> get_id() == aid){flag = 1; delete (*it); it = tester.erase(it); continue;} out << (*it) -> get_name() << " " << (*it) -> get_sex() << " "; out << (*it) -> get_age() << " " << (*it) -> get_id() << " "; out << (*it) -> get_laboratory() << " " << (*it) -> get_title() << std::endl; ++it; } out.close(); if(flag) {std::cout << "删除成功,输入任意键返回\n"; getch(); return;} out.open("教师.txt", std::ios::out); for(std::vector<TEACHER*>::iterator it = teacher.begin(); it != teacher.end();) { if((*it) -> get_id() == aid){flag = 1; delete (*it); it = teacher.erase(it); continue;} out << (*it) -> get_name() << " " << (*it) -> get_sex() << " "; out << (*it) -> get_age() << " " << (*it) -> get_id() << " "; out << (*it) -> get_department() << " " << (*it) -> get_profession() << " " << (*it) -> get_title() << std::endl; it++; } out.close(); if(flag) {std::cout << "删除成功,输入任意键返回\n"; getch(); return;} out.open("行政人员.txt", std::ios::out); for(std::vector<ADMINISTRATOR*>::iterator it = administrator.begin(); it != administrator.end();) { if((*it) -> get_id() == aid){flag = 1; delete (*it); it = administrator.erase(it); continue;} out << (*it) -> get_name() << " " << (*it) -> get_sex() << " "; out << (*it) -> get_age() << " " << (*it) -> get_id() << " "; out << (*it) -> get_politics() << " " << (*it) -> get_position() << std::endl; it++; } out.close(); if(flag) {std::cout << "删除成功,输入任意键返回\n"; getch(); return;} out.open("教师&行政人员.txt", std::ios::out); for(std::vector<TEAADMI*>::iterator it = teaadmi.begin(); it != teaadmi.end();) { if((*it) -> get_id() == aid){flag = 1; delete (*it); it = teaadmi.erase(it); continue;} out << (*it) -> get_name() << " " << (*it) -> get_sex() << " "; out << (*it) -> get_age() << " " << (*it) -> get_id() << " "; out << (*it) -> get_department() << " " << (*it) -> get_profession() << " " << (*it) -> get_title() << " "; out << (*it) -> get_politics() << " " << (*it) -> get_position() << std::endl; ++it; } out.close(); std::cout << "删除成功,输入任意键返回\n"; getch(); } void Edit_information() //修改信息 { std::cout << "输入目标ID以确认\n"; std::string aid; std::cin >> aid; for(unsigned int i = 0; i < aid.length(); i++) { if(aid[i] < '0' || aid[i] > '9') { std::cout << "输入非法,输入任意键返回\n"; getch(); return; } } std::multimap<std::string, COMMON *>::iterator beg, en, iter; beg = sear.lower_bound(aid); en = sear.upper_bound(aid); if(beg == en) { std::cout << "目标不存在,输入任意键返回\n"; getch(); return; } system("cls"); bool flag = 0; std::ofstream out; out.open("实验员.txt", std::ios::out); for(auto iter:tester) { if(iter -> get_id() == aid) { iter -> show(), std::cout << "\n\n根据提示输入修改信息\n\n"; while(iter -> change()) { system("cls"); iter -> show(); std::cout << "输入非法,请重新输入\n"; } flag = 1; } out << iter -> get_name() << " " << iter -> get_sex() << " "; out << iter -> get_age() << " " << iter -> get_id() << " "; out << iter -> get_laboratory() << " " << iter -> get_title() << std::endl; } out.close(); if(flag) {std::cout << "修改成功,输入任意键返回\n"; getch(); return;} out.open("教师.txt", std::ios::out); for(auto iter:teacher) { if(iter -> get_id() == aid) { iter -> show(), std::cout << "\n\n根据提示输入修改信息\n\n"; while(iter -> change()) { system("cls"); iter -> show(); std::cout << "输入非法,请重新输入\n"; } flag = 1; } out << iter -> get_name() << " " << iter -> get_sex() << " "; out << iter -> get_age() << " " << iter -> get_id() << " "; out << iter -> get_department() << " " << iter -> get_profession() << " " << iter -> get_title() << std::endl; } out.close(); if(flag) {std::cout << "修改成功,输入任意键返回\n"; getch(); return;} out.open("行政人员.txt", std::ios::out); for(auto iter:administrator) { if(iter -> get_id() == aid) { iter -> show(), std::cout << "\n\n根据提示输入修改信息\n\n"; while(iter -> change()) { system("cls"); iter -> show(); std::cout << "输入非法,请重新输入\n"; } flag = 1; } out << iter -> get_name() << " " << iter -> get_sex() << " "; out << iter -> get_age() << " " << iter -> get_id() << " "; out << iter -> get_politics() << " " << iter -> get_position() << std::endl; } out.close(); if(flag) {std::cout << "修改成功,输入任意键返回\n"; getch(); return;} out.open("教师&行政人员.txt", std::ios::out); for(auto iter:teaadmi) { if(iter -> get_id() == aid) { iter -> show(), std::cout << "\n\n根据提示输入修改信息\n\n"; while(iter -> change()) { system("cls"); iter -> show(); std::cout << "输入非法,请重新输入\n"; } flag = 1; } out << iter -> get_name() << " " << iter -> get_sex() << " "; out << iter -> get_age() << " " << iter -> get_id() << " "; out << iter -> get_department() << " " << iter -> get_profession() << " " << iter -> get_title() << " "; out << iter -> get_politics() << " " << iter -> get_position() << std::endl; } out.close(); std::cout << "修改成功,输入任意键返回\n"; getch(); } bool Query_information() //查询函数 { system("cls"); std::cout << "输入目标姓名或ID以查询\n"; std::string aid; std::cin >> aid; std::multimap<std::string, COMMON *>::iterator beg, en, iter; beg = sear.lower_bound(aid); en = sear.upper_bound(aid); if(beg == en) { std::cout << "查询结果为空,输入任意键返回\n"; getch(); return 0; } for(iter = beg; iter != en; ++iter) { iter -> second -> show(); std::cout << std::endl; } return 1; } void Browse_information() //浏览函数 { system("cls"); std::cout << "-------------------实验员-------------------\n"; std::cout << "姓名\t" << "性别\t" << "年龄\t" << "ID\t\t" << "实验室名称\t" << "职务\n"; for(auto iter:tester) iter -> show_row(); std::cout << "\n------------------行政人员------------------\n"; std::cout << "姓名\t" << "性别\t" << "年龄\t" << "ID\t\t" << "政治面貌\t" << "职称\n"; for(auto iter:administrator) iter -> show_row(); std::cout << "\n--------------------教师--------------------\n"; std::cout << "姓名\t" << "性别\t" << "年龄\t" << "ID\t\t" << "院系\t\t" << "专业\t\t" << "职务\n"; for(auto iter:teacher) iter -> show_row(); std::cout << "\n-----------------行政人员&教师--------------\n"; std::cout << "姓名\t" << "性别\t" << "年龄\t" << "ID\t\t" << "政治面貌\t" << "职称\t\t" << "院系\t\t" << "专业\t\t" << "职务\n"; for(auto iter:teaadmi) iter -> show_row(); } void count_information() //统计信息 { system("cls"); std::cout << "员工总人数:\t\t" << COMMON::get_person_sum() << std::endl; std::cout << "男性人数:\t\t" << COMMON::get_man_sum() << std::endl; std::cout << "女性人数:\t\t" << COMMON::get_woman_sum() << std::endl; std::cout << "教师人数:\t\t" << TEACHER::get_teacher_sum() << std::endl; std::cout << "实验员人数:\t\t" << TESTER::get_tester_sum() << std::endl; std::cout << "行政管理人员人数:\t" << ADMINISTRATOR::get_administrator_sum() << std::endl; std::cout << "行政管理人员&教师人数:\t" << TEAADMI::get_teaadmi_sum() << std::endl; std::cout << "\n\n输入任意键返回上一级\n"; getch(); } #endif // MYFUN_H_INCLUDED main.cpp 主函数: #include"interface.h" int main() { Information_load(); //加载信息 interface_login(); //首界面 room_delete(); //释放空间 // count_information(); return 0; }

请教大神以下代码哪部分是控制最后要到的状态的?

#include <iostream> #include <vector> #include <algorithm> #include <list> #include <queue> #include <unordered_map> #include <string> #include <sstream> #include <stdexcept> #include <memory> #include <Windows.h> using namespace std; class Board; class Solver; class Board { friend class Solver; friend class compare_node; public: typedef enum { TL_SPACE, TL_1, TL_2, TL_3, TL_4, TL_5, TL_6, TL_7, TL_8, }TILE; Board() { for (int i = 0; i != 8; tiles.push_back(TILE(++i))); tiles.push_back(TL_SPACE); } Board(int t[3][3]) { for (int i = 0; i != 3; ++i) for (int j = 0; j != 3; ++j) tiles.push_back(TILE(t[i][j])); } int hamming() { int count = 0; for (int i = 0; i != tiles.size(); ++i) if (tiles[i] != TILE((i + 1)) && tiles[i] != TL_SPACE) ++count; return count; } int manhattan() { int count = 0; int num; for (int i = 0; i != tiles.size(); ++i) { if (tiles[i] == TL_SPACE) continue; num = (tiles[i] + 8) % 9; count = count + (abs(num / 3 - i / 3) + abs(num % 3 - i % 3)); } return count; } bool equals(const Board &b) const { bool ret = true; for (int i = 0; i != b.tiles.size(); ++i) { if (this->tiles[i] != b.tiles[i]) { ret = false; break; } } return ret; } void neighbors(vector<Board> &nghbrs) { nghbrs.clear(); int pos = 0; for (; pos != tiles.size() && tiles[pos] != TL_SPACE; ++pos); int row = pos / 3; int col = pos % 3; if (row > 0) { nghbrs.push_back(*this); nghbrs.back().swap(pos, (row - 1) * 3 + col); } if (row < 2) { nghbrs.push_back(*this); nghbrs.back().swap(pos, (row + 1) * 3 + col); } if (col > 0) { nghbrs.push_back(*this); nghbrs.back().swap(pos, row * 3 + col - 1); } if (col < 2) { nghbrs.push_back(*this); nghbrs.back().swap(pos, row * 3 + col + 1); } } string toString() { string s; ostringstream convert; for (int i = 0; i != tiles.size(); ++i) convert << static_cast<int>(tiles[i]) << " "; s = convert.str(); return s; } private: vector<TILE> tiles; Board *parent = nullptr; int f = 0; int g = 0; int h = 0; void swap(size_t pos1, size_t pos2) { if (pos1 >= tiles.size() || pos2 >= tiles.size()) throw runtime_error("position not match"); std::swap(tiles[pos1], tiles[pos2]); } }; // function used to compared board in heap class compare_node { public: bool operator()(Board *&l, Board *&r) { return l->f > r->f; } }; // vector for board pointers class bvector : public vector<Board*> { public: bvector() { make_heap(this->begin(), this->end(), compare_node()); } void push_node(Board *b) { this->push_back(b); push_heap(this->begin(), this->end(), compare_node()); } void pop_node() { pop_heap(this->begin(), this->end(), compare_node()); this->pop_back(); } }; class Solver { friend class Board; public: Solver() = default; Solver(Board *p) : initial(p) {} void init() { if (initial == nullptr) { cerr << "Solver not initialized" << endl; return; } if (!isSolvable()) { cerr << "No solution existed" << endl; return; } initial->g = 0; initial->h = initial->manhattan() + initial->hamming(); initial->f = initial->g + initial->h; open_ref[initial->toString()] = initial; open_set.push_node(initial); while (!open_set.empty()) { Board *closed_node = open_set.front(); open_ref.erase(closed_node->toString()); closed_ref[closed_node->toString()] = closed_node; open_set.pop_node(); if (closed_node->equals(*end)) { Board *p = closed_node; while (p->parent != nullptr) { solution.push_back(p->toString()); p = p->parent; } solution.push_back(initial->toString()); reverse(solution.begin(), solution.end()); return; } vector<Board> neighbors; closed_node->neighbors(neighbors); for (auto iter = neighbors.begin(); iter != neighbors.end(); ++iter) { Board *new_node = new Board(*iter); new_node->g = 0; new_node->h = new_node->manhattan() + new_node->hamming(); new_node->f = new_node->f + new_node->h; // ignore the neighbor which is already evaluated. if (closed_ref.find(new_node->toString()) != closed_ref.end()) { delete new_node; continue; } if (open_ref.find(new_node->toString()) != open_ref.end()) { delete new_node; continue; } new_node->parent = closed_node; open_set.push_node(new_node); open_ref[new_node->toString()] = new_node; } } return; } vector<string> getSolution() { return solution; } // http://www.geeksforgeeks.org/check-instance-8-puzzle-solvable/ // It is not possible to solve an instance of 8 puzzle if the number of inversions is odd // in the initial state bool isSolvable() { int count = 0; for (int i = 0; i != initial->tiles.size(); ++i) for (int j = i + 1; j != initial->tiles.size(); ++j) if (initial->tiles[i] != Board::TILE::TL_SPACE && initial->tiles[j] != Board::TILE::TL_SPACE && static_cast<int>(initial->tiles[i]) > static_cast<int>(initial->tiles[j])) ++count; return (count % 2 == 0); } ~Solver() { delete initial; delete end; for (auto iter = open_ref.begin(); iter != open_ref.end(); ++iter) delete iter->second; for (auto iter = closed_ref.begin(); iter != closed_ref.end(); ++iter) delete iter->second; } private: Board *initial = nullptr; Board *end = new Board(); bvector open_set; unordered_map<string, Board*> open_ref; unordered_map<string, Board*> closed_ref; vector<string> solution; }; int main() { int t1[3][3] = { { 1, 2, 3 },{ 4, 5, 6 },{ 8, 7, 0 } }; int t2[3][3] = { { 8, 1, 3 },{ 4, 0, 2 },{ 7, 6, 5 } }; Board *b1 = new Board(t1); Board *b2 = new Board(t2); Solver s1(b1); Solver s2(b2); s1.init(); s2.init(); auto ret2 = s2.getSolution(); cout << "The solution to " << b1->toString() << endl; for (auto str : ret2) cout << str << endl; system("PAUSE"); return 0; }

计祘客的一道线段树 一直超时 实在不会了 求解答

地址:[https://nanti.jisuanke.com/t/10927](https://nanti.jisuanke.com/t/10927 "") 这是我的代码,太菜了 实在不会,有没有大神给点思路,始终不知道该怎么优化 ``` #include<iostream> #include<cstdio> #include<map> #include<cstring> #include<string> #include<stack> #include<queue> #include<algorithm> #include<cmath> #include<vector> using namespace std; #define LL long long int lev[15]; int n,m,q; struct node { int l,r; int mexp; int level; node* lc; node* rc; vector<int>ve; node() { lc = rc = NULL; level = 1; mexp = 0; } }; int GetLevel(int exp) { for(int i = m;i>1;i--) { if(exp>=lev[i]) { // cout << "level" << i << endl; return i; } } return 1; } void Build(int l,int r,node* root) { root->l = l; root->r = r; if(l>=r) { return; } int mid = (l+r)/2; root->lc = new node(); root->rc = new node(); Build(l,mid,root->lc); Build(mid+1,r,root->rc); } void PushDown(node* root) { /*if(root->e!=0 && root->l!=root->r) { PushDown(root->lc,root->e); PushDown(root->rc,root->e); root->e = 0; } root->e = e; if(root->l!=root->r) root->mexp = max(root->lc->mexp,root->rc->mexp); int level = GetLevel(root->mexp); root->mexp += e*level;*/ if(root->lc==NULL || root->rc==NULL) return; if(root->ve.size()!=0) { for(int i = 0;i<root->ve.size();i++) { root->lc->mexp += root->ve[i]*root->lc->level; root->lc->level = GetLevel(root->lc->mexp); root->rc->mexp += root->ve[i]*root->rc->level; root->rc->level = GetLevel(root->rc->mexp); } for(int i = 0;i<root->ve.size();i++) { root->lc->ve.push_back(root->ve[i]); root->rc->ve.push_back(root->ve[i]); } root->ve.clear(); } } void PushUp(node* root) { if(root->l!=root->r) { root->mexp = max(root->lc->mexp,root->rc->mexp); root->level = max(root->lc->level,root->rc->level); } } void Update(int l,int r,int e,node* root) { if(root==NULL) return; if(l<=root->l && root->r<=r) { root->mexp += root->level*e; root->ve.push_back(e); root->level = GetLevel(root->mexp); return; } PushDown(root); int mid = (root->l+root->r)/2; if(l<=mid) { Update(l,r,e,root->lc); } if(r>mid) { Update(l,r,e,root->rc); } PushUp(root); } int query(int l,int r,node* root) { if(l<=root->l && root->r<=r) { //cout << root->level << endl; return root->mexp; } PushDown(root); int mid = (root->l+root->r)/2; int a1,a2; a1 = a2 = 0; if(l<=mid) { a1 = query(l,r,root->lc); } if(r>mid) { a2 = query(l,r,root->rc); } PushUp(root); return max(a1,a2); } void Dele(node* root) { if(root->lc == NULL && root->rc==NULL) { root->ve.clear(); delete root; return; } Dele(root->lc); Dele(root->rc); root->ve.clear(); delete root; } int main() { int t; scanf("%d",&t); int _case = 0; while(t--) { node* root = new node(); scanf("%d%d%d",&n,&m,&q); Build(1,n,root); for(int i = 2;i<=m;i++) { scanf("%d",&lev[i]); } char ch; printf("Case %d:\n",++_case); while(q--) { cin >> ch; int a,b,c; switch(ch) { case 'W': scanf("%d%d%d",&a,&b,&c); Update(a,b,c,root); break; case 'Q': scanf("%d%d",&a,&b); printf("%d\n",query(a,b,root)); break; } //cout << ch << endl; } printf("\n"); Dele(root); } return 0; } ```

FlatBuffers的多语言集成问题

<div class="post-text" itemprop="text"> <h1>Question</h1> <p>I have a recurring crash (<code>panic: runtime error: slice bounds out of range</code>) from the <code>flatbuffers</code> generated server files when attempting to access a part of a buffer (created with <code>flatbuffers</code>) which contains a message streamed from one client to a server.<br> This problem only appears in integration of both client and server. When tested on their own, both client and server succeed in using <code>flatbuffers</code> and no crash occurs in the server <code>// see the boundary tests below</code><br> Knowing that:<br> - the sent and received <code>byte[]</code> is the same, (which excludes a problem in the communication method)<br> - the sent data is correctly formed before it is put in the <code>flatbuffers</code>' <code>buffer</code> and sent.<br> What could be causing this? </p> <h1>Problem context and details</h1> <p>I have a <code>c++</code> <strong>client</strong> and a <code>go</code> <strong>server</strong> that communicate using <code>FlatBuffers</code>.<br> The <strong>client</strong> and <strong>server</strong> both have automated boundary-tests which confirm that they each "correctly" use <code>flatbuffers</code> the way they should. (i.e. the <strong>client</strong> creates the buffer before sending it and the <strong>server</strong> receives before access it)<br> These tests work. We are using <code>FlatBuffers-v1.10.0</code></p> <p>My problem is that when they are used together, the following error always occurs in the <strong>server</strong> when accessing to the buffer: </p> <pre><code>panic: runtime error: slice bounds out of range goroutine 19 [running]: github.com/google/flatbuffers/go.(*Table).GetVOffsetT(...) /home/.../go/github.com/google/flatbuffers/go/table.go:134 github.com/google/flatbuffers/go.(*Table).OffsetT(0x4000045c68, 0x4000000004, 0x4000160008) /home/.../go/github.com/google/flatbuffers/go/table.go:16 +0xf0 github.com/PhantomIntelligence/Server/lib/Protocol/Stream.(*StreamedData).Id(0x4000045c68, 0x4000045c68) /home/.../go/github.com/PhantomIntelligence/Server/lib/Protocol/Stream/SteamedData.go:30 +0x2c github.com/PhantomIntelligence/Server/dataAccess/conversion/flatBuffers.ConvertStreamMessage(0x4000015a000, 0xa7c, 0xe00, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0) /home/.../go/github.com/PhantomIntelligence/Server/dataAccess/conversion/flatBuffers/deserialization.go:55 +0x1fc ... // the rest is irrelevant for this question's purpose </code></pre> <h2>Data causing the crash</h2> <p>The crash always happen on the first buffer received by the server when it tries to access it to use it. More specifically, it always happen when attempting to access the either the (0th, 12th or 15th) <code>ContainerData</code> of the 7th <code>Container</code>. </p> <blockquote> <p>Know that for this use case, we send a <em>StreamedData</em> with 16 <em>Containers</em>, each holding 16 <em>ContainerData</em> </p> </blockquote> <hr> <h1>Code details</h1> <blockquote> <p>Note that only the structure is remains from my original implementation. I am not allowed to divulgate the nature of the data we manipulate. Thus the object names might seem weird, but the structure is the relevant part. </p> </blockquote> <h2>Schema compilation</h2> <p>The <code>c++</code> <strong>client</strong> runs this during its compilation: </p> <pre><code>flatc -o lib/ --no-js-exports --no-prefix --scoped-enums --cpp schemas/*.fbs </code></pre> <p>The <code>go</code> <strong>server</strong> runs this during its compilation: </p> <pre><code>flatc -o lib/ --no-js-exports --no-prefix --scoped-enums --go schemas/*.fbs </code></pre> <h2>Schemas</h2> <p>Both the <strong>client</strong> and <strong>server</strong> use the following schema: </p> <blockquote> <p>Please note that this extract is not the complete schema, only the part relevant for this question. </p> </blockquote> <pre><code>// file: stream_streamed_data.fbs namespace Protocol.Stream; table ContainerData { id:uint16 = 0; a:uint16 = 0; b:uint16 = 0; c:int16 = 0; d:int16 = 0; e:uint8 = 0; } table Container { id:uint16 = 65535; data:[ContainerData]; } table StreamedData { id:uint16 = 0; containers:[Container]; } ---- // file: stream_payload.fbs include "stream_streamed_data.fbs"; /* some more includes ... */ namespace Protocol.Stream; union PayloadContent { StreamedData, ..., Request, Result } table Payload { sensor_id:string; content:PayloadContent; } ---- // file: header.fbs namespace Protocol; table Header { source_id:string; destination_id:string; timestamp:string; } ---- // file: protocol_message.fbs include "headers.fbs"; include "stream_payload.fbs"; /* some more includes ... */ namespace Protocol; union Content { Stream.Payload, ..., Other.Payload } table Message { header:Header; content:Content; } root_type Message; </code></pre> <p>The <strong>client</strong> has to stream <code>Protocol.Message</code>s that contain <code>Protocol.Stream.Payload</code>, which themselves contain a <code>Protocol.Stream.StreamedMessage</code>. </p> <h2><strong>Client</strong> implementation</h2> <pre><code>#ifndef CLIENT_FLATBUFFERSCONVERTER_HPP #define CLIENT_FLATBUFFERSCONVERTER_HPP #include &lt;flatbuffers/flatbuffers.h&gt; #include &lt;lib/protocol/protocol_message_generated.h&gt; #include &lt;chrono&gt; #include &lt;iostream&gt; namespace ServerCommunication { enum class ProtocolStructure : uint8_t { NONE = 0, /* some more types ... */ SENSOR_MESSAGE = 12, /* some more types ... */ UNRECOGNIZED_TYPE = // A NUMBER, MIN = NONE, MAX = UNRECOGNIZED_TYPE }; typedef uint8_t* FlatBuffersBytes; struct BytesToSend { FlatBuffersBytes data; size_t dataLength; }; namespace BufferSize { size_t const STREAMED_MESSAGE = 2560; } template&lt;class T&gt; class FlatBuffersConverter { public: explicit FlatBuffersConverter() = delete; ~FlatBuffersConverter() noexcept = delete; FlatBuffersConverter(FlatBuffersConverter const&amp; other) = delete; FlatBuffersConverter(FlatBuffersConverter&amp;&amp; other) noexcept = delete; FlatBuffersConverter&amp; operator=(FlatBuffersConverter const&amp; other)&amp; = delete; FlatBuffersConverter&amp; operator=(FlatBuffersConverter&amp;&amp; other)&amp; noexcept = delete; static BytesToSend const convertSensorMessage(typename T::Message&amp;&amp; message) noexcept; private: static std::string const generateSerializationTimestamp() noexcept; }; template&lt;class T&gt; BytesToSend const FlatBuffersConverter&lt;T&gt;::convertStreamMessage(typename T::StreamMessage&amp;&amp; message) noexcept { flatbuffers::FlatBufferBuilder builder(BufferSize::STREAM_MESSAGE); auto streamIdFromMessage = message.getStreamId(); auto streamId = builder.CreateString(streamIdFromMessage.c_str(), streamIdFromMessage.size()); auto source = streamId; auto destination = builder.CreateString("Server"); auto timestamp = builder.CreateString(generateSerializationTimestamp()); auto header = Protocol::CreateHeader( builder, source, destination, timestamp); auto containersFromStreamMessage = message.getContainers(); std::vector&lt;flatbuffers::Offset&lt;Protocol::Stream::Container&gt;&gt; containerVector; auto containerIterator = containersFromStreamMessage-&gt;begin(); auto containerEnd = containersFromStreamMessage-&gt;end(); for (; containerIterator != containerEnd; ++containerIterator) { auto dataFromContainer = containerIterator-&gt;getData(); std::vector&lt;flatbuffers::Offset&lt;GatewayProtocol::Stream::ContainerData&gt;&gt; containerDataVector; auto containerDataIterator = dataFromContainer-&gt;begin(); auto containerDataEnd = dataFromContainer-&gt;end(); for (; containerDataIterator != containerDataEnd; ++containerDataIterator) { auto track = Protocol::Stream::CreateContainerData( builder, containerDataIterator-&gt;id, containerDataIterator-&gt;a, containerDataIterator-&gt;b, containerDataIterator-&gt;c, containerDataIterator-&gt;d, containerDataIterator-&gt;e); containerDataVector.push_back(containerData); } auto containerDataFBVector = builder.CreateVector(containerDataVector); auto container = Protocol::Stream::CreateContainer( builder, containerIterator-&gt;id, containerDataFBVector); containerVector.push_back(container); } auto containers = builder.CreateVector(containerVector); auto streamMessageContent = Protocol::Stream::CreateStreamedData( builder, message.messageId, containers); auto streamPayload = Protocol::Stream::CreatePayload( builder, streamId, Protocol::Stream::PayloadContent::StreamedData, streamMessageContent.Union()); auto convertedMessage = Protocol::CreateMessage( builder, header, Protocol::Content::Stream_Payload, sensorPayload.Union()); builder.Finish(convertedMessage); auto size = builder.GetSize(); auto data = builder.GetBufferPointer(); BytesToSend bytesToSend{data, size}; return bytesToSend; } template&lt;class T&gt; std::string const FlatBuffersConverter&lt;T&gt;::generateSerializationTimestamp() noexcept { std::size_t const ARBITRARY_BIG_ENOUGH_SIZE = 128; auto timestamp = std::chrono::high_resolution_clock::now(); auto time_tTimestamp = std::chrono::system_clock::to_time_t(timestamp); auto utcTime = gmtime(&amp;time_tTimestamp); char charArrayTime[ARBITRARY_BIG_ENOUGH_SIZE]; auto numberOfCharacterWritten = strftime(charArrayTime, sizeof(charArrayTime), "%D %T", utcTime); std::string formattedTime(std::begin(charArrayTime), std::begin(charArrayTime) + numberOfCharacterWritten); return formattedTime; } } #endif //CLIENT_FLATBUFFERSCONVERTER_HPP </code></pre> <h2><strong>Client</strong> Boundary test</h2> <pre><code>#ifndef CLIENT_SERVERCOMMUNICATORTEST_CPP #define CLIENT_SERVERCOMMUNICATORTEST_CPP #include &lt;gtest/gtest.h&gt; /* some other include */ #include "spirit-sensor-gateway/server-communication/WebSocketServerCommunicationStrategy.hpp" #include "test/utilities/stub/WebSocketServerStub.h" // &lt;--- Receives and accesses the buffer using ServerCommunication::WebSocketServerCommunicationStrategy; using Stub::WebSocketServerStub; using TestFunctions::DataTestUtil; class WebSocketServerCommunicatorTest : public ::testing::Test { protected: }; TEST_F(WebSocketServerCommunicatorTest, given_aNumberOfRandomStreamDataMessage_when_send_then_theDataIsPutInFlatBuffersAndReceivedByTheServer) { auto numberOfMessageToSend = 10; WebSocketServerStub webSocketServerStub; WebSocketServerCommunicationStrategy&lt;Sensor::Test::ServerLike::Structures&gt; webSocketServerCommunicationStrategy; webSocketServerStub.run(); webSocketServerCommunicationStrategy.openConnection(webSocketServerStub.getAddress()); ServerStructuresLists::StreamDataMessages sentStreamDataMessages; for (auto i = 0; i &lt; numberOfMessageToSend; i++) { auto streamDataMessage = DataTestUtil::createRandomStreamDataMessage(); auto streamDataMessageCopy = DataModel::StreamDataMessage(streamDataMessage); sentStreamDataMessages.push_back(std::move(streamDataMessageCopy)); webSocketServerCommunicationStrategy.sendMessage(std::move(streamDataMessage)); } auto numberOfReceivedMessages = webSocketServerStub.getNumberOfMessageReceived(); while(numberOfMessageToSend != numberOfReceivedMessages) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::this_thread::yield(); numberOfReceivedMessages = webSocketServerStub.getNumberOfMessageReceived(); } webSocketServerCommunicationStrategy.closeConnection(); auto receivedStreamDataMessages = webSocketServerStub.getStreamDataMessages(); auto sameMessageSentAndReceived = sentStreamDataMessages.size() == receivedStreamDataMessages.size(); for (auto streamDataMessageIndex = 0; sameMessageSentAndReceived &amp;&amp; streamDataMessageIndex &lt; sentStreamDataMessages.size(); ++streamDataMessageIndex) { sameMessageSentAndReceived = sameMessageSentAndReceived &amp;&amp; sentStreamDataMessages.front() == receivedStreamDataMessages.front(); sentStreamDataMessages.pop_front(); receivedStreamDataMessages.pop_front(); } if (!sameMessageSentAndReceived) { while (!sentStreamDataMessages.empty() &amp;&amp; !receivedStreamDataMessages.empty()) { std::cout &lt;&lt; "Sent: " &lt;&lt; sentStreamDataMessages.front().toString() &lt;&lt; std::endl; std::cout &lt;&lt; "Received: " &lt;&lt; receivedStreamDataMessages.front().toString() &lt;&lt; std::endl; sentStreamDataMessages.pop_front(); receivedStreamDataMessages.pop_front(); } } ASSERT_TRUE(sameMessageSentAndReceived); } #endif //CLIENT_SERVERCOMMUNICATORTEST_CPP </code></pre> <h2><strong>Client</strong>'s ServerStub FlatBuffer Conversion function</h2> <pre><code>#include "ServerStubFlatBuffersConverter.h" using Stub::ServerFlatBuffersConverter; using ServerCommunication::ProtocolStructure; ServerFlatBuffersConverter::StreamDataMessage ServerFlatBuffersConverter::convertToStreamDataMessage(const ServerCommunication::FlatBuffersBytes flatBuffersBytes) { // the identification step has been done at this point, we know the []byte holds a StreamedData auto message = Protocol::GetMessage(flatBuffersBytes); auto streamDataMessagePayload = message-&gt;content_as_Stream_Payload(); auto streamedData = streamDataMessagePayload-&gt;content_as_StreamedData(); auto messageId = streamedData-&gt;id(); auto streamId = flatbuffers::GetString(streamDataMessagePayload-&gt;stream_id()); auto ContainersBuffer = streamedData-&gt;containers(); std::vector&lt;DataModel::MessageContainer&gt; containers; for (flatbuffers::uoffset_t containerIndex = 0; containerIndex &lt; ContainersBuffer-&gt;Length(); ++containerIndex) { auto containerFromBuffer = ContainersBuffer-&gt;Get(containerIndex); auto containerId = containerFromBuffer-&gt;id(); auto containerDatasBuffer = containerFromBuffer-&gt;data(); std::vector&lt;DataModel::ContainerData&gt; containerDatas; for (auto dataIterator = containerDatasBuffer-&gt;begin(); dataIterator != containerDatasBuffer-&gt;end(); ++dataIterator) { auto data = DataModel::ContainerData{ dataIterator-&gt;id(), dataIterator-&gt;a(), dataIterator-&gt;b(), dataIterator-&gt;c(), dataIterator-&gt;d(), dataIterator-&gt;e() }; containerDatas.push_back(data); } auto container = DataModel::MessageContainer(containerId, containerDatas); containers.push_back(container); } StreamDataMessage message(streamId, messageId, containers); return message; } </code></pre> <h2><strong>Server</strong> Implementation</h2> <pre><code>package flatBuffers import ( "github.com/PhantomIntelligence/Server/domain/protocol" "github.com/PhantomIntelligence/Server/lib/Protocol" "github.com/PhantomIntelligence/Server/lib/Protocol/Stream" "github.com/google/flatbuffers/go" ) type GatewayMessageType = byte const ( NONE = 0 /* some more types ... */ SENSOR_MESSAGE = 12 /* some more types ... */ UNRECOGNIZED_TYPE = // A NUMBER ) func ConvertStreamMessage(messageBytes []byte) protocol.StreamMessage { // the identification step has been done at this point, we know the []byte holds a StreamedData var protocolMessageFlatBuffersTable = new(flatbuffers.Table) var protocolMessageContentFlatBuffersTable = new(flatbuffers.Table) var clientMessageOffset = Protocol.GetRootAsMessage(messageBytes, 0) var header = new(Protocol.Header) clientMessageOffset.Header(header) clientMessageOffset.Content(protocolMessageFlatBuffersTable) var messageTimestampString = string(header.Timestamp()) var streamedPayload = new(Stream.Payload) streamedPayload.Init(protocolMessageFlatBuffersTable.Bytes, protocolMessageFlatBuffersTable.Pos) streamedPayload.Content(protocolMessageContentFlatBuffersTable) var streamIdFromClient = string(streamedPayload.StreamId()) var streamedDataFromClient = new(Stream.StreamedData) streamedDataFromClient.Init(protocolMessageContentFlatBuffersTable.Bytes, protocolMessageContentFlatBuffersTable.Pos) var numberOfContainers = streamedDataFromClient.ContainersLength() var containers []protocol.Container for containerIndex := 0; containerIndex &lt; numberOfContainers; containerIndex++ { var containerFromStream = new(Stream.Container) streamedDataFromClient.Containers(containerFromStream, containerIndex) var numberOfContainerDatas = containerFromStream.ContainerDatasLength() var datas []protocol.ContainerData for containerDataIndex := 0; containerDataIndex &lt; numberOfContainerDatas; containerDataIndex++ { var dataFromContainer = new(Stream.ContainerData) containerFromStream.Data(dataFromContainer, dataIndex) datas = append(datas, protocol.ContainerData{ Id: protocol.IdType(dataFromContainer.Id()), // &lt;--- This line crashes ! always @ containerIndex = 6, containerDataIndex = 0, 12 or 15 A: protocol.AType(dataFromContainer.A()), B: protocol.BType(dataFromContainer.B()), C: protocol.CType(dataFromContainer.C()), D: protocol.DType(dataFromContainer.D()), E: protocol.EType(dataFromContainer.E()), }) } containers = append(containers, protocol.Container{ ContainerId: protocol.ContainerIdType(containerFromStream.Id()), ContainerDatas: datas, }) } var streamedMessage = protocol.StreamedMessage{ StreamId: protocol.SensorIdType(streamIdFromClient), MessageId: protocol.MessageIdType(streamedDataFromClient.Id()), Containers: containers, } return streamedMessage } </code></pre> <h2>Server Boundary test</h2> <p>This test pass, we also have a similar test that sends <em>n</em> random data instead of 1 and it passes too</p> <pre><code>package receptionFromGateway_test import ( "/* some more imports */ "github.com/PhantomIntelligence/Server/test/utilities/clientStub" "os" "runtime" "testing" "time" ) func TestFlatBuffersReceptionAndAccessFromClient(test *testing.T) { defer os.RemoveAll("./logs") test.Run("given_aStreamedDataMessageSentFromClientStub"+ "_when_receivedAndAccessedByServer"+ "_then_streamedDataMessageIntegrityIsConserved", func(subTest *testing.T) { sentStreamedDataMessage := utilities.GenerateRandomStreamedDataMessage(16, 16) // 16 container, 16 data each deserializer := serialization.NewFlatBufferDeserializationFilter() pipe := dataFlow.NewPipe(deserializer) procedure := dataFlowMock.NewProcedurePassToPipeThenSave(pipe) pipeline := dataFlow.NewPipeline(procedure) client := clientStub.NewWebSocketCommunicator() // &lt;-- this calls `convertStreamMessageToFlatBuffers` written below server := serving.NewServer() server.Router.Mediator.Pipeline = pipeline go server.Serve(":3591") runtime.Gosched() time.Sleep(50 * time.Millisecond) client.Start() client.Send(sentStreamedDataMessage) runtime.Gosched() time.Sleep(50 * time.Millisecond) client.Stop() pipeline.GetProducingPipe().TerminateProcess() var receivedStreamedDataMessage = pipeline.GetProducingPipe().Filter.(*dataFlowMock.FilterSaveObjectReceived).ObjectReceived utilities.AssertEqual(subTest, receivedStreamedDataMessage, sentStreamedDataMessage) }) } </code></pre> <h2>Server ClientStub's serialization function</h2> <pre><code>package client Stub import ( "github.com/PhantomIntelligence/Server/dataAccess/conversion/flatBuffers" "github.com/PhantomIntelligence/Server/domain/protocol" "github.com/PhantomIntelligence/Server/lib/Protocol" "github.com/PhantomIntelligence/Server/lib/Protocol/Stream" "github.com/google/flatbuffers/go" ) const ( streamedDataMessageInitialSize = 2560 ) func convertStreamMessageToFlatBuffers(message protocol.StreamMessage) []byte { builder := flatbuffers.NewBuilder(streamedDataMessageInitialSize) var streamIdOffset = builder.CreateString(string(message.StreamId)) var headerOffset = createFlatBufferHeaders(builder, streamIdOffset) var numberOfContainers int var containerOffsets = make(map[int]flatbuffers.UOffsetT) for containerIndex, container := range message.Containers { var numberOfData int var containerDataOffsets = make(map[int]flatbuffers.UOffsetT) for containerIndex, container := range container.ContainerDatas { Stream.ContainerDataStart(builder) Stream.ContainerDataAddId(builder, uint16(container.ContainerDataId)) Stream.ContainerDataAddA(builder, uint16(container.A)) Stream.ContainerDataAddB(builder, uint16(container.B)) Stream.ContainerDataAddC(builder, int16(container.C)) Stream.ContainerDataAddD(builder, int16(container.D)) Stream.ContainerDataAddE(builder, byte(container.E)) containerDataOffset := Stream.ContainerDataEnd(builder) containerDataOffsets[containerIndex] = containerDataOffset numberOfData = containerIndex + 1 } Stream.ContainerStartDataVector(builder, numberOfData) // FlatBuffer UOffsetT vector requires to be filled by pre-pending backward the offsets for dataOffsetIndex := numberOfData - 1; dataOffsetIndex &gt;= 0; dataOffsetIndex-- { builder.PrependUOffsetT(containerDataOffsets[dataOffsetIndex]) } var dataOffsetVector = builder.EndVector(numberOfData) Stream.ContainerStart(builder) Stream.ContainerAddId(builder, uint16(container.ContainerId)) Stream.ContainerAddData(builder, dataOffsetVector) containerOffset := Stream.ContainerEnd(builder) containerOffsets[containerIndex] = containerOffset numberOfContainers = containerIndex + 1 } Stream.StreamedDataStartContainersVector(builder, numberOfContainers) // FlatBuffer UOffsetT vector requires to be filled by pre-pending backward the offsets for containerOffsetIndex := numberOfContainers - 1; containerOffsetIndex &gt;= 0; containerOffsetIndex-- { builder.PrependUOffsetT(containerOffsets[containerOffsetIndex]) } var containerOffsetVector = builder.EndVector(numberOfContainers) Stream.StreamedDataStart(builder) Stream.StreamedDataAddId(builder, uint16(message.MessageId)) Stream.StreamedDataAddContainers(builder, containerOffsetVector) var streamedDataMessageOffset = Stream.StreamedDataEnd(builder) Stream.PayloadStart(builder) Stream.PayloadAddSensorId(builder, streamIdOffset) Stream.PayloadAddContentType(builder, Stream.PayloadContentStreamedData) Stream.PayloadAddContent(builder, streamedDataMessageOffset) var streamPayloadOffset = Stream.PayloadEnd(builder) Protocol.MessageStart(builder) Protocol.MessageAddHeader(builder, headerOffset) Protocol.MessageAddContentType(builder, Protocol.ContentStream_Payload) Protocol.MessageAddContent(builder, streamPayloadOffset) clientStreamMessageOffset := Protocol.MessageEnd(builder) builder.Finish(clientStreamMessageOffset) flatBuffersBytes := builder.Bytes[builder.Head():] return flatBuffersBytes } func createFlatBufferHeaders(builder *flatbuffers.Builder, sensorIdOffset flatbuffers.UOffsetT) flatbuffers.UOffsetT { destinationIdOffset := builder.CreateString("Server") offset := flatBuffers.CreateHeaderOffset(builder, destinationIdOffset, sensorIdOffset) return offset } </code></pre> </div>

为什么在MFC中使用线程会出现程序崩溃?是我实用的方法不敌还是怎么回事?

在使用MFC中使用的线程是 API函数,调用CreateThread(); 可是使用的时候调试一步一步走都是正常的,但是一起运行就发现程序崩溃。我是一个初学的菜鸟,可能是代码有点乱,麻烦看一下!!! 谢谢各位大佬: ``` // UDPserver.cpp : 实现文件 // #include "stdafx.h" #include "ServerUDP.h" #include "UDPserver.h" #include <Winsock2.h>//加裁头文件 #include <stdio.h>//加载标准输入输出头文件 #define IDP_SOCKETS_INIT_FAILED 103 SOCKET m_revSocket; // CUDPserver CUDPserver::CUDPserver() { } CUDPserver::~CUDPserver() { } // CUDPserver 成员函数 // Server 成员函数 bool CUDPserver::Socket()//初始化 { //初始化Winscok if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return 1; } // SetSockOpt(); WORD wVersionRequested;//版本号 WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 1, 1 );//1.1版本的套接字 err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return false; }//加载套接字库,加裁失败则返回 if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 ) { WSACleanup( ); return false; }//如果不是1.1的则退出 return true; } #include"Set_up.h" CSet_up up; bool CUDPserver::GetLocalAddress(){ CString strAddress; int nCardNo = 1; //PIP_ADAPTER_INFO结构体指针存储本机网卡信息 PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO(); //得到结构体大小,用于GetAdaptersInfo参数 unsigned long stSize = sizeof(IP_ADAPTER_INFO); //调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量;其中stSize参数既是一个输入量也是一个输出量 int nRel = GetAdaptersInfo(pIpAdapterInfo,&stSize); //记录网卡数量 int netCardNum = 0; //记录每张网卡上的IP地址数量 int IPnumPerNetCard = 0; if (ERROR_BUFFER_OVERFLOW == nRel) { //如果函数返回的是ERROR_BUFFER_OVERFLOW //则说明GetAdaptersInfo参数传递的内存空间不够,同时其传出stSize,表示需要的空间大小 //这也是说明为什么stSize既是一个输入量也是一个输出量 //释放原来的内存空间 delete pIpAdapterInfo; //重新申请内存空间用来存储所有网卡信息 pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize]; //再次调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量 nRel=GetAdaptersInfo(pIpAdapterInfo,&stSize); } if (ERROR_SUCCESS == nRel) { //输出网卡信息 //可能有多网卡,因此通过循环去判断 while (pIpAdapterInfo) { //可能网卡有多IP,因此通过循环去判断 IP_ADDR_STRING *pIpAddrString =&(pIpAdapterInfo->IpAddressList); switch(pIpAdapterInfo->Type) { case MIB_IF_TYPE_OTHER: case MIB_IF_TYPE_ETHERNET: case MIB_IF_TYPE_TOKENRING: case MIB_IF_TYPE_FDDI: case MIB_IF_TYPE_PPP: case MIB_IF_TYPE_LOOPBACK: case MIB_IF_TYPE_SLIP: { strAddress = pIpAddrString->IpAddress.String; // 需要注意的是有时可能获取的IP地址是0.0.0.0,这时需要过滤掉 if(CString("0.0.0.0")==strAddress) break; // std::cout<<_T("第")<< nCardNo<<_T("张网卡的IP地址是")<< strAddress<<std::endl; // long PID = _ttol(strAddress); //CString 转成 char*,该语句缺一不 // mxcj.m_strIP = (DWORD)PID; // 再强制转换成DWORD m_DIP= strAddress; nCardNo++; break; } default: // 未知类型网卡就跳出 break; } pIpAdapterInfo = pIpAdapterInfo->Next; } } //释放内存空间 if (pIpAdapterInfo) { delete pIpAdapterInfo; } //initsocket();//创建套接字 return true; } bool CUDPserver::initsocket() { /*创建套接字*/ //AF_INET表示IPv4,SOCK_STREAM数据传输方式,IPPROTO_TCP传输协议; m_listenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (m_listenSocket == INVALID_SOCKET) { //printf("套接字创建失败"); WSACleanup(); return 0; } Bind(); return true; } bool CUDPserver::Bind()// 绑定地址端口 { sockaddr_in addrListen; addrListen.sin_family = AF_INET; //指定IP格式 addrListen.sin_port = htons(m_iDKH); //绑定端口号 addrListen.sin_addr.S_un.S_addr = INADDR_ANY; //表示任何IP service.sin_addr.s_addr = inet_addr("127.0.0.1"); if (bind(m_listenSocket, (SOCKADDR*)&addrListen, sizeof(addrListen)) == SOCKET_ERROR) //(SOCKADDR*) { //printf("绑定失败"); closesocket(m_listenSocket); return 0; } Connect(); //连接开始监听 return true; } unsigned int WINAPI ThreadProFunc(void *pParam); bool CUDPserver::Connect() //连接 { /*开始监听*/ if (listen(m_listenSocket, 5) == SOCKET_ERROR) { //printf("监听出错"); closesocket(m_listenSocket); return 0; } /*等待连接,连接后建立一个新的套接字*/ //SOCKET revSocket; //对应此时所建立连接的套接字的句柄 //HANDLE hThread; // DWORD dwThreadId; //sockaddr_in remoteAddr; //接收连接到服务器上的地址信息 //int remoteAddrLen = sizeof(remoteAddr); //printf("等待连接...\n"); /*等待客户端请求,服务器接收请求*/ //m_revSocket = accept(m_listenSocket, (SOCKADDR*)&remoteAddr, &remoteAddrLen); //等待客户端接入,直到有客户端连接上来为止 /*if (m_revSocket == INVALID_SOCKET) { closesocket(m_listenSocket); WSACleanup(); return 0; } else { /* 启动等待连接线程 */ HANDLE acceptThread = CreateThread(NULL, 0, WaitAcceptThread, (LPVOID)m_listenSocket, 0, NULL); WaitForSingleObject(acceptThread, INFINITE); // 等待线程结束 // return 0; //} return true; } unsigned int WINAPI ThreadProFunc(void *pParam) { CUDPserver server; server.Receive(); char revData[255] = ""; while(1){ /*通过建立的连接进行通信*/ int res = recv(server.m_revSocket, revData, 255, 0); if (res > 0) { //printf("Bytes received: %d\n", res); // server.m_wndOutputBuild.AddString(_T("调试输出正显示在此处。")); //printf("客户端发送的数据: %s\n", revData); return 0; } //sleep(1000); return 0; } } UINT __cdecl CUDPserver::hellothread(LPVOID lparam){ CUDPserver server; server.Receive(); char revData[255] = ""; while(1){ /*通过建立的连接进行通信*/ int res = recv(server.m_revSocket, revData, 255, 0); if (res > 0) { //printf("Bytes received: %d\n", res); // server.m_wndOutputBuild.AddString(_T("调试输出正显示在此处。")); //printf("客户端发送的数据: %s\n", revData); return 0; } //sleep(1000); return 0; } } HANDLE bufferMutex; DWORD WINAPI WaitAcceptThread(LPVOID IpParameter) { SOCKET m_socket = (SOCKET)IpParameter; // int rval; sockaddr_in remoteAddr; //接收连接到服务器上的地址信息 int remoteAddrLen = sizeof(remoteAddr); while(true){ /*等待客户端请求,服务器接收请求*/ m_revSocket = accept(m_socket, (SOCKADDR*)&remoteAddr, &remoteAddrLen); //等待客户端接入,直到有客户端连接上来为止 if (m_revSocket == INVALID_SOCKET) { //printf("客户端发出请求,服务器接收请求失败:\n",WSAGetLastError()); closesocket(m_revSocket); WSACleanup(); return 0; } HANDLE receiveThread = CreateThread(NULL, 0, RecMsgThread, (LPVOID)m_revSocket, 0, NULL); WaitForSingleObject(bufferMutex, INFINITE); if(NULL == receiveThread) { //printf("\nCreatThread AnswerThread() failed.\n"); return 0; } ReleaseSemaphore(bufferMutex, 1, NULL); } } DWORD WINAPI RecMsgThread(LPVOID IpParameter) { SOCKET ClientSocket=(SOCKET)(LPVOID)IpParameter; int rval; while(1) { char recvBuf[1024]; rval = recv(ClientSocket, recvBuf, 1024, 0); WaitForSingleObject(bufferMutex, INFINITE); if (rval == SOCKET_ERROR) { // printf("ONE Client Exit\n"); // vector<SOCKET>::iterator result = find(clientSocketGroup.begin(), clientSocketGroup.end(), ClientSocket); // clientSocketGroup.erase(result); // for (map<SOCKET, string>::iterator i=m_ipSocket.begin(); i!=m_ipSocket.end(); i++) // { // if (i->first == ClientSocket) // { // printf("%s下线\n",m_ipSocket[ClientSocket].c_str()); // m_ipSocket.erase(i); // break; // } // } closesocket(ClientSocket); ReleaseSemaphore(bufferMutex, 1, NULL); break; } recvBuf; if(recvBuf[0] == -113){ if(recvBuf[0]== -1){ return 0; } } // printf("%s Says: %s\n", m_ipSocket[ClientSocket].c_str(), recvBuf); // 接收信息 Sleep(1000); ReleaseSemaphore(bufferMutex, 1, NULL); } return 0; } ```

关于C++ 文件夹资源PAK打包解包程序源码的问题求助!

// MakeFilePackDlg.cpp : 实现文件 // #include "stdafx.h" #include "MakeFilePack.h" #include "MakeFilePackDlg.h" #include "CJShell.h" #include ".\makefilepackdlg.h" #include <strstream> #include "../engine/include/engine.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CMakeFilePackDlg 对话框 CMakeFilePackDlg::CMakeFilePackDlg(CWnd* pParent /*=NULL*/) : CDialog(CMakeFilePackDlg::IDD, pParent) , m_strSrcPath(_T("")) , m_strPackExtName(_T("pak")) , m_bCompress(TRUE) , m_nZipLevel(6) , m_bEnc(TRUE) , m_bEncHeaderOnly(FALSE) , m_bDefaultPassword(TRUE) , m_strPassword(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMakeFilePackDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_strSrcPath); DDX_Text(pDX, IDC_EDIT2, m_strPackExtName); DDX_Check(pDX, IDC_CHECK1, m_bCompress); DDX_Text(pDX, IDC_EDIT3, m_nZipLevel); DDX_Control(pDX, IDC_SPIN1, m_wndSpinZipLevel); DDX_Check(pDX, IDC_CHECK2, m_bEnc); DDX_Control(pDX, IDC_EDIT3, m_wndEditZipLevel); DDX_Check(pDX, IDC_ENCHEADERONLY, m_bEncHeaderOnly); DDX_Check(pDX, IDC_DEFAULT_PASSWORD, m_bDefaultPassword); DDX_Text(pDX, IDC_PASSWORD, m_strPassword); } BEGIN_MESSAGE_MAP(CMakeFilePackDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_ADD_DIR, OnBnClickedAddDir) ON_BN_CLICKED(IDC_ADD_DIRS, OnBnClickedAddDirs) ON_BN_CLICKED(IDC_CLEAR_DIR, OnBnClickedClearDir) ON_BN_CLICKED(IDC_MAKEPACK, OnBnClickedMakepack) ON_BN_CLICKED(IDC_CHECK1, OnBnClickedCheck1) ON_BN_CLICKED(IDC_CHECK2, OnBnClickedCheck2) ON_BN_CLICKED(IDC_DEFAULT_PASSWORD, OnBnClickedDefaultPassword) ON_BN_CLICKED(IDC_EXPORTPACK, OnBnClickedExportpack) END_MESSAGE_MAP() // CMakeFilePackDlg 消息处理程序 class CMyCommandLineInfo : public CCommandLineInfo { public: bool bZip; bool bEnc; CString m_strPath; int m_iIndex; CMyCommandLineInfo() { m_iIndex = 0; bZip = false; bEnc = false; } void ParseParam( const char* pszParam, BOOL bFlag, BOOL bLast) { if(m_iIndex == 0) m_strPath = pszParam; else if(stricmp(pszParam,"enc") == 0) bEnc = true; else if(stricmp(pszParam,"zip") == 0) bZip = true; m_iIndex++; } }; BOOL CMakeFilePackDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将\“关于...\”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_wndEditZipLevel.EnableWindow(m_bCompress); m_wndSpinZipLevel.EnableWindow(m_bCompress); m_wndSpinZipLevel.SetRange32(0,9); CMyCommandLineInfo cmdLineInfo; AfxGetApp()->ParseCommandLine(cmdLineInfo); if(cmdLineInfo.m_iIndex > 0) { m_bEnc = cmdLineInfo.bEnc; m_bCompress = cmdLineInfo.bZip; m_strSrcPath =cmdLineInfo.m_strPath; UpdateData(FALSE); OnBnClickedMakepack(); PostMessage(WM_CLOSE); } return TRUE; // 除非设置了控件的焦点,否则返回 TRUE } void CMakeFilePackDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMakeFilePackDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标显示。 HCURSOR CMakeFilePackDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } static LPCTSTR GetBrowseFolder() { static CCJShell s_dlg; if(s_dlg.BrowseForFolder(AfxGetMainWnd())) { if(s_dlg.m_strPath.Right(1) == '\\') s_dlg.m_strPath.Delete(s_dlg.m_strPath.GetLength()-1,1); return s_dlg.m_strPath; } return NULL; } void CMakeFilePackDlg::OnBnClickedAddDir() { // TODO: 在此添加控件通知处理程序代码 LPCTSTR lpszDir; if(lpszDir = GetBrowseFolder()) { UpdateData(TRUE); if(m_strSrcPath.IsEmpty() || m_strSrcPath.Right(1) == _T('\n')) m_strSrcPath += lpszDir; else { m_strSrcPath += _T("\r\n"); m_strSrcPath += lpszDir; } UpdateData(FALSE); } } void CMakeFilePackDlg::OnBnClickedAddDirs() { // TODO: 在此添加控件通知处理程序代码 LPCTSTR lpszDir; if(lpszDir = GetBrowseFolder()) { CFileFind ff; CString strFind; strFind.Format(_T("%s\\*"),lpszDir); BOOL b = ff.FindFile(strFind); UpdateData(TRUE); m_strSrcPath = _T(""); while(b) { b = ff.FindNextFile(); if(ff.IsDirectory() && !ff.IsDots()) { TCHAR szDir[MAX_PATH]; _stprintf(szDir,_T("%s\\%s\r\n"),lpszDir,ff.GetFileName()); m_strSrcPath += szDir; } } UpdateData(FALSE); } } void CMakeFilePackDlg::OnBnClickedClearDir() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); m_strSrcPath = _T(""); UpdateData(FALSE); } void CMakeFilePackDlg::OnBnClickedMakepack() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); std::istrstream str(m_strSrcPath); if(m_strPackExtName.IsEmpty()) m_strPackExtName = _T("pak"); char szPath[MAX_PATH]; while(1) { szPath[0] = 0; str.getline(szPath,sizeof(szPath)); if(!szPath[0]) break; char* p = szPath + strlen(szPath)-1; while(p != szPath && (*p == '\r' || *p == '\n')) { *p = 0; --p; } char szPackName[MAX_PATH]; sprintf(szPackName,"%s.%s",szPath,m_strPackExtName); int nEnc = 0; if(m_bEnc) { if(m_bEncHeaderOnly) nEnc = 2; else nEnc = 1; } const char* pszPassword = NULL; if(m_bEnc) { if(!m_bDefaultPassword) pszPassword = m_strPassword; } std::vector<std::string> aFilter; BOOL bStop = FALSE; if(!PackAggregate::MakePackDir(szPath,szPackName,m_bCompress,nEnc,m_nZipLevel,pszPassword,aFilter,NULL,bStop,NULL)) { CString strMsg; strMsg.Format(_T("打包%s失败!"),szPath); AfxMessageBox(strMsg); } } } void CMakeFilePackDlg::OnBnClickedCheck1() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); m_wndEditZipLevel.EnableWindow(m_bCompress); m_wndSpinZipLevel.EnableWindow(m_bCompress); } void CMakeFilePackDlg::OnBnClickedCheck2() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); GetDlgItem(IDC_ENCHEADERONLY)->EnableWindow(m_bEnc); GetDlgItem(IDC_DEFAULT_PASSWORD)->EnableWindow(m_bEnc); GetDlgItem(IDC_PASSWORD)->EnableWindow(m_bEnc && (!m_bDefaultPassword)); } void CMakeFilePackDlg::OnBnClickedDefaultPassword() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); GetDlgItem(IDC_PASSWORD)->EnableWindow(m_bEnc && (!m_bDefaultPassword)); } void CMakeFilePackDlg::OnBnClickedExportpack() { // TODO: 在此添加控件通知处理程序代码 PackAggregate PakAggregate; BYTE des_key[3][8]; PasswordToDesKey( PackAggregate::GetDefaultPassword(),des_key[0],des_key[1],des_key[2] ); PakAggregate.SetDesKey((const BYTE*)des_key); **// 2010 3 Can't Use //PakAggregate.openAggregate( "test\\1.pak" ); //if (PakAggregate.openAggregate("test\\2.pak")) //{ // PakAggregate.tOutputFunc; //} //else //{ // 打开图形包失败 //Assert(0); // } ** } 把最后一段的//取消掉。程序编译的时候会报错,什么东西不能在右边的错误,求帮助,是不是这个代码不全?因为不取消掉最后一段的//,生成出来的程序能正常使用,但是无法解包,一并求解决!搞了一个通宵。没有办法了,求大神帮忙!

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

2020春招面试了10多家大厂,我把问烂了的数据库事务知识点总结了一下

2020年截止目前,我面试了阿里巴巴、腾讯、美团、拼多多、京东、快手等互联网大厂。我发现数据库事务在面试中出现的次数非常多。

程序员如何与产品经理优雅的干架

早前,平安产险科技一名外包程序员和一名外包产品经理干架的视频几乎在互联网圈都传遍了,因为产品提了一个需求:要求用户App的主题颜色能根据手机壳自动调整。 首先说这个需求对于应用开发工程师来说,确实是有点奇葩,当然并非不能实现。这块涉及图形图像处理,用机器学习和人工智能来提取图像颜色,这是基本图像识别过程,对于采集图像,可以提示对着镜子自拍一张,上传图片,通过大量的训练数据,来识别手机体颜色。当然并...

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

在拼多多上班,是一种什么样的体验?我心态崩了呀!

之前有很多读者咨询我:武哥,在拼多多上班是一种什么样的体验?由于一直很忙,没抽出时间来和大家分享。上周末特地花点时间来写了一篇文章,跟大家分享一下拼多多的日常。 1. 倒时差的作息 可能很多小伙伴都听说了,拼多多加班很严重。这怎么说呢?作息上确实和其他公司有点区别,大家知道 996,那么自然也就能理解拼多多的“11 11 6”了。 所以当很多小伙伴早上出门时,他们是这样的: 我们是这样的: 当...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

太狠了,疫情期间面试,一个问题砍了我5000!

疫情期间找工作确实有点难度,想拿到满意的薪资,确实要点实力啊!面试官:Spring中的@Value用过么,介绍一下我:@Value可以标注在字段上面,可以将外部配置文件中的数据,比如可以...

自学编程的 6 个致命误区

嗨,小伙伴们大家好,我是沉默王二。本篇文章来和大家聊聊自学编程中的一些误区——这是我在 B 站上看了羊哥的一期视频后有感而发的文章。因为确实有很多读者也曾私信问过我这些方面的问题,很有代表性,所以我就结合自己的亲身体会来谈一谈,希望对小伙伴们有所启发。 01、追求时髦 所谓基础不牢,地动山摇啊。可很多小伙伴压根就没注意过这个问题,市面上出什么新鲜的技术就想去尝试,结果把自己学的乱七八糟,心灰意冷...

安卓App太能乱来了!被曝一天扫你后台1.3万次:小米系统更新,一不小心扯出惊人真相...

晓查 乾明 发自 凹非寺量子位 报道 | 公众号 QbitAI安卓乱象,所有人都是知道的。但你知道到底有多乱么?现在,我们这些普通用户,也能定量分析检测了。真相,可能比想象中还严重。来看...

立即提问
相关内容推荐