簡體   English   中英

獲取指向列表中元素的指針

[英]Getting pointer to element in a list

我有一個完整的struct account列表。

我想從函數中返回類型為account*的指針。 怎么做呢?

account* find_account(int ID){
    for (list<account>::iterator i = accounts_database.begin; i != accounts_database.end; i++ ){
        if (i->id==ID)
            return &(*(i));
    }
    else return NULL; 
}

這行不通...知道從迭代器獲取account*的正確方法是什么?

您忘記了beginend后面的() 同樣使用C ++ 11樣式,我將這樣編寫代碼,看起來好多了。

account* find_account(int ID)
{
    for ( auto & elem : accounts_database )
        if ( elem.id == ID )
            return &elem;
    return nullptr;
}
#include "stdafx.h"

#include<iostream>
#include<conio.h>
#include <list>
#include<iomanip>
using namespace std;


struct account
{
    int id;
    string name;
};
account* find_account(int);
account* find_account(int ID)
 {
    list<account*> accounts_database;
    account* a1,*a2;
    a1= new account();
    a2= new account();
    a1->id = 10;
    a1->name = "C++";
    a2->id = 30;
    a2->name = "Java";
    account* result_found= new account();
    accounts_database.push_back(a1);
    accounts_database.push_back(a2);
    list<account*>::const_iterator i;
    for(i = accounts_database.begin(); i != accounts_database.end(); ++i) 
    {
        if ((*i)->id==ID)
        {
            result_found = *i;
            break;
        }
        else
            result_found = NULL; 
    }
    return result_found;
}
int main( )
{
   account* a = find_account(30);
   return 0;
}

上面的代碼可能會更好地幫助您。 我剛剛編寫了一個粗糙的代碼,請嘗試盡可能優化。

歡迎發表評論...

暫無
暫無

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

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