【问题标题】:writing the vector map to a file in Omnetpp将矢量地图写入 Omnetpp 中的文件
【发布时间】:2016-02-18 14:00:30
【问题描述】:

我在将矢量图写入文件时遇到问题。我想知道 wsmdata 中的详细值。我知道为了访问详细信息,我需要使用运算符重载,例如“std::ostream& operator

以下是部分代码: .h 文件: 使用 std::map;

typedef std::vector<WaveShortMessage*> WaveShortMessages;
std::map<long,WaveShortMessages>    receivedWarningMap;

.cc 文件:

// add warning message to received messages storage
 receivedWarningMap[wsm->getTreeId()].push_back(wsm->dup());
std::cout<<"Wsm dup() values/ receivedWarningMap="<<wsm->dup()<<endl;
std::ofstream tracefile;
tracefile.clear();
tracefile.open("traceFile1.txt", std::ios_base::app);
for (UINT i = 0; i < receivedWarningMap[wsm->getTreeId()].size(); i++)
        {
            std::cout << receivedWarningMap[wsm->getTreeId()][i] << std::endl;

            EV<< "MyID="<<getMyID()<< "Recepient ID"<<wsm->getRecipientAddress()<<"Neighbor ID="<< wsm->getSenderAddress()<< std::endl;

} 跟踪文件.close();

【问题讨论】:

  • 很难理解你的目标是什么。你能提供一个文件内容和一些伪代码的最小示例吗?

标签: c++ dictionary vector operator-overloading omnet++


【解决方案1】:

首先为你的类WaveShortMessage定义运算符&lt;&lt;,例如这样:

std::ostream & operator<<(std::ostream &os, WaveShortMessage * wsm) {
    os << "Recepient ID=" << wsm->getRecipientAddress() << "; ";
    os << "Neighbor ID=" << wsm->getSenderAddress() << "; ";
    // and any other fields of this class
    //...
    return os;
}

然后使用以下代码将地图写入文本文件:

// remember to add this two includes at the beginning:
// #include <fstream>
// #include <sstream> 

std::ofstream logFile;
logFile.open("log.txt"); // if exists it will be overwritten 
std::stringstream ss;
for (auto it = receivedWarningMap.begin(); it != receivedWarningMap.end(); ++it) {
    ss << "id=" << static_cast<int>(it->first) << "; wsms=";
    for (auto it2 : it->second) {
        ss << it2 << "; ";
    }
    ss << endl;
}
logFile << ss.str();
logFile.close();

【讨论】:

  • 谢谢 Jerzy D。它运作良好。我想知道如何将累积的消息重新广播到邻居节点。这里我们只是在文件中累积和输出,但我还想重新发送/广播累积的消息。我怎样才能做到这一点?
  • 您想将哪种结构发送给邻居? OMNeT++ 有机会在消息中使用自己的 C++ 结构,您的目标可能很容易实现。但是,根据 Stackoverflow 规则,您应该提出一个新问题,因为这个问题涉及到文件的写入。
  • 感谢您的建议。我会将这个问题作为一个新问题发布,希望尽快得到您的回复。
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多