[英]no match for ‘operator=’ using iterator for a vector
我正在开发一个Timer类,该类使用通用树来存储不同的处理时间。 该结构具有字符串和双精度变量,用于存储标签以及该“标签”所花费的时间(每个标签对应于某些实际过程)。 这是定义:
struct TimerNode
{
double time_value;
std::string name;
std::vector<TimerNode*> children;
TimerNode(){};
TimerNode(const std::string name): name(name){}
TimerNode& operator=(const TimerNode& other){//CopyAssignable
this->time_value=other.time_value; this->name=other.name;
return *this;}
TimerNode(const TimerNode& other){//CopyConstructible
this->time_value=other.time_value; this->name=other.name;}
}tree_;
该结构在计时器类中,它将使用它来维护每个过程所用时间的记录。 它还具有一个称为open_register的函数,该函数将在每次调用计时器时调用,并接收带有用户决定的标签名称的字符串(以标记不同的过程)。 然后,此功能将检查此标签之前是否已被使用过,以便将该过程的时间总计为先前使用的时间。 因此,它必须检查结构可能必须检查的每个孩子,并且我使用了迭代器,因为我将在std :: vector孩子内部进行搜索。 所以
TimerNode* actual_timer = &open_timers_.back(); //open_timers is a stack
std::vector<TimerNode>::iterator it;
for(*it=actual_timer->children.begin(); it != actual_timer->children.end(); ++it){
if(it->name == received_name){//we found it.
/*At this point we need to put the node associated with this
* into the stack and start counting because it is a child
* that was used before but stopped. So we will add the time
* expended this time to the value it already has.*/
open_timers_.push_back(*it);
break;
}
}
但是,在编译g ++时,在for行中抱怨说
../src/include/timer.h:73:46:错误:'it .__ gnu_cxx :: __ normal_iterator <_Iterator,_Container> :: operator *与_Iterator = const opice :: Global_Timer不匹配'operator =': :TimerNode *,_Container = std :: vector,__gnu_cxx :: ____ normal_iterator <_Iterator,_Container> :: reference = const opice :: Global_Timer :: TimerNode&= actual_timer-> opice :: Global_Timer :: TimerNode :: children.std ::: vector <_Tp,_Alloc> ::以_Tp = opice :: Global_Timer :: TimerNode *,_Alloc = std :: allocator,std :: vector <_Tp,_Alloc> :: iterator = __gnu_cxx :: __ normal_iterator>,类型名称std: :_Vector_base <_Tp,_Alloc> :: _ Tp_alloc_type :: pointer = opice :: Global_Timer :: TimerNode **'
我一直在寻找解决办法,我发现有些人喜欢这样 ,这似乎差不多我也有同样的问题,但它并没有解决这个问题,因为我有同样的错误。
我还看到了一些其他与匹配运算符有关的问题,但它们似乎与我的问题不太相似。 您能指出我在哪里犯错或在这里错过了什么吗? 我猜想它与重载运算符有关,但是我无法弄清楚如何在结构中重载=运算符以解决矢量迭代器的问题。 非常感谢你。
删除星号:
for(it=actual_timer->children.begin(); it != actual_timer->children.end(); ++it) {
*it = actual_timer->children.begin()
尝试分配actual_timer->children.begin()
到元素指向it
。 it
指向的元素本身不是迭代器,因此不是编译错误。 此外, it
还没有初始化,因此即使编译成功,访问它所指向的元素也会调用未定义的行为。
问题出在您的for
语句中,您在哪里写
*it=actual_timer->children.begin()
代替
it=actual_timer->children.begin()
您会收到一个编译错误,因为*it
意思是“取消引用名为it
的迭代器”,从而为您提供对TimerNode
的引用。 由于希望没有TimerNode::operator=(const std::vector<TimerNode>::iterator&)
,因此会出现错误。
另外,您正在取消引用未初始化的指针,因此,如果您编写*it = SomeTimerNode
,则不会有编译错误,但是您将被抛出未定义的行为域。
您将解引用运算符放到了it
前面; 要分配给迭代器,只需使用其变量,而不是其指向的元素即可。
vector<int> v { 1, 2, 3 };
auto it = v.begin();
cout << *it; // prints 1
it = v.begin() + 1;
cout << *it; // prints 2;
*it = 3;
cout << *it; // prints 3; v contains [1,3,3] now
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.