初始化包含自身向量的结构体

Initialising a struct that contains a vector of itself

本文关键字:结构体 向量 包含自 初始化      更新时间:2023-10-16

我有一个菜单系统,我想从常量数据初始化。MenuItem可以作为子菜单包含MenuItems的矢量。但它只在一定程度上起作用。以下是问题的概要:

#include <vector>
struct S { std::vector<S> v ; } ;
S s1 = { } ;
S s2 = { { } } ;
S s3 = { { { } } } ;

g++ -std=c++0x(版本4.4.5)应对s1s2,但s3回来了:

prog.cpp:6:22: error: template argument 1 is invalid

(见ideone)。我做错了什么吗?

GMan的评论是正确的:在你代码中的S::v声明中,S仍然是不完整的。类型必须是完整的,才能用作STL容器中的值类型。有关更多信息,请参阅Matt Austern的文章"标准图书管理员:不完整类型的容器"。

如果您要切换到可用于不完整类型的容器,那么您的代码就没问题。例如,给定以下内容:

#include <initializer_list>
template <typename T>
struct Container
{
    Container() { }
    Container(std::initializer_list<T>) { }
};
struct S { Container<S> v; };

,那么你的初始化应该可以正常工作:

S s3 = { { { } } } ;

这个也可以:

S s4 = { { { { { { { { { { { { { { { { /*zomg*/ } } } } } } } } } } } } } } } };

boost::optional和boost::recursive_wrapper看起来很有用

struct S { // one brace
    boost::optional< // another brace
      boost::recursive_wrapper< // another brace
        std::vector< // another brace
          S
        >
      >
    > v; 
};

添加的每个子菜单需要4个大括号。当涉及构造函数调用时,不需要省略大括号。例如

S m{{{{ 
  {{{{ }}}}, 
  {{{{ 
    {{{{ }}}}, 
    {{{{ }}}} 
  }}}} 
}}}}; 

老实说,使用构造函数看起来更可读

struct S {
    // this one is not really required by C++0x, but some GCC versions
    // require it.
    S(char const *s)
    :v(s) { } 
    S(std::string const& s)
    :v(s) { }
    S(std::initialize_list<S> s)
    :v(std::vector<S>(s)) { } 
    boost::variant<
      std::string,
      boost::recursive_wrapper<
        std::vector<
          S
        >
      >
    > v; 
};

现在简化为

S s{ 
  "S1", 
  {
    "SS1",
    "SS2",
    { "SSS1", "SSS2" }
  }
};

你正在尝试做的是一个即将到来的 c++当前特性,称为"初始化列表",其中向量或列表可以用={}初始化。我不知道他们是否在TR1中推出了它。可能是在TR2。

#include <vector>
#include <list>
#include <iostream>
using namespace std;
int main(void) {
    vector<int> vi = {1, 2, 3, 4, 5};
    list<int> li = {5, 4, 3, 2, 1, 0};
    cout<<"vector size="<<vi.size()<<", list size="<<li.size()<<endl;
    return 0;
}

你正在使用的代码在我看来不合适。如果你想实现包含结构(树)的结构,在节点中包含一个指向结构/节点的指针列表(如果无法实现,则只是void指针)。

大多数菜单结构本质上是一个有序的基于列表的树(一个地方有n个节点,但其他地方可能有m个节点,等等)。Robert Sedgewick编写了一本名为《c++中的算法》的教科书。

#include <vector>
#include <iterator>
#include <string>
void * pRoot = NULL; //pointer to CTree
class CTreenode;
class CTree;
class CTree {
    public:
        vector<class CTreeNode> lctnNodeList; //list does not have at() or operator[]
        vector<class CTreeNode>::iterator lctni;
    public:
        CTree() {}
        ~CTree() {
            for (lctni=lctnNodeList.begin(); lctni != lctnNodeList.end(); nctni++) {
                if (NULL==lctni->getChildPtr()) {
                    //do nothing, we have already done all we can
                } else {
                    delete (CTree *)lctnNodeList.pChild;
                }
                //do action here
            }
        }
        void addToList(string& data, CTree * p) { 
            CTreeNode ctn(data, p);
            lctnNodeList.push_back(d); 
        }
        void eraseAt(size_t index) { 
            vector<class CTreeNode>::iterator i = lctnNodeList.begin();
            vector<class CTreeNode>::iterator i2 = lctnNodeList.begin();
            i2++;
            size_t x;
            for (x=0; x <= index; x++,i++,i2++) {
                if (index == x) {
                    lctnNodeList.erase(i,i2);
                    break;
                }
            }
        }
        void at(size_t index, string& returndata, CTree * &p) { 
            vector<class CTreeNode>::iterator i = lctnNodeList.begin();
            size_t x;
            for (x=0; x <= index; i++,x++) {
                if (x==index) {
                     i->getData(returndata, p);
                     break;
                }
            }
        }
        const CTreeNode& operator[](const size_t idx) {
            if (idx < lctnNodeList(size)) {
                return lctnNodeList.at(idx);
            } else {
                //throw an error
            }
        }
        const size() {
            return lctnNodeList.size();
        }
        //this can be applied to the root of the tree (pRoot).
        doActionToThisSubtree(void * root) {
            CTree * pct = (CTree *)root;
            for (pct->lctni=pct->lctnNodeList.begin(); pct->lctni != pct->lctnNodeList.end(); pct->nctni++) {
                //this is a depth-first traversal.
                if (NULL==pct->lctni->getChildPtr()) {
                    //do nothing, we have already done all we can
                    //we do this if statement to prevent infinite recursion
                } else {
                    //at this point, recursively entering child domain
                    doActionToThisSubtree(pct->lctni->getChildPtr());
                    //at thisd point, exiting child domain
                }
                //do Action on CTreeNode node pct->lctni-> here.
            }
        }
};
class CTreeNode {
    public:
        CTree * pChild; //CTree *, may have to replace with void *
        string sData;
    public:
        CTreeNode() : pChild(NULL) {}
        CTreeNode(string& data, pchild) : pChild(pchild) {
            sData = data;
        }
        ~CTreeNode() { 
             if (NULL!=pChild) { 
                 delete pChild;//delete (CTree *)pChild; 
                 pChild = NULL; 
             }
        void getChild(CTreeNode& child) { 
            child = *pChild;//child = *((CTree *)pChild); 
        }
        bool addChild(string& s) { 
            if (NULL==pChild) {
                return false;
            } else {
                pChild = new CTree;
            }
            return true;
        }
        void * getChildPtr() { return pChild; }
        void getData(string& data, CTree * &p) { //not sure about how to put the & in there on CTree
            data=sData;
            p = pChild;
        }
        void setData(string& data, CTree * p) {
            sData=data;
            pChild = p;
        }
};

这里的问题是相互依赖,我认为我已经通过类声明解决了这个问题。做类CTreeNode;类CTree{}之前。http://www.codeguru.com/forum/showthread.php?t=383253

我可能弄乱了这段代码,而且它是不完整的,因为我已经很多年不需要编写树了,但我认为我已经涵盖了基本的内容。我没有实现operator[].