【问题标题】:How to add structure to the STL list如何将结构添加到 STL 列表
【发布时间】:2012-10-30 16:47:11
【问题描述】:

我有一个这样的全局结构:-

struct MachineList
    {
    BSTR AccountId;
    BSTR MachineId;
    BSTR Make;
    char* Make1;
    BSTR Model;
    char* Model1;
    BSTR SerialNumber;
    BSTR IpAddress1;
    char* IpAddress;
    BSTR Port1;
    int Port;
    BSTR LocationCode;
    SOCKET Sock;
    BSTR Status;
} MACHINELIST,*PMACHINELIST;
int MachineCount=-1;

我有一个 XML,我对其进行解析并将其存储在如下结构中:- 我想添加通过解析填充到 stl 列表中的每个结构,所以我添加了以下代码

vector<struct  MACHINELIST > SS;

现在我收到以下错误:-

错误 C2371:'MACHINELIST':重新定义;不同的基本类型错误 C2512: 'MACHINELIST' : 没有合适的默认构造函数可用

int GetMachineList(char *Xmlpath)
{
    wLog->WriteDebugLog("Inside GetMachineList\n");
    try 
    {
        //Qualify namespase explicitly to avoid Compiler Error C2872 "ambiguous symbol" during linking.
        //Now Msxml2.dll use the "MSXML2" namespace
        //(see http://support.microsoft.com/default.aspx?scid=kb;en-us;316317):
        MSXML2::IXMLDOMDocumentPtr docPtr;//pointer to DOMDocument object
        MSXML2::IXMLDOMNodeListPtr NodeListPtr;//indexed access. and iteration through the collection of nodes
        MSXML2::IXMLDOMNodePtr DOMNodePtr;//pointer to the node

        MSXML2::IXMLDOMNode *pIDOMNode = NULL;//pointer to element's node
        MSXML2::IXMLDOMNode *pIParentNode = NULL;//pointer to parent node
        MSXML2::IXMLDOMNode *pIAttrNode = NULL;//pointer to attribute node
        MSXML2::IXMLDOMNamedNodeMapPtr DOMNamedNodeMapPtr;//iteration through the collection of attribute nodes
        MSXML2::IXMLDOMNodeList *childList=NULL;//node list containing the child nodes


        //Variable with the name of node to find: 
        BSTR strFindText  = L" ";//" " means to output every node

        //Variables to store item's name, parent, text and node type:
        BSTR bstrItemText,bstrItemNode, bstrItemParent,bstrNodeType;

        //Variables to store attribute's name,type and text:     
        BSTR bstrAttrName, bstrAttrType, bstrAttrText;

        HRESULT hResult;

        int i = 0;//loop-index variable
        int n = 0;//lines counter


        //Initialize COM Library:
        CoInitialize(NULL);

        //Create an instance of the DOMDocument object:
        docPtr.CreateInstance(__uuidof(DOMDocument30));

        // Load a document:
        _variant_t varXml(Xmlpath);//XML file to load//uncomment this
        _variant_t varResult((bool)TRUE);//result 

        varResult = docPtr->load(varXml);

        if ((bool)varResult == FALSE)
        {
            wLog->WriteErrorLog("failed to load XML file. Check the file name\n");
            printf("failed to load XML file. Check the file name\n");

            return 1;
        }

        //Collect all or selected nodes by tag name:
        NodeListPtr = docPtr->getElementsByTagName(strFindText);//original
        // NodeListPtr=   docPtr->documentElement->getElementsByTagName(strFindText) ;



        //Output the number of nodes:
        //printf("Number of nodes: %d\n", (NodeListPtr->length));

        //Output root node:
        docPtr->documentElement->get_nodeName(&bstrItemText);
        //%ls formatting is for wchar_t* parameter's type (%s for char* type):
        printf("\nRoot: %ls\n", bstrItemText);  



**PMACHINELIST MachineList;**



        for(i = 0; i < (NodeListPtr->length); i++)
        {

            if (pIDOMNode) pIDOMNode->Release();            
            NodeListPtr->get_item(i, &pIDOMNode);


            if(pIDOMNode )
            {               

                pIDOMNode->get_nodeTypeString(&bstrNodeType);

                //We process only elements (nodes of "element" type): 
                BSTR temp = L"element";

                if (lstrcmp((LPCTSTR)bstrNodeType, (LPCTSTR)temp)==0) 
                {
                    n++;//element node's number
                    printf("\n\n%d\n", n);//element node's number
                    printf("Type: %ls\n", bstrNodeType);

                    pIDOMNode->get_nodeName(&bstrItemNode);
                    if(0== wcscmp(bstrItemNode, L"ModuleSettings"))
                    {
                        isModuleSettings=TRUE;
                        //MS.account_id_name
                        printf("");
                    }


                    printf("Node: %ls\n", bstrItemNode);                
                    if(0== wcscmp(bstrItemNode, L"Machine"))
                    {
if(MachineCount++!=-1)
                        {
                            SS.push_back(MachineList);
                        }
                        //printf("value of count is %d\n",count);
                        count++;
                        //printf("value of count is %d\n",count);

                        isMachineList=TRUE;

                        **MachineList=new MACHINELIST;
                        MachineCount++;**
                        //MS.account_id_name

                    }
                    if(0== wcscmp(bstrItemNode, L"/Machine"))
                    {
                        printf("detected");
                    }
                    pIDOMNode->get_text(&bstrItemText);
                    printf("Text: %ls\n", bstrItemText);
                    if(isModuleSettings)//work here
                    {
                        if(0== wcscmp(bstrItemNode, L"capture_local_dir"))
                        {
                            CapturelocalDir=bstrItemText;
                            printf("CapturelocalDir is %ls\n",CapturelocalDir);
                        }
                        if(0== wcscmp(bstrItemNode, L"capture_log_dir"))
                        {
                            CapturelogDir=bstrItemText;
                            printf("CapturelogDir is %ls\n",CapturelogDir);
                        }
                        if(0== wcscmp(bstrItemNode, L"capture_log_level"))
                        {
                            CapturelogLevel=bstrItemText;
                            printf("CapturelogLevel is %ls\n",CapturelogLevel);
                        }
                        if(0== wcscmp(bstrItemNode, L"capture_request_interval"))
                        {
                            CapturerequestInterval=bstrItemText;
                            printf("CapturerequestInterval is %ls\n",CapturerequestInterval);
                        }
                        if(0== wcscmp(bstrItemNode, L"capture_connection_interval"))
                        {
                            CaptureConnectionInterval=bstrItemText;
                            printf("CaptureConnectionInterval is %ls\n",CaptureConnectionInterval);
                        }
                    }
                    if(isMachineList)
                    {
                    /*  PMACHINELIST MachineList;
                        MachineList=new MACHINELIST;*/


                        if(0== wcscmp(bstrItemNode, L"MachineId"))
                        {
                            m_LocalStorage.machinelist[count].MachineId=bstrItemText;
                            //MachineList.MachineId=bstrItemText;
                            MachineList->MachineId=bstrItemText;
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"IpAddress"))
                        {
                            m_LocalStorage.machinelist[count].IpAddress=bstrItemText;
                            m_LocalStorage.machinelist[count].IpAddress1=_com_util::ConvertBSTRToString(bstrItemText);
                            printf("ip address1 is %s\n",m_LocalStorage.machinelist[count].IpAddress1);
                            MachineList->IpAddress=_com_util::ConvertBSTRToString(bstrItemText);
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"Port"))
                        {
                            m_LocalStorage.machinelist[count].Port=bstrItemText;
                            m_LocalStorage.machinelist[count].Port1=_wtoi(bstrItemText);
                            MachineList->Port==_wtoi(bstrItemText);
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                            printf("port1 is %d\n",m_LocalStorage.machinelist[count].Port1);
                        }
                        if(0== wcscmp(bstrItemNode, L"Model"))
                        {
                            m_LocalStorage.machinelist[count].Model=bstrItemText;
                            m_LocalStorage.machinelist[count].Model1=_com_util::ConvertBSTRToString(bstrItemText);
                            MachineList->Model1=_com_util::ConvertBSTRToString(bstrItemText);
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"Make"))
                        {
                            m_LocalStorage.machinelist[count].Make=bstrItemText;
                            m_LocalStorage.machinelist[count].Make1=_com_util::ConvertBSTRToString(bstrItemText);
                            MachineList->Make1=_com_util::ConvertBSTRToString(bstrItemText);
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"SerialNumber"))
                        {
                            m_LocalStorage.machinelist[count].SerialNumber=bstrItemText;
                            MachineList->SerialNumber=bstrItemText;
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"AccountId"))
                        {
                            m_LocalStorage.machinelist[count].AccountId=bstrItemText;
                            MachineList->AccountId=bstrItemText;
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                        if(0== wcscmp(bstrItemNode, L"location_code"))
                        {
                            m_LocalStorage.machinelist[count].LocationCode=bstrItemText;
                            MachineList->LocationCode=bstrItemText;
                            //printf("Machine id is %ls\n",ML[count].MachineId);
                        }
                    }




                    //Get the attributes:
                    int j = 0;//loop-index variable
                    long length;// number of attributes in the collection

                    DOMNamedNodeMapPtr = pIDOMNode->attributes;

                    hResult = DOMNamedNodeMapPtr->get_length(&length);


                }
            }
        }

        //Do not forget to release interfaces:
        pIDOMNode->Release();
        pIDOMNode = NULL;
        //pIParentNode->Release();
        pIParentNode = NULL;


    } 

    catch(...)
    {
        wLog->WriteErrorLog("Exception occurred while parsing XML\n");

    }


    CoUninitialize();
        printf("value of machine count is %d",MachineCount);
    wLog->WriteDebugLog("Ends GetMachineList\n");
    return 0;


}

