vector find operator overload?

Apr 14, 2013 at 10:13pm
Hi!
I'm trying to make a function that checks if an object of type Block* with the m_ID same as the one I'm giving it exists inside a vector. Can I just overload an operator and that is all that it needs? the ==?

Some more information:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//The vector in the class Map:
std::vector<Block*> m_ActiveSeeds;

//current function prototype
bool Map::addSeed(Block* test){
    if(test (exists in m_ActiveSeeds)){
        return false
    }
    else{
        m_ActiveSeeds.push_back(test);
    }

//the Block class info
class Block{
    private:
        pair<int,int> m_ID;
   public:
        pair<int,int> getID(){return m_ID;}
Last edited on Apr 14, 2013 at 10:18pm
Apr 14, 2013 at 11:01pm
I've provided 2 ways for you to do it, the second way I am not 100% sure it'll work in C++03, but it should.

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
41
42
43
44
45
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Block {
	unsigned id_;
public:
	unsigned id() const { return id_; }
	Block(unsigned id) : id_(id) { }
};


bool doCheck(Block* block) {
	if (block->id() == 7)
		return true;

	return false;
}

int main() {

	vector<Block*> blocks;
	blocks.push_back(new Block(1));
	blocks.push_back(new Block(3));
	blocks.push_back(new Block(5));
	blocks.push_back(new Block(7));

	// C++11 Lambda Check
	Block* block9 = nullptr;
	unsigned target_id = 9;
	std::find_if(blocks.begin(), blocks.end(), [&](Block* current_block) {
		if (current_block->id() == target_id) {
			block9 = current_block;
			return true;
		}
		return false;
	});

	// C++03
	vector<Block*>::iterator block7 = std::find_if(blocks.begin(), blocks.end(), doCheck);

	return 0;
}
Apr 15, 2013 at 9:28am
fixed it by making this function:
1
2
3
4
5
6
bool checkSameID(Block* test1, Block* test2){
    if(test1->getID().first == test2->getID().first && test1->getID().second == test2->getID().second){
        return true;
    }
    else return false;
}
Topic archived. No new replies allowed.