How to access std::map to auto?

Asked 1 years ago, Updated 1 years ago, 96 views

std::vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7 };
for ( auto xyz : numbers )
{
     std::cout << xyz << std::endl;
}

In C++0x, vector for for if you turn the xyz door like this, int type was

type
std::map< foo, bar > testing = { /*...blah...*/ };
for ( auto abc : testing )
{
    std::cout << abc << std::endl;         // foo? bar?
    std::cout << abc->first << std::endl; // or the etherator?
}

What happens if it's map like this? vector is accessed as an element by turning around the for statement, as if approaching with an index list needs to be accessed through an eater How can I access map or multimap?

c++ map for-loop c++11

2022-09-22 22:25

1 Answers

Declaring std::vector<X> means storing elements of the X type in the container Declaring std::map<X, Y> means saving std::pair<const X, Y>. In std::pair<const X, Y>, the reason const is added only to Xkey, and Y corresponds to . key cannot be changed, but Y can be changed.

The elements stored in map are std::map<K, V>::value_type. Therefore, when you write an interpreter, such as for(auto..), you access std::pair. When accessing <K, V> with std::pair, you must access first (K), second ().

int main(){
    map<int, int> temp;
    temp[5] = 4;
    temp[1] = 2;

    for(auto &kv : temp){
        cout << kv.first << " " << kv.second << endl;
    }
}


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.