【问题讨论】:

    标签: c++ visual-studio-2010 list data-structures stl


    【解决方案1】:

    要声明任何类型的向量,您需要将类型作为模板参数传递。在你的情况下,类型是MachineList:

    vector<MachineList> SS;
    

    要添加实例,您可以使用例如push_back():

    SS.push_back(MACHINELIST); // add the MACHIHELIST instance
    SS.push_back(MachineList()); // add a default constructed MachineList.
    

    在您的代码中,MACHINELISTMachineList 类型的实例。

    响应 cmets 进行编辑:如果要存储指针,则需要一个指针向量:

    vector<MachineList*> SS;
    

    然后你可以这样添加条目:

    MachineList* m = new MachineList;
    SS.push_back(m);
    

    您有责任在适当的时候删除指针以释放动态分配的资源。我建议使用smart pointers 而不是原始的,但您的代码中存在更多基本问题。

    【讨论】:

    • 先生感谢您的回复,现在我想添加使用 new 创建的结构指针,所以我在上面的代码中执行了以下操作 if(0== wcscmp(bstrItemNode, L"Machine")) { if(MachineCount++!=-1) { SS.push_back(MachineList); } //printf("count 的值为 %d\n",count);计数++; //printf("count的值为%d\n",count); isMachineList=TRUE;机器列表=新机器列表;机器计数++; }我收到以下错误错误 C2664 cannot convert parameter 1 from 'PMACHINELIST' to 'MACHINELIST &&'
    • @Dany 不幸的是,指向 X 和 X 的指针并不相同,因此您不能将指向 MachineList 的指针插入到 vector&lt;MachineList&gt; 中。
    • 先生,我现在如何添加我使用 new 创建的结构?
    • @ juanchopanza 在这一行 MachineList* m = new MachineList;它说 m 未定义
    • 使用 List stl 我们如何获得列表的第一个节点我的意思是 stl 中是否有任何函数可以一个一个地获取节点
    【解决方案2】:

    试试:

    vector< MachineList > SS;
    

    MachineList 是您的结构的名称。 MACHINELIST 是结构的一个实例。 *PMACHINELIST 是指向此类结构的指针。

    【讨论】:

    • 先生感谢您的回复,现在我想添加使用 new 创建的结构指针,所以我在上面的代码中执行了以下操作 if(0== wcscmp(bstrItemNode, L"Machine")) { if(MachineCount++!=-1) { SS.push_back(MachineList); } //printf("count 的值为 %d\n",count);计数++; //printf("count的值为%d\n",count); isMachineList=TRUE;机器列表=新机器列表;机器计数++; }我收到以下错误错误 C2664 cannot convert parameter 1 from 'PMACHINELIST' to 'MACHINELIST &&' –
    • 感谢使用 List stl 的解决方案我们如何获得列表的第一个节点我的意思是 stl 中是否有任何功能可以一个一个地获取节点
    【解决方案3】:

    使用vector&lt;MachineList&gt;。当您使用struct MachineList { ... }; 声明时,它会创建一个类型MachineList,该类型已知是一个结构,并且不需要使用struct 作为前缀来使用它。

    在声明之后使用MACHINELIST,*PMACHINELIST 是C 风格的代码,没有必要。

    【讨论】:

    • 先生感谢您的回复,现在我想添加使用 new 创建的结构指针,所以我在上面的代码中执行了以下操作 if(0== wcscmp(bstrItemNode, L"Machine")) { if(MachineCount++!=-1) { SS.push_back(MachineList); } //printf("count 的值为 %d\n",count);计数++; //printf("count的值为%d\n",count); isMachineList=TRUE;机器列表=新机器列表;机器计数++; }我收到以下错误错误 C2664 cannot convert parameter 1 from 'PMACHINELIST' to 'MACHINELIST &&' –
    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2021-09-05
    • 2016-09-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多