【问题标题】:Getting pointer to element in a list获取指向列表中元素的指针
【发布时间】:2015-12-22 10:14:55
【问题描述】:

我有一个列表,里面全是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* 的正确方法是什么吗?

【问题讨论】:

  • “这不起作用” - 你得到什么错误?我猜想const 的事?提示:您使用const_iterator,但随后返回非const 指针。
  • 改了还是不行
  • 请提供实际错误,SSCCE 也可能是个好主意。
  • C++ 中没有 for-else 构造,就像 Python 中一样。去掉else关键字就可以了。

标签: c++ list vector iterator


【解决方案1】:

您忘记了begin 和end 后面的()。同样使用 C++11 风格,我会编写这样的代码,看起来好多了。

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

【讨论】:

    【解决方案2】:
    #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;
    }
    

    以上代码可能会更好地帮助您。 只是我写了一个粗略的代码,请尽量优化。

    欢迎 cmets...

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多