Finding Vector(includes objects) Element's Index by Element
Jan 21, 2023 at 12:28pm Jan 21, 2023 at 12:28pm UTC
I'm trying to find the index of a vector element. Vector includes class objects. But I can't find a way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <vector>
#include <algorithm>
#include <iostream>
class myClass
{
int a;
};
void indexfinder (std::vector<myClass>& vec1, myClass& _key)
{
auto i = std::find(vec1.begin(), vec1.end(), _key);
//if it's found
if (i != vec1.end())
{
int k = i - vec1.begin();
std::cout << k;
}
//if it's not found
else
std::cout << -1;
}
int main()
{
myClass abc1;
myClass abc2;
myClass abc3;
std::vector<myClass>vec1 {abc1, abc2, abc3};
indexfinder(vec1,abc3);
}
I tried this without class, just with integers and it was working. This code is giving a lot of errors with class objects. Especially says there's no operator== for this type or smth.
Jan 21, 2023 at 12:44pm Jan 21, 2023 at 12:44pm UTC
I found a solution like this and it's working with this example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <vector>
#include <iostream>
class myClass
{
public :
int a;
bool operator == (myClass _x)
{
if (this ->a == _x.a)
return 1;
else
return 0;
}
};
void indexfinder (std::vector<myClass>& vec1, myClass& _key)
{
for (auto i = 0; i <(int ) vec1.size(); i++)
{
if (vec1.at(i) == _key)
std::cout << i;
}
}
int main()
{
myClass abc1;
abc1.a = 0;
myClass abc2;
abc2.a = 0;
myClass abc3;
abc3.a = 5;
std::vector<myClass>vec1 {abc1, abc2, abc3};
indexfinder(vec1,abc3);
}
Jan 21, 2023 at 12:51pm Jan 21, 2023 at 12:51pm UTC
Perhaps this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <vector>
#include <algorithm>
#include <iostream>
class myClass
{
int a {};
public :
myClass(int a_) : a(a_) {}
friend bool operator ==(const myClass& a, const myClass& b) {
return a.a == b.a;
}
};
void indexfinder(const std::vector<myClass>& vec1, const myClass& _key) {
const auto i { std::find(vec1.begin(), vec1.end(), _key) };
//if it's found
if (i != vec1.end()) {
const auto k { std::distance(vec1.begin(), i) };
std::cout << k;
}
//if it's not found
else
std::cout << -1;
}
int main() {
myClass abc1(1);
myClass abc2(2);
myClass abc3(3);
std::vector<myClass>vec1 { abc1, abc2, abc3 };
indexfinder(vec1, abc3);
}
Last edited on Jan 21, 2023 at 1:32pm Jan 21, 2023 at 1:32pm UTC
Topic archived. No new replies allowed.