Vector of objects: sorting and testing elements

Hi,
I have a vector of objects that I would like to (1) sort then (2) test in ascending order.

In my snippet I have the following issues:

The line "return lhs.getTargetDistance() < rhs.getTargetDistance();" returns "getTargetDistance: is not a member of 'std::vector<_Ty>'"

I don't know how to implement the last for loop in the snippet.

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
void fillVector(vector<NodeClass>&); 
//fillVector - create a vector and fill it up with all the nodes

bool sortByDist(vector<NodeClass>&);
// sort objects within the vector

int main()
{
	fillVector(nodeMesh);
	sortByDist(nodeMesh);
	return 0;
}

void fillVector(vector<NodeClass>& newNodeMesh){
//several types, only showing two here:

	//initially set to false, only one element set to true
	bool inRedNode = false;

	// initially set to 0.0, randomly generated values are assigned while filling the vector
	float targetDistance = 0.0f;

	//loop and add to vector
	newNodeMesh.push_back(newNode);
}

// function to sort the vector by targetDistance
bool sortByDist(vector<NodeClass> &lhs, vector<NodeClass> &rhs){
 	return lhs.getTargetDistance() < rhs.getTargetDistance();
}

// once the vector has been sorted, each element should also be tested:
for (unsigned int i=0; i<newNodeMesh.size(); i++){
redNode=newNodeMesh[i].getInRedNode();
if (redNode = true){
	// skip this element and test the next element in the vector
	}
else 
     do something ();
}
Last edited on
Test for what?
Your attempt looks more like do something for every element that is not red.
Keskiverto, yes, if (redNode = true) then this element is added to another list, but what I am really after is to find the first element in the vector that is not red, so that I can do something();

The order of the vector should be according to targetDistance, so firstly the elements in the vector should be sorted according to targetDistance (which is returning an error in lines 28-30)
(which is returning an error in lines 28-30)

On line 4 you do declare function that takes reference to one vector object as argument.

The function implemented on lines 28-30 takes two arguments. Different functions.

The latter function calls member function getTargetDistance() of each std::vector. Alas, std::vector does not have such member. Does the NodeClass have one?

Should you perhaps call std::sort somewhere?


find the first element in the vector that is not red

Find. Yes,

1
2
3
4
5
6
7
using V = std::vector<NodeClass>;
V foo;
auto pos = std::find_if_not( foo.begin(), foo.end(),
                             []( const NodeClass & n ) { return n.getInRedNode(); } );
if ( foo.end() != pos ) {
  // do something with *pos
}
Last edited on
Topic archived. No new replies allowed.