我在c ++中有一个将节点添加到图结构的函数。例如:
auto n1 = g.node_insert("1");
节点的名称为“ 1”,它返回一个迭代器n1
。
我想在调用功能时将节点添加到图中。但是,根据计数器增加节点和返回的迭代器的名称。例如n1、1 .... n2、2 ... n3、3
我的问题是如何在函数中构造迭代器的名称,以使名称分别为n1,n2,n3等。
我已经尝试过,但是出现conflicting declaration ‘auto node’
错误。
int counter = 0;
void function() {
/*add node to the graph*/
counter++;
std::string node = "n" + std::to_string(counter);
auto node = OpListIterator.node_insert(std::to_string(counter));
}
答案 0 :(得分:1)
为什么不使用向量存储迭代器?
size_t const NUM_NODES = 32;
std::vector<Iterator_type> n(NUM_NODES);
for(size_t i = 0; i < NUM_NODES; i++)
{
n[i] = OpListIterator.node_insert(std::to_string(i));
}
//then access node i with n[i]
答案 1 :(得分:0)
但是根据计数器增加节点和返回的迭代器的名称。
变量名是您在源代码中编写的,在编译时将被丢弃。
您不能编写在运行时修改其自身源代码的代码(除非您将源代码与可执行文件一起发送并重新编译-这比您需要的要复杂得多)。
例如n1,1 .... n2,2 ... n3,
为什么不只是
std::vector<graph::iterator> make_n_nodes(graph &g, unsigned n)
{
std::vector<graph::iterator> v;
for (unsigned i = 0; i < n; ++n)
{
v.push_back(g.node_insert(i));
}
return v;
}
然后,您的节点被称为“ v[0]..v[n-1]
,节点v[0]
的标识符为0
。