自定义类型需要初始化程序来声明auto?

时间:2016-07-30 04:57:03

标签: c++ c++11 auto

我有这种类型:

  9 class Node {
 10         string name;
 11         int    dependencies;
 12         vector<Node*> children;
 13         unordered_map<string, Node*> map;
 14
 15
 16         public:
 17                 Node(string name) : name(name) {}
 18                 void decrementDependency() { dependencies--;}
 19                 void incrementDependency() { dependencies++;}
 20                 string getName() { return name; }
 21                 vector<Node*> getChildren() { return children; }
 22                 int getNumDependencies() { return dependencies; }
 23
 24                 void addDependent(Node* node) {
 25                         map[node->getName()] = node;
 26                         children.push_back(node);
 27                         node->incrementDependency();
 28                 }
 29 };

我试图在基于范围的循环中迭代vector<Node*>,如下所示:

 for (auto Node* node : children) {
      node->decrementDependency();
 }

但是,编译器会出现此错误error: declaration of variable 'Node' with type 'auto' requires an initializer

为什么会这样?是因为它是指向Node的指针的向量吗?

1 个答案:

答案 0 :(得分:2)

使用Node* nodeauto Node* node,而不是for (Node* node : children) { node->decrementDependency(); }

for (auto node : children) {
      node->decrementDependency();
}

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
    <input type="text" id="txtA" name="txtA">
    <input type="text" id="txtB" name="txtB">

    <button onclick="CheckVal()" type="button"> Check It </button>

        <script type="text/javascript">
            function CheckVal(){

                var count;//which needs to be compared with BValue
                var AValue = $("#txtA").val();
                var BValue = $("#txtB").val();

                 if (AValue == "") {
                            alert("Enter AValue and continue");
                        } else if (BValue  == "") {
                            alert("Enter To BValue and continue");
                        } else if (AValue  > BValue ) {
                            alert("AValue should be lesser than To BValue");
                        } else if (AValue == "" || BValue == "") {
                            alert("Please enter the AValue and BValue to continue");
                        } else if (AValue == "0") {
                            alert("Invalid AValue");
                        } else if (BValue  > count) {
                            alert("Invalid To Page Number");
                        } else {
                             // do some operations here
                             alert("This is Else Part");
                        }
                }
        </script>

    </body>
</html>
相关问题