将矢量地图写入Omnetpp中的文件

时间:2016-02-18 14:00:30

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

我在将矢量地图写入文件时遇到问题。我想知道wsmdata中的详细值。我知道为了访问详细信息我需要使用运算符重载,如“std :: ostream& amp;运算符<<(std :: ostream& os,map&);“在头文件和.cc文件中。但我不知道如何详细地使用它来访问矢量数据或输出文件中的矢量数据。我已经困在这个问题很长一段时间了。有人可以帮忙吗?

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

public static T Resolve<T>()
    {
        T ret = default(T);

        if (IsRegisteredInternal<T>())
        {
            ret = Container.Resolve<T>();
        }

        return ret;
    }

    private static bool IsRegisteredInternal<T>()
    {
        if (Container.IsRegistered<T>())
            return true;
        if (typeof(T).IsGenericType)
        {
            return Container.IsRegistered(typeof(T).GetGenericTypeDefinition());
        }
        return false;
    }

.cc文件:

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

}     tracefile.close();

1 个答案:

答案 0 :(得分:1)

首先为您的班级<<定义运算符WaveShortMessage,例如:

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();