活动介绍
file-type

计算字符串编辑距离的C++算法实现

4星 · 超过85%的资源 | 下载需积分: 19 | 775B | 更新于2024-10-30 | 97 浏览量 | 15 下载量 举报 收藏
download 立即下载
编辑距离问题是计算机科学中一个经典的字符串匹配问题,它旨在确定将一个字符串转换成另一个字符串所需的最小操作次数。这个问题涉及到了三个基本操作:删除一个字符、插入一个字符以及替换一个字符。编辑距离(也称为Levenshtein距离)在文本处理、自然语言处理和生物信息学等领域有广泛应用,例如拼写检查、语音识别和基因序列比对等。 算法的核心思想是动态规划,通过构建一个二维数组来存储从字符串A的每个子串到字符串B相应子串的编辑距离。数组的行代表字符串A的长度,列代表字符串B的长度。从空字符串开始,逐步计算每个位置的编辑距离,直到遍历完整个字符串。 在给定的C++代码中,首先定义了两个字符串变量A1和A2,分别接收用户输入的字符串。接下来,初始化两个长度变量m和n,分别表示A1和A2的长度,以及创建一个大小为n+1的一维整型数组d,用于存储编辑距离。 算法主要分为两部分:首先初始化d数组,其中前n个元素设置为从1到n的递增值,这是因为将空字符串转换为前n个长度的B字符串至少需要从1到n的操作。然后,使用双层循环进行动态规划: 1. 外层循环遍历字符串A的每个字符(i从1到m),每次迭代代表在A中向后移动一位。 2. 内层循环遍历字符串B的每个字符(j从1到n),计算当前A子串到B子串的编辑距离。 - x表示不删除当前A字符的代价(即保留A的字符与B的字符相等时的代价)。 - y保存上一行(j-1)的最优值。 - z存储左上方单元格的最优值(如果j>1)。 - del表示当前字符是否相等,等于0则无需操作,否则需要1次删除操作。 更新d[j]的值,取x + del、y + 1和z + 1三者中的最小值作为当前位置的编辑距离。这样做的目的是寻找在当前状态下,从A到B的最优操作路径。 最终,输出d数组的最后一个元素d[n],即为字符串A到字符串B的编辑距离。在样例输入 "fxpimu" 和 "xwrs" 中,由于需要将 "fxpimu" 转换成 "xwrs",需要进行5次操作:删除 "f", 删除 "x", 插入 "w", 插入 "r", 替换 "u" 为 "s",因此输出为5。 总结,该编程任务实现了编辑距离问题的动态规划解决方案,通过逐个比较和调整字符串A和B的子串,找到最短的编辑路径,从而计算出两个字符串之间的编辑距离。这种算法效率较高,适用于实际应用中的字符串相似度计算。

相关推荐

filetype

