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

12

我有一个菜单系统,想要从常量数据中初始化。一个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)。我做错了什么吗?


4
在标准库容器作为模板参数时,如果使用不完整的类型,则行为未定义。 - GManNickG
5
更多信息请参阅Matt Austern的《标准图书管理员:不完整类型的容器》。 - James McNellis
3个回答

11

GMan在他的评论中是正确的:在你的代码中声明S::v时,S仍然是不完全的。类型必须是完整的才能用作STL容器中的值类型。有关更多信息,请参见Matt Austern的文章“The Standard Librarian: Containers of Incomplete Types。”

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

#include <initializer_list>

template <typename T>
struct Container
{
    Container() { }
    Container(std::initializer_list<T>) { }
};

struct S { Container<S> v; };

那么您最初的初始化应该可以正常工作:

S s3 = { { { } } } ;
这也可以起作用:
S s4 = { { { { { { { { { { { { { { { { /*zomg*/ } } } } } } } } } } } } } } } };

这难道不是过于简化到荒谬的地步了吗?这不是“包含自身向量的结构体”,你也没有“切换到允许不完整类型的容器”……因为它们都不包含任何数据!这段代码什么也没存储,也什么也没做。在我看来,这与按值包含自身的对象的不可能性相当契合。 - underscore_d

6
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" }
  }
};

0

你要做的是 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;
        }
};

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

我可能会弄乱这段代码,并且它是不完整的,因为我多年来没有写过树,但我认为我已经涵盖了基础知识。我没有实现operator[]。


2
std::initialize_list<> 既是语言特性又是库特性,因此不能成为技术报告的一部分(即仅属于 C++0x)。 - ildjarn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接