C++ 测试迭代器是否是列表中的最后一个

C++ 测试迭代器是否是列表中的最后一个,c++,c++17,C++,C++17,我创建了这个迭代器来遍历端口列表。我想给每个端口添加逗号,但最后一个端口除外。为此,我想我可以测试it==(verilogPorts.end()-1),它似乎可以工作 我应该使用VerilogPort.size()还是verilogPorts.end()以外的东西-1? 似乎-1是一个潜在的问题 for (std::list<VerilogPort>::iterator it = verilogPorts.begin(); it != verilogPorts.end(); ++i

我创建了这个迭代器来遍历端口列表。我想给每个端口添加逗号,但最后一个端口除外。为此,我想我可以测试
it==(verilogPorts.end()-1)
,它似乎可以工作

我应该使用VerilogPort.size()还是verilogPorts.end()以外的东西-1?
似乎-1是一个潜在的问题

 for (std::list<VerilogPort>::iterator it = verilogPorts.begin(); it != verilogPorts.end(); ++it) {
        add_comma = (it == (verilogPorts.end() - 1));
        if (port_section != "") {
            port_section = port_section + "/n";
        }
        port_section = port_section  + it->get_port_string_and_comment(add_comma);
    } 
for(std::list::iterator it=verilogPorts.begin();it!=verilogPorts.end();++it){
添加逗号=(它=(verilogPorts.end()-1));
如果(端口_部分!=“”){
port_section=port_section+“/n”;
}
port\u section=port\u section+it->get\u port\u string\u和\u comment(添加\u逗号);
} 

好,使用距离函数像这样求解。相对于上面关于不编译的评论。我验证了Makefile有问题,错误发生后留下了一个过时的可执行文件。我真的不知道这是不是一个“好”的解决办法

for (std::list<VerilogPort>::iterator it = verilogPorts.begin(); it != verilogPorts.end(); ++it) {
            add_comma = (std::distance(it, verilogPorts.end()) != 1);
            if (port_section != "") {
                port_section = port_section + "\n";
            }
            port_section = port_section  + it->get_port_string_and_comment(add_comma);
        }
for(std::list::iterator it=verilogPorts.begin();it!=verilogPorts.end();++it){
添加逗号=(std::distance(it,verilogPorts.end())!=1);
如果(端口_部分!=“”){
端口\段=端口\段+“\n”;
}
port\u section=port\u section+it->get\u port\u string\u和\u comment(添加\u逗号);
}

定义“似乎有效”。它绝对不应该编译。我想我这里有一个更大的问题。这些类型甚至不匹配。但它确实编译了。也许我也有生成文件的问题。让我再戳一戳……如果你不在开头,你也可以先加逗号,而不是最后加逗号。这要容易得多:
if(it!=verilogPort.begin())port_section+=“,”;port_section+=it->get_port_string_和_comment()我首先尝试了,这就是我成功编译的原因,但是输出的格式是这样的:输入一些端口名称,//一些注释。所以逗号在注释之前。当我按照您的建议实现它时,逗号出现在注释后面,这是错误的,并导致Verilog编译器抛出错误。