mardi 15 mars 2022

Which STL Container will be good to store millions of user define(class) data?

Suppose we've millions of custom data that need to be stored and search later these which STL will be good? let's say

class A{ 
    public:
      int i;
      float f;
      string s;
};

We need to to store the objects of class A.

Read bitset from file using istream_iterator

I'm trying to read a text file into a vector of std::bitset-objects. The file consists of 1's and spaces (for indicating 0 or false) and I'm trying to do this by overloading the input operator>> and using istream_iterators. I start by changing the spaces in the string to 0's and then construct a bit that I push to the vector with that string. However when I print the output looks very strange and it seems that I'm reading in more elements than lines in the file (the vector of bitsets is longer than the number of lines). The code looks as follows:

  
  template<long unsigned int N>
  std::istream& operator>>(std::istream& is, std::bitset<N>& b){
    std::string line;
    std::getline(is,line);
    for(unsigned long int i =0;i<N;++i){line[i]==' '? line[i]='0':'1';};
    std::cout << line << std::endl;
    b = std::bitset<N>(line);
    return is;
  }
 
 int main(){
  const unsigned long int N = 40;
  std::ifstream file("activities.txt");
  std::istream_iterator<std::bitset<N>> begin(file),end;
  std::vector<std::bitset<N>> bits;
  
  for(auto it = begin;it!=end;++it){
    bits.push_back(*it);
  }
  
  for(auto bit: bits){ std::cout << bit << std::endl;}
 }

I succeeded in doing the same thing without using the istream_iterator and the overloading of operator>> but I'm just trying to figure out why this way is not working.

lundi 14 mars 2022

There two picture i added.Please solve this two problem using C [closed]

[You are given N number of integer values, count the number of 5 or 3s in the list.

Also print the total sum of these 5s and 3s. First line of input contains an integer N followed by N number of integer values in the next lines. All the integer values are within the range of 1 and 100000]1

How to create a wrapper or intermediate layer to access a class, without exposing it?

I use a third party engine, that has a class "Sprite". My classes use sprite, and call its methods.

There is a probability that "Sprite" will be replaced in the future by some other game engine. I would like to have a layer between my class, and Sprite, so that it is easy to swap out Sprite in future.

I figure there are at least two ways to do this:

  1. Implement a wrapper class that has a bridge method for every method in sprite, and that my code uses to access the sprite.

For Example:

Wrapper{
private:
Sprite* foo;
public:

  void method1(){
     foo->method1();
   }

   int method2(){
      return foo->method2();
    }
}

The downside with this approach is that there is a lot of work to write a method for each method in Sprite, even though all it is doing is just calling the method and returning whatever result. It is also a lot of maintenance work each time there is a change in sprite.

  1. Alternative 2 : Some kind of magic by overloading the -> operator.

     struct LoggingFoo : public Sprite {
     void log() const { } //Just a method for logging.Doesn't matter. 
    
    
     Foo const *operator -> () const { log(); return this; }
     Foo       *operator -> ()       { log(); return this; }
    

    };

Not very sure of all the things to keep in mind with this option ? For example, what happens to class methods ? Does it make sense to publicly inherit Sprite for this use case ?

Note: In practice, there is no object that is intended to inherit from Sprite in my code.

EDIT: What would be the most concise way to create the wrapper, yet expose all public member variables and functions? For example, not having to specify each and every variable and function to expose ?

What is a pattern to ensure that every derived class (including derived classes of the immediate derived class) implement a method?

I have a base class and a number of generations of descendants (derived classes):

class Base{
    public:
    virtual void myFunc() = 0;
}
    
class Derived : public Base{
    //This class needs to implement myFunc()
}
    
class Derived2 : public Derived{
    //How to force this class to implement its version of myFunc(), and force it to call Derived::myFunc as well ?
}
    
class Derived3 : public Derived2{
    //.....should implement its own myFunc and call Derived2's mynFunc()...
}
    
class Derived4 : public Derived3{
    //.....should implement its own myFunc and call Derived3's mynFunc()...
}

Is there a pattern to ensure:

  • That each derived class (regardless of whether it is an immediate descendant of the base class, or a descendant of a descendant of the base class), implement its version of myFunc?
  • That each derived class calls its immediate parent class myFunc?

