简体   繁体   中英

C++ Equivalent of VLOOKUP function

I'm trying to create an equivalent of the excel VLOOKUP function for a two dimensional csv file I have. If given a number 5 I would like to be able to look at a column of a dynamic table I have and find the row with the highest number less than five in that column.

For example. If I used 5 from my example before:

2  6
3  7
4  11
6  2
9  4

Would return to me 11, the data paired with the highest entry below 5.

I have no idea how to go about doing this. If it helps, the entries in column one (the column I will be searching) will go from smallest to largest.

I am a beginner to C++ so I apologize if I'm missing some obvious method.

std::map can do this pretty easily:

You'd start by creating a map of the correct type, then populating it with your data:

std::map<int, int, std::greater<int> > data;

data[2] = 6;
data[3] = 7;
data[4] = 11;
data[6] = 2;
data[9] = 4;

Then you'd search for data with lower_bound or upper_bound :

std::cout << data.lower_bound(5)->second; // prints 11

A couple of notes: First, note the use of std::greater<T> as the comparison operator. This is necessary because lower_bound will normally return an iterator to the next item (instead of the previous) if the key you're looking for isn't present in the map. Using std::greater<T> sorts the map in reverse, so the "next" item is the smaller one instead of the larger.

Second, note that this automatically sorts the data based on the keys, so it depends only on the data you insert, not the order of insertion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM