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++:
int qlen;
unsigned char* buffe;
std::list<std::vector<unsigned char>> LIST;
std::vector<unsigned char> ELEM;
unsigned char elem1[64];
unsigned char elem2[60];
unsigned char elem3[69];
randombytes_buf(elem1, sizeof elem1);
randombytes_buf(elem2, sizeof elem2);
randombytes_buf(elem3, sizeof elem3);
ELEM.insert(ELEM.end(), &elem1[0], &elem1[64]);
LIST.push_back(ELEM);
ELEM.clear(); // needed
ELEM.insert(ELEM.end(), elem2, elem2 + sizeof elem2);
LIST.push_back(ELEM);
ELEM.clear(); // needed
ELEM.insert(ELEM.end(), &elem3[0], &elem3[69]);
LIST.push_back(ELEM);
for (auto& elem : LIST) {
qlen = elem.size();
buffe = elem.data();
std::cout << qlen << std::endl;
}
Last updated
Was this helpful?