search

Home  >  Q&A  >  body text

C++ cannot use (pointer) to get the value address in the STL container?

Please note that pointers are used instead of references: ...

int main(){

    std::vector<int> testData{100,500,60};
        
    auto atValue = [=](std::vector<int> &vec,int *data){
        for(auto it = vec.begin();it != vec.end();it++){
            if (*it == 500) {
                data = &*it;
                break;
            }
        }
    };
    
    
    int *tint = NULL;
    atValue(testData,tint);
    //*tint = 50;
    printf("%d",*tint);    
    
    return 0;
}

felix said:
int data changed to int &data

The problem has been solved.Thank you.

PHP中文网PHP中文网2750 days ago614

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 13:31:57

    int main(){
    
        std::vector<int> testData{100,500,60};
            
        auto atValue = [=](std::vector<int> &vec,int **data){
            for(auto it = vec.begin();it != vec.end();it++){
                if (*it == 500) {
                    *data = &*it;
                    break;
                }
            }
        };
        
        
        int *tint = new int(0);
        atValue(testData,&tint);
        //*tint = 50;
        printf("%d",*tint);
        delete tint;
        
            
        
        return 0;
    }

    have try

    reply
    0
  • Cancelreply