给我一个完整的没有缩减的代码 ,完整这个题目。 【问题描述】 拼写纠错算法广泛应用于文本编辑工具、自然语言处理工具、搜索引擎及其它基于字符输入的检索系统。以下是一个基于词汇间固定搭配来纠错拼写的算法描述。请实现该算法,完成给定文件中错误单词的识别及替换词推荐任务。 拼写纠错算法: 1. 单词读入:逐个读入文件in.txt中的单词(仅由连续英文字母组成),并将所有单词转换为小写以进行统一处理。 注意:对于缩略词,例如it's, 处理时将单引号去掉,转换为"it"与"s"两个词。 2. 错误单词识别:与给定的词典文件dict.txt中的单词匹配来识别错误单词。如果一个单词不在dict.txt文件中,则认定为拼写错误。 3. 修正单词推荐: a) 在自然语言处理中,一个2-gram(bigram)是指由两个连续的单词组成的序列。序列的连续性会在遇到标点符号或其它非字母字符时终止(空格' '和横向制表符'\t'除外)。例如,句子“look, the quick brown fox.”的2-grams包括:(the, quick),(quick, brown),和(brown, fox)。由于逗号分隔,词look不与后续词构成2-gram。 b) 当出现拼写错误的单词是某个2-gram中的第二个单词时(假设前一个单词是正确的),查找整个文件中所有首个单词相同的正确的2-grams,并从中选择第二个单词与错误单词具有最小编辑距离的2-gram作为修正建议。如果存在多个编辑距离最小的候选修正词,则按字典序输出这些单词。所谓正确2-gram,是指不含错误拼写单词的2-gram。最小编辑距离可以通过调用给定的editdistDP.c中的editdistDP函数计算得到。 c) 如果按上述方法找不到修正词(没有参考的2-gram,即正确句子中不含与出错2-gram首个单词相同的2-gram),则输出:“No suggestion“。 d)如果一个句子的第一个单词是错误单词,或者错误单词前面的单词也是错误单词,则忽略该错误单词(不做任何处理,没有任何输出)。 【输入形式】 需要进行拼写纠错的文件为in.txt,词典文件为dict.txt(其中每行一个单词,按照字典序存放)。 【输出形式】 向控制台输出结果。按出错单词在文中首次出现次序依次按行列出出错单词及修改建议。要求: 1. 每行一个出错单词及修正结果信息,格式为前缀词+英文冒号+空格+出错词+空格+->+空格+修正词列表。 2. 当有多个修正词时,修正词用逗号分隔,并按字典序排列。 3. 如果一个出错单词没有可推荐的修正词,则在修正词的位置输出“No suggestion”。即前缀词+英文冒号+空格+出错词+空格+->+空格+No suggestion 注意:只有出错单词以及前面的正确单词都相同的,才算相同的出错单词!相同的出错单词的修正结果只输出一次! 【样例输入】 课程平台下载区文件“project2025.zip”中包含了in.txt, dict.txt和editdistDP.C等与作业实现相关的文件。in.txt是要进行错误单词识别和纠正的样例文本文件,dict.txt为关键词列表(每行一个词),editdistDP.c为一种计算编辑距离算法的实现代码。 【样例输出】 data: structurs -> structure,structures 【样例说明】 structurs为出错单词,structure,structures两个词在in.txt文件中存在于data structure, data structures 2-gram中,与出错单词所在2-gram data structures,满足第一个单词data相同,且structure和structures 与出错单词编辑距离最小,为1. 输出按字典序structure在前,structures在后。

filetype

