为结构向量创建C ++向量迭代器

时间:2018-04-03 01:26:12

标签: c++ vector struct types iterator

我在main()函数之外声明了一个结构(有一些运算符重载)。

我在main()中创建了一个struct的向量,然后通过引用另一个函数传递它。(node是struct)

best_patches = tf.gather_nd( patches, idx_best_patches, name = 'best_patches' )

我需要迭代向量。我试图使用迭代器,但在声明它时我收到错误。 (即时使用"使用命名空间std;")

void openInsert(vector<node> &vec, node node)//insert nodes in least to greatest

错误是:

vector<node>::iterator itr = vec.begin();

还:

 no suitable user-defined conversion from  
 "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<node>>>" to 
 "std::_Vector_iterator<std::_Vector_val<std::_Simple_types<<error-type>>>>" exists 

2 个答案:

答案 0 :(得分:0)

您的错误来自行

上的node node
void openInsert(vector<node> &vec, node node)//insert nodes in least to greatest

一般来说,拥有一个与变量同名的类型并不是一个好主意。如果编译器对您的类型是node还是node变量感到困惑,这可能导致难以调试此类问题。

常见(和最好)的做法是用大写字母开始你的类和结构名称。将node类型更改为Node会将问题行更改为

void openInsert(vector<Node> &vec, Node node)//insert nodes in least to greatest

应解决您的问题。

答案 1 :(得分:0)

如果following a naming convention的小写字母用于类名,则可以通过使用名称空间来避免名称冲突

#include <vector>

namespace mp{

class node{};

}

// when refering to the class, prefix with mp::
// when refering to a variable name, don't.
void foo(std::vector<mp::node>& vec, mp::node node){
    std::vector<mp::node>::iterator itr = vec.begin();
}

compilable example on ideone