mareks
mareks

Reputation: 491

Control the order of elements in map

I create a map:

map<string, string> cuts;

cuts["cutb"] = "a>1";
cuts["cuta"] = "b>3";
cuts["cutc"] = "c<5";

When I iterate over this map with map<string, string>::iterator itr = cuts.begin(); it gets ordered alphabetically: cuta, cutb, cutc, etc.

How do I force the iterator to follow the order in which I've defined the elements i.e. cutb, cuta, cutc?

Upvotes: 0

Views: 123

Answers (3)

Boris Strandjev
Boris Strandjev

Reputation: 46963

You need to use some other implementation of the data structure. The red-black tree implementation will not do for you in your case.

Looking at it from more general perspective: why you need to create a map if you traverse the entries in order of addition? Won't list/array/vector of pairs suffice for you?

EDIT: Tip: whenever you choose to use a specific data structure ask yourself what exactly operations you need it to support. After answering that, you should be able to choose more precisely. Map is good if you need to find by key, insert by key and to check if a certain key exists. However, the price you will pay in the implementations that optimise those operations is usually that you lose the order of insertion of the elements.

EDIT2: looping through list of pairs:

// pair is class in namespace std
vector<pair<string, string> > v;
v.push_back(make_pair("cutb", "a>1"));
v.push_back(make_pair("cuta", "b>3"));
v.push_back(make_pair("cutc", "c<5"));
for (int i = 0; i < v.size(); i++) {
  // the first element of the pair is addressed with .first; the second - .second
  cout << "For key " << v[i].first << " the value is "  << v[i].second << endl;
}

Iterating in vector can also be done using iterators, but I like the index approach more, as it is just as optimal, but easier to understand.

Upvotes: 3

gvd
gvd

Reputation: 1831

Ok this is going to be a little bit more readable:

typedef std::pair<std::string, std::string> item;
std::vector<item> vec; 
vec.push_back(item("hello", "world"));
vec.push_back(item("abc", "efg"));

for (size_t i = 0; i < vec.size(); ++i) {
    std::cout << vec.at(i).first << " " << vec.at(i).second << std::endl;
}

Upvotes: 2

Swadq
Swadq

Reputation: 1837

You can't (or if you can, you shouldn't). If you need to retain order, you need another data structure. Try STL's vector

http://www.cplusplus.com/reference/vector/vector/

Upvotes: 2

Related Questions