//RuledFaces // Std C++ Includes #include <iostream> #include <sstream> #include <algorithm> #include <fstream> #include "RuledFaces.h" using namespace NXOpen; using namespace std; //ofstream fout("D:\\D:\NXopen\BaiduSyncdisk\studio\zhinengguodu\\res.txt"); //============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\FXM\Documents\nx_customized\23-RuledFaces\RuledFaces.cpp // // This file was generated by the NX Block UI Styler // Created by: MIC-明 // Version: NX 2212 // Date: 07-17-2025 (Format: mm-dd-yyyy) // Time: 14:33 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C++ source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session* (RuledFaces::theSession) = NULL; UI* (RuledFaces::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ RuledFaces::RuledFaces() { try { // Initialize the NX Open C++ API environment RuledFaces::theSession = NXOpen::Session::GetSession(); RuledFaces::theUI = UI::GetUI(); workPart = theSession->Parts()->Work(); mb = theUI->NXMessageBox(); lw = theSession->ListingWindow(); lf = theSession->LogFile(); theDlxFileName = "RuledFaces.dlx"; theDialog = RuledFaces::theUI->CreateDialog(theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &RuledFaces::apply_cb)); theDialog->AddOkHandler(make_callback(this, &RuledFaces::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &RuledFaces::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &RuledFaces::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &RuledFaces::dialogShown_cb)); } catch (exception& ex) { //---- Enter your exception handling code here ----- throw; } } //------------------------------------------------------------------------------ // Destructor for NX Styler class //------------------------------------------------------------------------------ RuledFaces::~RuledFaces() { if (theDialog != NULL) { delete theDialog; theDialog = NULL; } } //------------------------------------------------------------------------------ // Print string to listing window or stdout //------------------------------------------------------------------------------ void RuledFaces::print(const NXString& msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } void RuledFaces::print(const string& msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } void RuledFaces::print(const char* msg) { if (!lw->IsOpen()) lw->Open(); lw->WriteLine(msg); } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char* param, int* retcod, int param_len) { RuledFaces* theRuledFaces = NULL; try { theRuledFaces = new RuledFaces(); // The following method shows the dialog immediately theRuledFaces->Launch(); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if (theRuledFaces != NULL) { delete theRuledFaces; theRuledFaces = NULL; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- Enter your callback code here ----- } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //This method launches the dialog to screen //------------------------------------------------------------------------------ NXOpen::BlockStyler::BlockDialog::DialogResponse RuledFaces::Launch() { NXOpen::BlockStyler::BlockDialog::DialogResponse dialogResponse = NXOpen::BlockStyler::BlockDialog::DialogResponse::DialogResponseInvalid; try { dialogResponse = theDialog->Launch(); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return dialogResponse; } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ void RuledFaces::initialize_cb() { try { group0 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group0")); colorPicker0 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker0")); colorPicker01 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker01")); bodySelect0 = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("bodySelect0")); separator0 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator0")); group = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group")); face_select0 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select0")); face_select01 = dynamic_cast<NXOpen::BlockStyler::FaceCollector*>(theDialog->TopBlock()->FindBlock("face_select01")); separator01 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator01")); colorPicker02 = dynamic_cast<NXOpen::BlockStyler::ObjectColorPicker*>(theDialog->TopBlock()->FindBlock("colorPicker02")); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any value set //here will take precedence and dialog will be launched showing that value. //------------------------------------------------------------------------------ void RuledFaces::dialogShown_cb() { try { //---- Enter your callback code here ----- group->SetEnable(false); group->SetShow(false); face_select0->SetEnable(false); face_select0->SetShow(false); face_select01->SetEnable(false); face_select01->SetShow(false); } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ int RuledFaces::apply_cb() { int errorCode = 0; try { //---- Enter your callback code here ----- NXOpen::Session::UndoMarkId markId1; markId1 = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "RuledFaces"); do_it(); } catch (exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ int RuledFaces::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { if (block == colorPicker0) { //---------Enter your code here----------- } else if (block == colorPicker01) { //---------Enter your code here----------- } else if (block == bodySelect0) { //---------Enter your code here----------- } else if (block == separator0) { //---------Enter your code here----------- } else if (block == face_select0) { //---------Enter your code here----------- } else if (block == face_select01) { //---------Enter your code here----------- } else if (block == separator01) { //---------Enter your code here----------- } else if (block == colorPicker02) { //---------Enter your code here----------- } } catch (exception& ex) { //---- Enter your exception handling code here ----- RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ int RuledFaces::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); } catch (exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; RuledFaces::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Description: Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ PropertyList* RuledFaces::GetBlockProperties(const char* blockID) { return theDialog->GetBlockProperties(blockID); } bool RuledFaces::isEqualXY(const Point3d& a1, const Point3d& a2, const Point3d& b1, const Point3d& b2, double eps = 1e-3) { auto equalXY = [&](const Point3d& p1, const Point3d& p2) { return std::fabs(p1.X - p2.X) < eps && std::fabs(p1.Y - p2.Y) < eps; }; return (equalXY(a1, b1) && equalXY(a2, b2)) || (equalXY(a1, b2) && equalXY(a2, b1)); } Features::Ruled* RuledFaces::doCreateRuledFace(Edge* edge1, Edge* edge2) { NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); NXOpen::Features::RuledBuilder* ruledBuilder1; ruledBuilder1 = workPart->Features()->CreateRuledBuilder(nullNXOpen_Features_Feature); ruledBuilder1->SetPositionTolerance(0.001); ruledBuilder1->SetShapePreserved(false); ruledBuilder1->FirstSection()->SetDistanceTolerance(0.001); ruledBuilder1->FirstSection()->SetChainingTolerance(0.00095); ruledBuilder1->SecondSection()->SetDistanceTolerance(0.001); ruledBuilder1->SecondSection()->SetChainingTolerance(0.00095); ruledBuilder1->AlignmentMethod()->AlignCurve()->SetDistanceTolerance(0.001); ruledBuilder1->AlignmentMethod()->AlignCurve()->SetChainingTolerance(0.00095); ruledBuilder1->FirstSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesCurvesAndPoints); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); std::vector<NXOpen::Edge*> edges1(1); edges1[0] = edge1; NXOpen::EdgeDumbRule* edgeDumbRule1; edgeDumbRule1 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges1, selectionIntentRuleOptions1); ruledBuilder1->FirstSection()->AllowSelfIntersection(true); ruledBuilder1->FirstSection()->AllowDegenerateCurves(false); std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = edgeDumbRule1; NXOpen::NXObject* nullNXOpen_NXObject(NULL); NXOpen::Point3d helpPoint1(0, 0, 0); ruledBuilder1->FirstSection()->AddToSection(rules1, edge1, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint1, NXOpen::Section::ModeCreate, false); ruledBuilder1->SecondSection()->SetAllowedEntityTypes(NXOpen::Section::AllowTypesOnlyCurves); std::vector<NXOpen::Edge*> edges2(1); edges2[0] = edge2; NXOpen::EdgeDumbRule* edgeDumbRule2; edgeDumbRule2 = workPart->ScRuleFactory()->CreateRuleEdgeDumb(edges2, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; ruledBuilder1->SecondSection()->AllowSelfIntersection(true); ruledBuilder1->SecondSection()->AllowDegenerateCurves(false); std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = edgeDumbRule2; NXOpen::Point3d helpPoint2(0, 0, 0); ruledBuilder1->SecondSection()->AddToSection(rules2, edge2, nullNXOpen_NXObject, nullNXOpen_NXObject, helpPoint2, NXOpen::Section::ModeCreate, false); std::vector<NXOpen::Section*> sections1(2); sections1[0] = ruledBuilder1->FirstSection(); sections1[1] = ruledBuilder1->SecondSection(); ruledBuilder1->AlignmentMethod()->SetSections(sections1); NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); Features::Ruled* ruled1(dynamic_cast<NXOpen::Features::Ruled*>(nXObject1)); try { Body* body = ruled1->GetBodies()[0]; //std::vector<NXOpen::DisplayableObject*> objsTobeBlanked(1); //objsTobeBlanked[0] = body; //theSession->DisplayManager()->BlankObjects(objsTobeBlanked); //workPart->ModelingViews()->WorkView()->FitAfterShowOrHide(NXOpen::View::ShowOrHideTypeHideOnly); body->SetLayer(254); workPart->ModelingViews()->WorkView()->UpdateDisplay(); } catch (const std::exception& ew) { print(ew.what()); } if (!ruled1->GetFaces().empty() && dynamic_cast<Face*>(ruled1->GetFaces()[0]) != nullptr) { return ruled1; } return nullptr; } bool RuledFaces::doReplaceFace(Face* origin_face, Face* replace_face) { if (origin_face == nullptr || replace_face == nullptr) { print("error"); return 0; } origin_face->SetColor(_transitioned_face_color); NXOpen::Features::Feature* nullNXOpen_Features_Feature(NULL); NXOpen::Features::ReplaceFaceBuilder* replaceFaceBuilder1; replaceFaceBuilder1 = workPart->Features()->CreateReplaceFaceBuilder(nullNXOpen_Features_Feature); replaceFaceBuilder1->OffsetDistance()->SetFormula("0"); replaceFaceBuilder1->ResetReplaceFaceMethod(); replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions1; selectionIntentRuleOptions1 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions1->SetSelectedFromInactive(false); std::vector<NXOpen::Face*> faces1(1); faces1[0] = origin_face; NXOpen::FaceDumbRule* faceDumbRule1; faceDumbRule1 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces1, selectionIntentRuleOptions1); delete selectionIntentRuleOptions1; std::vector<NXOpen::SelectionIntentRule*> rules1(1); rules1[0] = faceDumbRule1; replaceFaceBuilder1->FaceToReplace()->ReplaceRules(rules1, false); replaceFaceBuilder1->ResetReplaceFaceMethod(); replaceFaceBuilder1->ResetFreeEdgeProjectionOption(); NXOpen::SelectionIntentRuleOptions* selectionIntentRuleOptions2; selectionIntentRuleOptions2 = workPart->ScRuleFactory()->CreateRuleOptions(); selectionIntentRuleOptions2->SetSelectedFromInactive(false); std::vector<NXOpen::Face*> faces2(1); faces2[0] = replace_face; NXOpen::FaceDumbRule* faceDumbRule2; faceDumbRule2 = workPart->ScRuleFactory()->CreateRuleFaceDumb(faces2, selectionIntentRuleOptions2); delete selectionIntentRuleOptions2; std::vector<NXOpen::SelectionIntentRule*> rules2(1); rules2[0] = faceDumbRule2; replaceFaceBuilder1->ReplacementFaces()->ReplaceRules(rules2, false); replaceFaceBuilder1->SetReverseDirection(false); replaceFaceBuilder1->OnApplyPre(); NXOpen::NXObject* nXObject1 = nullptr; try { nXObject1 = replaceFaceBuilder1->Commit(); } catch (const std::exception&) { replaceFaceBuilder1->SetReverseDirection(true); try { nXObject1 = replaceFaceBuilder1->Commit(); } catch (const std::exception&) { origin_face->SetColor(_transitional_face_color); } } NXOpen::Expression* expression1(replaceFaceBuilder1->OffsetDistance()); replaceFaceBuilder1->Destroy(); if (nXObject1 == nullptr) return false; return true; } bool RuledFaces::ifContainEqulaEdge(Edge* origin_edge, EdgeSet& edge_set, Edge*& res_edge) { res_edge = nullptr; if (!origin_edge) return false; Point3d origin_edge_p1, origin_edge_p2; origin_edge->GetVertices(&origin_edge_p1, &origin_edge_p2); for (auto it = edge_set.begin(); it != edge_set.end(); ) { if (*it) { Point3d tmp_edge_p1, tmp_edge_p2; (*it)->GetVertices(&tmp_edge_p1, &tmp_edge_p2); if (isEqualXY(origin_edge_p1, origin_edge_p2, tmp_edge_p1, tmp_edge_p2)) { res_edge = (*it); edge_set.erase(it); // 正确删除并获取下一个迭代器 return true; } else { ++it; } } else { it = edge_set.erase(it); // 移除空指针 } } return false; } vector<Body*> RuledFaces::getBodies() { //std::vector<Body*> bodies; //bodies.clear(); //int num = UI::GetUI()->SelectionManager()->GetNumSelectedObjects(); //for (int i = 0; i < num; i++) //{ // TaggedObject* obj = UI::GetUI()->SelectionManager()->GetSelectedTaggedObject(i); // Body* body = dynamic_cast<Body*>(obj); // if (body != nullptr) { // bodies.push_back(body); // } //} std::vector<TaggedObject*> tagged_objs = bodySelect0->GetSelectedObjects(); std::vector<Body*> bodies; std::for_each(tagged_objs.begin(), tagged_objs.end(), [&](TaggedObject* obj) { Body* body = dynamic_cast<Body*>(obj); if (body) bodies.push_back(body); }); return bodies; } void RuledFaces::getFixedAndTransitionalFaces(const vector<Body*>& bodies, vector<Face*>& fixed_faces, vector<Face*>& transitional_faces) { for (auto body : bodies) { vector<Face*> faces = body->GetFaces(); std::for_each(faces.begin(), faces.end(), [&](Face* face) { if (face->Color() == _fixed_face_color) fixed_faces.push_back(face); else if (face->Color() == _transitional_face_color) transitional_faces.push_back(face); }); } //face_select0->SetSelectedObjects(vector<TaggedObject*>(fixed_faces.begin(), fixed_faces.end())); //face_select01->SetSelectedObjects(vector<TaggedObject*>(transitional_faces.begin(), transitional_faces.end())); } EdgeSet RuledFaces::getFixedEdgeSet(const vector<Face*>& fixed_faces) { EdgeSet edge_set; for (auto fixed_face : fixed_faces) { vector<Edge*> edges = fixed_face->GetEdges(); for_each(edges.begin(), edges.end(), [&](Edge* edge) { edge_set.insert(edge); }); } return edge_set; } //------------------------------------------------------------------------------ // Do something //------------------------------------------------------------------------------ void RuledFaces::do_it() { // TODO: add your code here _fixed_face_color = colorPicker0->GetValue()[0]; _transitional_face_color = colorPicker01->GetValue()[0]; _transitioned_face_color = colorPicker02->GetValue()[0]; vector<Body*> bodies = getBodies(); vector<Face*> fixed_faces, transitional_faces; getFixedAndTransitionalFaces(bodies, fixed_faces, transitional_faces); EdgeSet fixed_edges = getFixedEdgeSet(fixed_faces); for (auto transitional_face : transitional_faces) { vector<Edge*> trans_edges = transitional_face->GetEdges(); vector<Edge*> rule_edges; rule_edges.clear(); for (auto trans_edge : trans_edges) { if (!trans_edge) continue; Edge* found_edge = nullptr; bool res = false; res = ifContainEqulaEdge(trans_edge, fixed_edges, found_edge); if (res) rule_edges.push_back(found_edge); } if (rule_edges.size() != 2) { continue; } Edge* edge1 = rule_edges[0]; Edge* edge2 = rule_edges[1]; Features::Ruled* ruled = doCreateRuledFace(edge1, edge2); if (ruled == nullptr) { print("error"); continue; } Face* ruled_face = ruled->GetFaces()[0]; bool res = doReplaceFace(transitional_face, ruled_face);; if (!res) { tryReverseRuledDirection(ruled); res = doReplaceFace(transitional_face, ruled_face); } } } bool RuledFaces::tryReverseRuledDirection(Features::Ruled* ruled_face) { if (ruled_face == nullptr) return nullptr; NXOpen::Session::UndoMarkId markId; markId = theSession->SetUndoMark(NXOpen::Session::MarkVisibilityVisible, "Redefine Feature"); NXOpen::Features::EditWithRollbackManager* editWithRollbackManager1; editWithRollbackManager1 = workPart->Features()->StartEditWithRollbackManager(ruled_face, markId); NXOpen::Features::RuledBuilder* ruledBuilder1; ruledBuilder1 = workPart->Features()->CreateRuledBuilder(ruled_face); ruledBuilder1->SecondSection()->ReverseDirectionOfLoop(0); ruledBuilder1->AlignmentMethod()->UpdateSectionAtIndex(1); NXOpen::NXObject* nXObject1; nXObject1 = ruledBuilder1->Commit(); ruledBuilder1->Destroy(); editWithRollbackManager1->UpdateFeature(false); editWithRollbackManager1->Stop(); editWithRollbackManager1->Destroy(); }

yhw330738537
  • 粉丝: 0
上传资源 快速赚钱