User Tools

Site Tools


start:prog2:lectures:code2

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
start:prog2:lectures:code2 [2017/03/02 17:31]
kkv created
start:prog2:lectures:code2 [2022/12/10 09:08] (current)
Line 51: Line 51:
   void (*print)(const struct Person*);   void (*print)(const struct Person*);
   void (*printer)(const struct Person*);   void (*printer)(const struct Person*);
-  struct Person *This; 
 } person1, person2; } person1, person2;
  
Line 77: Line 76:
   person1.print = print;   person1.print = print;
   person1.printer = print_nice;   person1.printer = print_nice;
-  person1.This = &​person1;​ 
  
   person2.name = "​Petya";​   person2.name = "​Petya";​
Line 83: Line 81:
   person2.print = print;   person2.print = print;
   person2.printer = print_ugly;   person2.printer = print_ugly;
-  person2.This = &​person2;​ 
  
   person1.print(&​person1);​   person1.print(&​person1);​
Line 92: Line 89:
  
 </​code>​ </​code>​
 +
 +=== Universal search ===
 +<code c++>
 +// Programming 1. Sample at 2018-02-15-14-55.05
 +#include <​stdio.h>​
 +
 +struct S{
 +  int a;
 +  int b;
 +};
 +
 +void* search( void *key,
 +              void *arr,
 +              int n,
 +              int size,
 +              int (*comp)(const void *, const void *)
 +            ){
 +
 +  for(int i=0;​i<​n;​i++){
 +    if(comp(key,​ arr+i*size) == 0){
 +      return arr+i*size;
 +    }
 +  }
 +  return NULL;
 +}
 +
 +// if both fields are equal, the structures are equal
 +// otherwise compare by the sum of two fields
 +int comp(const void *a, const void *b){
 +  struct S *aa = (struct S*)a;
 +  struct S *bb = (struct S*)b;
 +  if(aa->a == bb->a && aa->b == bb->b){
 +    return 0;
 +  }
 +  if((aa->​a + aa->b) - (bb->a + bb->b) > 0){
 +    return 1;
 +  }
 +  return -1;
 +}
 +
 +int main(){
 +  struct S arr[]={{1,​2},​{3,​4},​{5,​6},​{6,​7}};​
 +  struct S* value;
 +  struct S key={5,6};
 +
 +  value = search(&​key,​ arr, 4, sizeof(struct S), comp);
 +  if(value){
 +    printf("​%zu\n",​ value - arr);
 +  }else{
 +    printf("​nooooo\n"​);​
 +  }
 +  return 0;
 +}
 +
 +</​code>​
 +
start/prog2/lectures/code2.1488475905.txt.gz · Last modified: 2022/12/10 09:08 (external edit)