簡體   English   中英

C ++如何從迭代器獲取向量中對象的地址

[英]c++ how to get address of an object in a vector from iterator

我有一個矢量vec,其中包含對象Order(不是指向對象的指針)

現在我需要在容器中找到某個對象並對其進行操作

for ( auto it = vec.begin(); it !=  vec.end(); ++it ) {

    Order *p_o = it; // ERROR HERE
    if ( p_o->id_ == id ) { p_o->size_ -= reduce_amount; }

}


error: C2440: 'initializing': cannot convert from 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Order>>>' to 'Order *'

我如何獲得迭代器持有的對象的地址

我都嘗試過

it.pointer
it.reference

但這產生了

C:\CPP\Simulator\Venue\venue.cpp:88: error: C2274: 'function-style cast': illegal as right side of '.' operator

迭代器為指針建模 ,但不一定是指針本身。 因此,只需取消引用它,如果您確實需要指向該對象,請獲取該對象的地址:

auto& my_ref_to_the_object = *iter;
auto* my_ptr_to_the_object = &my_ref_to_the_object;

您的代碼似乎根本不需要真正指向對象的指針:

for (auto it = vec.begin(); it !=  vec.end(); ++it) {
    Order& p_o = *it;
    if (p_o.id_ == id) {
        p_o.size_ -= reduce_amount;
    }
}

甚至更簡單:

for (Order& p_o : vec) {
    if (p_o.id_ == id) {
        p_o.size_ -= reduce_amount;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM