I am currently trying to use find_if to find an element in a vector of pairs.I have tried searching on google how to overload << operator and it did give me a large amount of information on how to overload <<. It still left me confused how to achieve my goal. Below is the code i am using, i want to find the string supplied to the function in my vector of pairs s.
void Utils::findIt(string serchVal)
{
vector<pair<string, HWND>>::iterator it = find_if(s.begin(), s.end(),
[&serchVal](const pair<string, HWND>& element) { return element.first == serchVal; });
cout << "find function found : " << *it << endl;
}
i have tried overloading the << operator like this.
template <typename T, typename D>
void operator<<(ostream& os, vector<pair(typename T, typename D)> &lst)
{
cout << lst.begin.front();
}
i am not well versed in overloading functions and i am still new to vectors. so any help concerning this would be appreciated!
You do not need to overload operator<<
for a std::vector<std::pair>
here as std::find_if
will return the iterator pointing to the element found in the std::vector
, which in this case will be an iterator to a std::pair<std::string, HWND>
, to print this via a std::ostream
you could use,
template<typename _Ty1, typename _Ty2>
std::ostream& operator<<(std::ostream& _os, const std::pair<_Ty1, _Ty2>& _p) {
_os << _p.first << ' ' << _p.second;
return _os;
}
if you want to go down the operator<<
overloading route. However, printing elements of a std::pair
is trivial anyway so overloading the insertion operator is not entirely necessary here.
The complete code for your problem:
#include <iostream>
#include <vector>
#include <utility>
template <typename T, typename D>
std::ostream& operator<<(std::ostream& os, std::vector<std::pair<T, D>> &lst) {
for (const auto &p : lst) {
os << p.first << ", " << p.second;
}
return os;
}
int main() {
std::vector<std::pair<int, int>> pairs = { { 1, 2 }, { 5, 6 } };
std::cout << pairs << std::endl;
return 0;
}
Step by step:
std::ostream&
back to caller code so we change your void operator<<
to std::ostream& operator<<
prototype. In the operator<<
you just do what you want. If you pair
's data in the output - put it there:
for (const auto &p : lst) { os << p.first << ", " << p.second; }
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.