Containers

The std::list<std::array<unsigned char, 69>> is how you do it. Previously, I did it wrong by using std::vector instead of std::list. The problem with vector is that it loses the abstraction. Yes, a vector of array works, but the layout is all flat and you cannot use push_back this command cannot save the array into the vector. The only that works is std::memcpy like i said, all is flat.

Whereas, the std::list or list of array works as I needed. Each array is an individual element of the list. This is not the case with vector!

Here is the snippet that works:

void list_of_array()
{
    unsigned char *buf;
    int n;

    unsigned char key1[32];
    unsigned char key2[32];
    unsigned char key3[32];

    randombytes_buf(key1, 32);
    randombytes_buf(key2, 32);
    randombytes_buf(key3, 32);

    int vcount = 3;
    unsigned char *verification_keys = new unsigned char[crypto_sign_PUBLICKEYBYTES*3];
    
    std::memcpy(
        verification_keys, 
        key1, 
        crypto_sign_PUBLICKEYBYTES);

    std::memcpy(
        verification_keys + crypto_sign_PUBLICKEYBYTES, 
        key2, 
        crypto_sign_PUBLICKEYBYTES);

    std::memcpy(
        verification_keys + crypto_sign_PUBLICKEYBYTES*2, 
        key3, 
        crypto_sign_PUBLICKEYBYTES);

    std::list<std::array<unsigned char, crypto_sign_PUBLICKEYBYTES>> trustedkeys;
    std::array<unsigned char, crypto_sign_PUBLICKEYBYTES> public_key;

    unsigned char *VKEYS = new unsigned char[crypto_sign_PUBLICKEYBYTES*3];

    for (int i = 0; i < vcount; i++) {
        // copy a C array slice to C++ std::array
        std::copy(
            verification_keys + i * crypto_sign_PUBLICKEYBYTES,
            verification_keys + i * crypto_sign_PUBLICKEYBYTES + crypto_sign_PUBLICKEYBYTES ,
            std::begin(public_key));

        buf = public_key.data();
        n = public_key.size();

        std::memcpy(VKEYS + i * crypto_sign_PUBLICKEYBYTES, buf, n);
        trustedkeys.push_back(public_key);
    }

    for (auto &key : trustedkeys) {
        buf = key.data(); 
    }

    delete[] verification_keys;
    delete[] VKEYS;
}

Create a list of jagged array in C++:

Last updated

Was this helpful?