Error in traversing a doubly linked list when similar conditions are applied - doubly-linked-list

I have been given a sorted doubly linked list and am to insert a new node such that it remains sorted.
I was using this method to traverse the list
while(temp->next)
{
if(temp->next->data <= newnode->data)
{
temp=temp->next;
}
}
But this doesn't seem to work but when I used this
while(temp-next && temp->next->data <= newnode->data)
{
temp=temp->next;
}
I didn't suffer from any errors.
I'm still in the process of learning and I'm unable to find what I'm doing wrong.

Related

How do I use STL std::list with objects?

I want to create linked lists of objects sorted by an object attribute (physical size); but so far it seems I will have to code them myself...
These lists will be short, typically a dozen nodes each; but I may have up to a thousand lists; so I can't afford the extra weight of using std::map's. In fact, I'd be quite happy with single linked list.
But I need the node to be more than just a value.
The key value in my objects is rarely going to change; however elements will have to come out of one list and move to another quite often.
((Actual use: One list per quad, in a quad-tree (as for collision detection, etc); objects sorted by size, as the larger objects are less numerous but need to be picked quickly from larger ranges, so they should come up first in the lists.))
But every example I find for using std::list to maintain sorted lists uses a list of integers as the example; but that's not very useful; what I have is objects that have one value member to be sorted by.
I was thinking of using lower_bound to find the insertion point, then insert the object; but the lower_bound iterator takes a begin, and end, and a plain value as the third argument; I see no mechanism by which I can specify to use a particular member of my objects to sort by.
I could, of course, define a conversion operator,
my_object_type::int(){ return sortby; }
Would that work? Is there a better way?
I seem to have found my answer in this reference:
https://www.geeksforgeeks.org/lower_bound-in-cpp/
under "Syntax 2"; there is provision for a fourth
argument being a comparison functor. So, something
like this should work (not tested yet):
class pnt_proxy
{
int x; //position
int y;
point* real_pnt; //the real point this represents
public:
float sz; //rough largest diagonal across object
}
class pproxy_cmp : public std::binary_function< pnt_proxy, pnt_proxy, bool >
{
public:
bool operator()( pnt_proxy const & a, pnt_proxy const & b ) const
{
return a.sz < b.sz;
}
};
std::list< pnt_proxy > ll;
void insert_sorted( pnt_proxy const & pp )
{
if( ll.size() )
{
std::list<pnt_proxy>::iterator insert_at;
insert_at =
std::lower_bound( ll.begin(), ll.end(), pp, pproxy_cmp() );
ll.insert( insert_at, pp );
}
else ll.push_back( pp );
}

How to write to an Element in a Set?

With arrays you can use a subscript to access Array Elements directly. You can read or write to them. With Sets I am not sure of a way to write its Elements.
For example, if I access a set element matching a condition I'm only able to read the element. It is passed by copy and I can't therefore write to the original.
For example:
columns.first(
where: {
$0.header.last == Character(String(i))
}
)?.cells.append(value: addValue)
// ERROR: Cannot use mutating member on immutable value: function call returns immutable value
You can't just change things inside a set, because of how a (hash) set works. Changing them would possibly change their hash value, making the set into an invalid state.
Therefore, you would have to take the thing you want to change out of the set, change it, then put it back.
if var thing = columns.first(
where: {
$0.header.last == Character(String(i))
}) {
columns.remove(thing)
thing.cells.append(value: addValue)
columns.insert(thing)
}
If the == operator on Column doesn't care about cells (i.e. adding cells to a column doesn't suddenly make two originally equal columns unequal and vice versa), then you could use update instead:
if var thing = columns.first(
where: {
$0.header.last == Character(String(i))
}) {
thing.cells.append(value: addValue)
columns.update(thing)
}
As you can see, it's quite a lot of work, so maybe sets aren't a suitable data structure to use in this situation. Have you considered using an array instead? :)
private var _columns: [Column]
public var columns : [Column] {
get { _columns }
set { _columns = Array(Set(newValue)) }
// or any other way to remove duplicate as described here: https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift
}
You are getting the error because columns might be a set of struct. So columns.first will give you an immutable value. If you were to use a class, you will get a mutable result from columns.first and your code will work as expected.
Otherwise, you will have to do as explained by #Sweeper in his answer.

SwiftUI Conditional List - Unable to infer complex closure return type