EDIT: The pattern that comes to mind to me is Decorator pattern, but wondering if there is some better way or variation.

Why the plaintext in libtomcrypt cannot be generated by PRNG(e.g., yarrow)

Firstly, I just tell you the scenario I just met. I WANT to test the efficiency of the aes-ofb in libtomcrypt with different plaintext sizes such as 64, 128, 256 Byte, etc. TO make my codes more automatic, I just would like to use the PRNG to fill up the plaintext. secondly, I just show the function that could fill up the plaintext with yarrow prng.

static inline int PRNG(unsigned char buf[], unsigned int len){
 /* create the seed for the pseudo-random number generator */
unsigned char buf_seed[4];
int err;
std::random_device rd;
int x = (int) rd();
memcpy(buf_seed, &x, sizeof(x));
/* send the buf_seed into the PRNG in libtomcrypt*/
prng_state prng;
if ((err = yarrow_start(&prng))!= CRYPT_OK){
    printf("Start error:%s\n", error_to_string(err));
}
if((err=yarrow_add_entropy(buf_seed, sizeof(buf_seed),&prng))!=CRYPT_OK){
printf("Add_entropy error:%s\n",error_to_string(err));
}
if((err=yarrow_ready(&prng))!=CRYPT_OK){
  printf("Ready error:%s\n",error_to_string(err));
}
yarrow_read(buf,len,&prng);
sprng_done(&prng);
return 0;}

In addition, to make my plaintext could be filled up easily, I just use a pointer array to store the address of different with different sizes. THE corresponding codes like following.

char *plaintext[5];
int len_pt(64);
for (int i = 0; i < 5; i++){
    std::cout << "the length of the plaintext is " << len_pt << std::endl;
    if (i == 4){
        len_pt = 768;
    } 
    plaintext[i] = new char[len_pt];
    PRNG((unsigned char *)plaintext[i], len_pt);
    len_pt *= 2;
}

When I just used this kind of plaintext, my encryption and decryption will apprear erros.

int tom_aes::ofb(char *plaintext, int len_pt){
if (PRNG(this->iv, this->iv_len) != 0){
    std::cout << "[ERROR] PRNG failed!" << std::endl;
}
symmetric_OFB   ofb;
/* temporary variables */
unsigned char *ciphertext = new unsigned char[len_pt];
unsigned char *deciphertext = new unsigned char[len_pt];
/* ENCRYPT */
if ((err = ofb_start(find_cipher("aes"), this->iv, key, sizeof(key), 0, &ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}
if ((err = ofb_encrypt((unsigned char*)plaintext, ciphertext, len_pt, &ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}

if ((err = ofb_done(&ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}

/* DECRYPT */
if ((err = ofb_start(find_cipher("aes"), this->iv, key, sizeof(key), 0, &ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}

if ((err = ofb_decrypt(ciphertext, deciphertext, len_pt, &ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}

if ((err = ofb_done(&ofb)) != CRYPT_OK){
    printf("[tom_aes_ofb]ERROR: in %s, %s\n", __func__, error_to_string(err));
    return 0;
}

if (memcmp(deciphertext, plaintext, len_pt) == 0){
    printf("\n[tom_aes_ofb]Recovery:       OK\n");
}
else{
    printf("\n[tom_aes_ofb]Recovery:       FAIL\n");
}
delete ciphertext;
delete deciphertext;
return 0;} 

I have just tested above codes. When the plaintext is just like:

char            plaintext[] = "Hi I am an AES ECB test vector distributed on 4 128-bit blocks!";

The encryption and decryption could execute smooothly. But the plaintext filled up by my prng function will be destroyted. I cannot figure it out. Wish you could give a hand.

dimanche 13 mars 2022

C++: Pass string literal or variable to function

I have a function f that takes a string as input. I usually want to provide a string literal, e.g., f("hello"). However, I want to implement another function g that builds upon f:

std::string f(const std::string&& x) {
  return x + " world";
}

std::string g(const std::string&& x) {
  std::string res = f(x);  // problem: rvalue reference to std::string cannot bind to lvalue of type std::string
  res += "!";
  return res;
}

int main() {
  std::string res_a = f("hello");
  std::string res_b = g("world");
  return 0;
}

How can I achieve this in C++11/14 in a way that I can use f with string literals as well as variables?