-2

i got aproblem in map where i'm trying to cout the map but it come out in different orders. is there is away to make it come out in arranged order.

#include<iostream>
#include<map>
int main(){
std::map<std::string,int> person;
person["Mostafa"]=12;
person["Mickel"]=14;
person["tftf"]=141;
person["Daniel"]=15;
std::map<std::string,int>::iterator it;
for(it=person.begin();it!=person.end();it++){
    std::pair<std::string,int> memo=*it;
    std::cout<<memo.first<<": "<<memo.second<<std::endl;
}
std::cin.get();
return 0;
}

and the out put is: Daniel: 15 Mickel: 14 Mostafa: 12 tftf: 141

2 Answers2

0

It's simple, std::map sort its items by keys (the names in your case). You may want to find another solution e.g container for your problem. Here is a previous question and an answer that might give you some insight.

std::map, how to sort by value, then by key

BeErikk
  • 74
  • 1
  • 7
0

You can use a vector of pairs to solve this issue.
- First, define a type person as a pair of string and int.
- Second, define a vector of persons and then add to the vector as required.
Then you will be able to print in the same order you have inserted.

#include<iostream>
#include<map>
#include<vector>

int main(){
    typedef std::pair<std::string,int> person;

    std::vector<person> vMap;
    vMap.emplace_back("Mostafa", 12);
    vMap.emplace_back("Mickel", 14);
    vMap.emplace_back("tftf", 141);
    vMap.emplace_back("Daniel", 15);

    for(const auto& a: vMap)
     std::cout<<a.first<< " " << a.second<<std::endl;

    return 0;
}

Here is a live demo: https://coliru.stacked-crooked.com/a/7913c31d50074bdc

P.W
  • 26,289
  • 6
  • 39
  • 76