I know questions involving this error have been asked before, but I have looked through them and none of them have helped me solve this particular issue.
I have a List, which depending on a certain condition, will have some items filtered out. Here it is:
List(tasks) { task in
if (!self.toggleIsOn) || (!task.completed.status) {
TaskRowView(task)
}
}
Everything works fine, but when I add the conditional, it gives me this error:
Unable to infer complex closure return type; add explicit type to disambiguate
On the List line. How can I fix this?
List expects a View returned for every item, using Group like that is a bit of a hack.
Better to move the logic out of the List, either
var filteredTasks: [Task] {
return tasks.filter { !self.toggleIsOn || !$0.completed.status }
}
...
List(filteredTasks) { task in
TaskRowView(task)
}
or
List(tasks.filter( { !self.toggleIsOn || !$0.completed.status })) { task in
TaskRowView(task)
}
I managed to fix this problem by surrounding the returned value in a Group - this meant that the return type was always Group, even if the Group didn't contain anything.
List(tasks) { task in
Group {
if (!self.toggleIsOn) || (!task.completed.status) {
TaskRowView(task)
}
}
}

Yang Model recursive search for must condition

I have a problem with a restriction on my CLI. I've been investigating yang RFC7950 (https://www.rfc-editor.org/rfc/rfc7950) but I've found nothing.
Here is an example.
grouping httpGroup {
list http-list{
key "value";
leaf value {
status current { yexte:preliminary; }
description "value to match";
must "(not(../protocol)) and (not(../network-port)))" {
error-message "Not compatible with protocol or non-TCP ports";
}
type string { length "1..255"; }
}
}
}
This group will be included in several groups with the following structure:
list and {
leaf-list protocol { ..... }
uses A;
list or {
leaf-list protocol { ..... }
uses A;
}
}
grouping A {
status{}
leaf-list protocol { ..... }
leaf-list X { ..... }
uses httpGroup;
}
I need this must condition included in httpGroup to verify that protocol value has not been configured in any level of the hierarchy.
I've made this be adding more relatives paths to search for this node:
// same level
not(../protocol)
// next level
not(../and/protocol)
not(../or/protocol)
// previous level
not(../../protocol)
not(../../protocol)
//recursively down previous level
not(../../and/protocol)
not(../../or/protocol)
// third level
not(../and/or/protocol)
not(../and/and/protocol)
As you can see, this is not a clean solution at all.
Is there any way it can be done for a whole hierarchy like:
if protocol node exists and http-list exists then error.
Thank you in advance.
Groupings are meant to be reusable. It is a bad practice to attempt to create a grouping that may only be used in specific contexts. This is exactly what happens if you define an XPath expression within a grouping and this expression references nodes that are "outside" this grouping (a not yet known ancestor data node, for example, or even worse - an ancestor with a specific name).
The proper way for you to handle this situation would be to use a refine statement in each different context where this grouping is used. You target the value leaf with it, then refine it by adding a must statement, the expression of which of course depends on usage context. You do not define a must statement within grouping http-list.
Within grouping A:
grouping A {
status{}
leaf-list protocol { ..... }
leaf-list X { ..... }
uses httpGroup {refine "http-list/value" {must "not(../../protocol)";}}
}
As you can see, grouping A is now completely self-sufficient and may be used within any context - the must will not have any problems with it.

Are there any side effects of exiting a loop with return rather than break in Swift?

I need to match items in two different arrays (one with imported items and another with local items that share some properties with the imported items) to sync two databases that are quite different. I need to use several criteria to do the matching to increase the robustness of finding the right local item and match it with the imported item. I could check each criterium in the same loop, but that is too expensive, because the criteria are checked by the likelihood of success in descending order. Thus, in my first implementation I used a boolean flag called found to flag that the checking of other criteria should be ignored.
Using pseudo code:
// calling code for the matching
for item in importedItems {
item.match() }
In the imported item class:
match()
{
var found = false
for localItem in localItems
{
if (self.property == localItem.property)
{
// update the local item here
found = true
break
}
}
// match with less likely 2nd property
if (!found)
{
for localItem in localItems
{
if (self.property2 == localItem.property2)
{
// update the local item here
found = true
break
}
}
}
The if !found {...} pattern is repeated two additional times with even less likely criteria.
After reviewing this code, it is clear that this can be optimized by returning instead of breaking when there is a match.
So, my question is "are there any known side-effects of leaving a loop early by using return instead of break in Swift?" I could not find any definitive answer here in SO or in the Swift documentation or in blogs that discuss Swift flow control.
No, there are no side effects, quite the opposite it's more efficient.
It's like Short-circuit evaluation in a boolean expression.
But your code is a bad example because found cannot be used outside the function.
This is a more practical example returning a boolean value
func match() -> Bool
{
for localItem in localItems
{
if (self.property == localItem.property)
{
// update the local item here
return true
}
}
....
return false
}
If you know for sure that you can return because nothing else have to be done after the loop then there are no side effects of using return