因此,我有以下代码,在其中读取XML文件并将值保存到向量。我对矢量没有太多的经验,但是现在有了参数“ motor”,我希望能够获得一个motor值,并从该矢量中读取参数。
我是否必须在结构中添加一些内容?或初始化2D向量vector<vector <NameValue>> motors;
如果我确实初始化2D向量,我将如何填充该向量。还是有一个很好的指南可以帮助我完全理解向量?
这是TinyXML的文档。 http://www.grinninglizard.com/tinyxmldocs/index.html
#include <QCoreApplication>
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <tinyxml.h>
using namespace std;
struct NameValue
{
string motor;
string name;
string value;
};
vector<NameValue> read()
{ //READING XML FILE
QString directory;
string file;
directory = QCoreApplication::applicationDirPath();
file = directory.toUtf8().constData();
file = file + "/Profile.xml";
cout<<file<<endl;
TiXmlDocument doc (file);
if(!doc.LoadFile()){
cout<<"Cannot open file"<<endl;}
vector<NameValue> xmlread;
NameValue elem;
TiXmlElement *pRoot, *pParm, *pMotor;
pRoot = doc.FirstChildElement("PRO");
if (pRoot) //parsing
{
pMotor = pRoot->FirstChildElement("Motor");
if(pMotor){
while (pMotor)
{
elem.motor = pMotor->Attribute("value");
pParm = pMotor->FirstChildElement("PARAMETER");
while (pParm)
{
elem.name = pParm->Attribute("name");
elem.value = pParm->Attribute("value");
xmlread.push_back(elem);
pParm = pParm->NextSiblingElement("PARAMETER");
}
pMotor = pMotor->NextSiblingElement("Motor");
}
}
}
return xmlread;
}
int main (int argc, char *argv[])
{
vector<NameValue> elems = read();
cout<<elems[0].motor<<endl;
}
这是我的XML文件的一部分:
<PRO>
<Motor value = "1">
<PARAMETER name = "SPEED" value = "100" />
<PARAMETER name = "LOOP" value = "1" />
<PARAMETER name = "DEADBAND" value = "10" />
</Motor>
<Motor value = "2">
<PARAMETER name = "SPEED" value = "100" />
<PARAMETER name = "LOOP" value = "1" />
<PARAMETER name = "DEADBAND" value = "10" />
</Motor>
<Motor value = "3">
<PARAMETER name = "SPEED" value = "100" />
<PARAMETER name = "LOOP" value = "1" />
<PARAMETER name = "DEADBAND" value = "10" />
</Motor>
</PRO>
答案 0 :(得分:1)
您已经拥有的内容只需很少的修改即可生成2D向量。只需使用emplace_back
就地构建内部向量:
vector<vector<NameValue>> xmlread2D;
NameValue elem;
TiXmlElement *pRoot, *pParm, *pMotor;
pRoot = doc.FirstChildElement("PRO");
if (pRoot)
{
pMotor = pRoot->FirstChildElement("Motor");
while (pMotor)
{
// allocate new inner vector
xmlread2D.emplace_back();
auto& xmlread = xmlread2D.back();
// in C++17 the above can be replaced with a single line
// unmodified inner loop
elem.motor = pMotor->Attribute("value");
pParm = pMotor->FirstChildElement("PARAMETER");
while (pParm)
{
elem.name = pParm->Attribute("name");
elem.value = pParm->Attribute("value");
xmlread.push_back(elem);
pParm = pParm->NextSiblingElement("PARAMETER");
}
pMotor = pMotor->NextSiblingElement("Motor");
}
}