This post has already been read 9630 times!
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<std::pair<int, int>> v = {{1,2}, {3,4}, {5,6}};
auto p = std::make_pair(3, 4);
if(std::find(v.begin(), v.end(), p) != v.end())
std::cout << "yes\n";
}
#include <vector>
#include <cassert>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<std::pair<int, int>> v = {{1,2}, {3,4}, {5,6}};
auto p = std::make_pair(3, 4);
assert(std::is_sorted(v.begin(), v.end()));
if(std::binary_search(v.begin(), v.end(), p))
std::cout << "yes\n";
}
Searching element in std::map by Value
#include <map>
#include <string>
#include <iterator>
std::map<std::string, int>::iterator serachByValue(std::map<std::string, int> & mapOfWords, int val)
{
// Iterate through all elements in std::map and search for the passed element
std::map<std::string, int>::iterator it = mapOfWords.begin();
while(it != mapOfWords.end())
{
if(it->second == val)
return it;
it++;
}
}
int main()
{
std::map<std::string, int> mapOfWords;
// Inserting data in std::map
mapOfWords.insert(std::make_pair("earth", 1));
mapOfWords.insert(std::make_pair("moon", 2));
mapOfWords["sun"] = 3;
std::map<std::string, int>::iterator it = serachByValue(mapOfWords, 3);
if(it != mapOfWords.end())
std::cout<<it->first<<" :: "<<it->second<<std::endl;
return 0;
}
External Sorting Criteria / Comparator
External sorting criteria i.e. Comparator
struct WordGreaterComparator
{
bool operator()(const std::string & left, const std::string & right) const
{
return (left > right);
}
};
std::map with external sorting criteria i.e. Comparator
std::map<std::string, int, WordGreaterComparator > mapOfWords_2;
mapOfWords_2.insert(std::make_pair("earth", 1));
mapOfWords_2.insert(std::make_pair("moon", 2));
mapOfWords_2.insert(std::make_pair("sun", 3));
for(std::map<std::string, int>::iterator it = mapOfWords_2.begin(); it != mapOfWords_2.end(); it++)
std::cout<<it->first<<" :: "<<it->second<<std::endl;
Output:
sun :: 3
moon :: 2
earth :: 1