Finding in a vector of Structure
-
hi, I have a vector of a structure. I want to find a value of a element of structure, so that i can get that elememt in vector. I m not able to get any algo in STL so solve this problem. If you hv any idea please tell me. Remember my vector is a vector of structure. There is a function _InIt find(_InIt _First, _InIt _Last, const _Ty& _Val) doesn't for it. Thanks & Regards Pankaj Jain
-
hi, I have a vector of a structure. I want to find a value of a element of structure, so that i can get that elememt in vector. I m not able to get any algo in STL so solve this problem. If you hv any idea please tell me. Remember my vector is a vector of structure. There is a function _InIt find(_InIt _First, _InIt _Last, const _Ty& _Val) doesn't for it. Thanks & Regards Pankaj Jain
That should work, unless the object/class allocates memory and it does not have a comparison method (operator==). The default comparison does a bitwise comparison, which will not work if the class (_Val) allocates memory (naturally). Each collection type and each algorithm requires certain minimum requirements and the minimum requirement for find is a valid “operator ==”. If that is not the problem, then I have no idea.
INTP "Program testing can be used to show the presence of bugs, but never to show their absence."Edsger Dijkstra
-
hi, I have a vector of a structure. I want to find a value of a element of structure, so that i can get that elememt in vector. I m not able to get any algo in STL so solve this problem. If you hv any idea please tell me. Remember my vector is a vector of structure. There is a function _InIt find(_InIt _First, _InIt _Last, const _Ty& _Val) doesn't for it. Thanks & Regards Pankaj Jain
Perhaps something like this: ---------------------------- // Console.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include using namespace std; struct Data { Data(int Num1, int Num2) : m_Num1(Num1), m_Num2(Num2) {} int m_Num1; int m_Num2; friend bool operator==(const Data &lhs, const Data &rhs) { return (lhs.m_Num1 == rhs.m_Num1) && (lhs.m_Num2 == rhs.m_Num2); } }; void main() { // Create and populate the collection. typedef vector coll_t; coll_t coll; coll.push_back(Data(3, 1)); coll.push_back(Data(4, 1)); coll.push_back(Data(5, 9)); coll.push_back(Data(2, 6)); coll.push_back(Data(5, 3)); // Find first (5, 9). coll_t::const_iterator i = find(coll.begin(), coll.end(), Data(5, 9)); if (i != coll.end()) { cout << "Found at index: " << (i-coll.begin()) << endl; } } Steve