question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,400,185 | 71,424,134 | How do I use blitz++ | I am a beginner in c++. My focus of learning c++ is to do scientific computation. I want to use blitz++ library. I am trying to solve rk4 method but I am not getting the inner workings of the code(I know rk4 algorithm)
#include <blitz/array.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace blitz;
using namespace std;
# This will evaluate the slopes. say if dy/dx = y, rhs_eval will return y.
void rhs_eval(double x, Array<double, 1> y, Array<double, 1>& dydx)
{
dydx = y;
}
void rk4_fixed(double& x, Array<double, 1>& y, void (*rhs_eval)(double, Array<double, 1>, Array<double, 1>&), double h)
{
// Array y assumed to be of extent n, where n is no. of coupled equations
int n = y.extent(0);
// Declare local arrays
Array<double, 1> k1(n), k2(n), k3(n), k4(n), f(n), dydx(n);
// Zeroth intermediate step
(*rhs_eval) (x, y, dydx);
for (int j = 0; j < n; j++)
{
k1(j) = h * dydx(j);
f(j) = y(j) + k1(j) / 2.;
}
// First intermediate step
(*rhs_eval) (x + h / 2., f, dydx);
for (int j = 0; j < n; j++)
{
k2(j) = h * dydx(j);
f(j) = y(j) + k2(j) / 2.;
}
// Second intermediate step
(*rhs_eval) (x + h / 2., f, dydx);
for (int j = 0; j < n; j++)
{
k3(j) = h * dydx(j);
f(j) = y(j) + k3(j);
}
// Third intermediate step
(*rhs_eval) (x + h, f, dydx);
for (int j = 0; j < n; j++)
{
k4(j) = h * dydx(j);
}
// Actual step
for (int j = 0; j < n; j++)
{
y(j) += k1(j) / 6. + k2(j) / 3. + k3(j) / 3. + k4(j) / 6.;
}
x += h;
return; # goes back to function. evaluate y at x+h without returning anything
}
int main()
{
cout << y <<endl; # this will not work. The scope of y is limited to rk4_fixed
}
Here are my questions?
In rhs_eval x,y are just values. But dydx is pointer. So rhs_eval's output value will be assigned to y. No need to return anything. Am i correct?
What does int n = y.extent(0) do? In comment n is saying it's the number of coupled equation. What is the meaning of extent(0). what does extent do? what is that '0'? Is it the size of first element?
How do I print the value of 'y'? what is the format? I want to get the value of y from rk4 by calling it from main. then print it.
I compiled blitz++ using MSVS 2019 with cmake using these instruction--
Instruction
I got the code from here- only the function is given
| #include <blitz/array.h>
#include <iostream>
#include <cstdlib>
using namespace blitz;
using namespace std;
/* This will evaluate the slopes. say if dy/dx = y, rhs_eval will return y. */
const double sig = 10; const double rho = 28; const double bet = 8.0 / 3;
void lorenz(double x, Array<double, 1> y, Array<double, 1> &dydx)
{
/* y vector = x,y,z in components */
dydx(0) = sig * (y(1) - y(0));
dydx(1) = rho * y(0) - y(1) - y(0) * y(2);
dydx(2) = y(0) * y(1) - bet * y(2);
}
void rk4_fixed(double& x, Array<double, 1>& y, void (*rhs_eval)(double, Array<double, 1>, Array<double, 1> &), double h)
{
int n = y.extent(0);
Array<double, 1> k1(n), k2(n), k3(n), k4(n), f(n), dydx(n);
(*rhs_eval) (x, y, dydx);
for (int j = 0; j < n; j++)
{
k1(j) = h * dydx(j);
f(j) = y(j) + k1(j) / 2.0;
}
(*rhs_eval) (x + h / 2., f, dydx);
for (int j = 0; j < n; j++)
{
k2(j) = h * dydx(j);
f(j) = y(j) + k2(j) / 2.;
}
(*rhs_eval) (x + h / 2., f, dydx);
for (int j = 0; j < n; j++)
{
k3(j) = h * dydx(j);
f(j) = y(j) + k3(j);
}
(*rhs_eval) (x + h, f, dydx);
for (int j = 0; j < n; j++)
{
k4(j) = h * dydx(j);
}
for (int j = 0; j < n; j++)
{
y(j) += k1(j) / 6. + k2(j) / 3. + k3(j) / 3. + k4(j) / 6.;
}
x += h;
}
int main()
{
Array<double, 1> y(3);
y = 1, 1, 1;
double x = 0, h = 0.05;
Array<double, 1> dydx(3);
dydx = 0, 0, 0;
for (int i = 0; i < 10; i++)
{
rk4_fixed(x, y, &lorenz, h);
cout << x << " ,";
for (int j = 0; j < 3; j++)
{
cout << y(j)<<" ";
}
cout << endl;
}
return 0;
}
Another great thing is, it is possible to use blitz++ without any compilation. In Visual Studio 2019, expand {project name} than right click "references" and "Manage NuGet Packages" search for blitz++. download it. No added extra linking or others have to be done.
|
71,400,724 | 71,586,963 | Copying a Public key Mod from an Intel SGX Enclave to Untrusted area | I am developing a C pseudo-API in which Java code calls C code through the JNI, in which it connects to an Intel SGX Enclave. I have a function in which I create an RSA-Key pair to be used further on.
Create RSA Pair:
sgx_status_t create_rsa_pair(){
unsigned char p_n[RSA_MOD_SIZE];
unsigned char p_d[RSA_MOD_SIZE];
unsigned char p_p[RSA_MOD_SIZE];
unsigned char p_q[RSA_MOD_SIZE];
unsigned char p_dmp1[RSA_MOD_SIZE];
unsigned char p_dmq1[RSA_MOD_SIZE];
unsigned char p_iqmp[RSA_MOD_SIZE];
int n_byte_size = RSA_MOD_SIZE;
long e = 65537;
sgx_status_t ret_create_key_params = sgx_create_rsa_key_pair(n_byte_size, sizeof(e), p_n, p_d, (unsigned char*)&e, p_p, p_q, p_dmp1, p_dmq1, p_iqmp);
if (ret_create_key_params != SGX_SUCCESS) {
ocall_print("Key param generation failed");
}
//void *private_key = NULL;
sgx_status_t ret_create_private_key = sgx_create_rsa_priv2_key(n_byte_size, sizeof(e), (unsigned char*)&e, p_p, p_q, p_dmp1, p_dmq1, p_iqmp, &private_rsa);
if(ret_create_private_key != SGX_SUCCESS) {
ocall_print("Private key generation failed");
}
void *public_key = NULL;
sgx_status_t ret_create_public_key = sgx_create_rsa_pub1_key(n_byte_size, sizeof(e), p_n, (unsigned char*)&e, &public_key);
if(ret_create_public_key != SGX_SUCCESS) {
ocall_print("Public key generation failed");
}
//Copy the result and send it in an ocall.
uint8_t* ocall_mod = (uint8_t*)malloc(RSA_MOD_SIZE);
uint8_t* ocall_exp = (uint8_t*)malloc(sizeof(long));
memcpy(ocall_mod,p_n,RSA_MOD_SIZE);
memcpy(ocall_exp,&e,sizeof(long));
printf("pre/ocall_mod::");
for(int i = 0; i < RSA_MOD_SIZE;i++){
printf("%"PRIu8",",ocall_mod[i]);
}
printf("\n");
ocall_return_pubkey(ocall_mod,ocall_exp);
return SGX_SUCCESS;
}
Ocall code:
void ocall_return_pubkey(uint8_t* key_mod,long *key_exp){
printf("Post/Ocall key-mod:: ");
for(int i = 0; i < RSA_PUBLIC_SIZE;i++)
printf("%"PRIu8",",key_mod[i]);
printf("\n");
Now, If I compile this and check terminal results:
pre/ocall_mod::199,100,141,174,148,185,21,88,102,216,116,190,170,232,156,196,107,78,228,1,5,38,92,154,20,11,234,149,74,19,254,237,240,223,145,92,188,248,25
Post/Ocall key-mod:: 199,0,0,0,0,0,0,0,0,0,57,44,0,127,0,0,0,83,144,167,247,127,0,0,9,107,99,240,0,0,0,0,172,141,193,3,0,0,0,0,68,83,144,167,247
I've posted only a portion of the mod for brevity's sake, but the information does seem to be corrupted or deleted, especially considering the large number of 0's.
I've tried passing a pointer throught the Ecall as an argument in order to receive my result through it, but (at least in this scenario), the enclave blocks the program execution due to this copy from trusted to untrusted memory, meaning that sending a pointer from the enclave through an ocall seems like the only option. Any help or tips for this?
Thanks in advance.
Edit: On a separate note, All the code I've written works if all used in a single function (Encryption, Decryption + Creation of an AES key), but if it is separated into multiple functions, it fails, for some reason.
| Using ocalls to return information is not the way to go for this.
While I had failed previously with this Idea, the way to go is by adding a pointer and its size to a functions arguments in order to copy the results.
so
Enclave EDL
public sgx_status_t whatever([out,size=output_size]uint8_t* output,size_t output_size)
Now, bear in mind that output_size is not the number of bytes written. By setting output_size = 0 before using the Ecall, the corresponding buffer inside the enclave will be NULL, returning a segfault upon usage.
if at any point you require the number of bytes written, i.e encryption, you should use the following:
sgx_status_t encrypt([out,size=output_size]uint8_t *output, size_t output_size, [out,size=num_size]size_t* bytes_written,size_t num_size);
In which num_size should be equal to sizeof(size_t).
I was able to solve this problem, Hope it helps you guys.
|
71,400,850 | 71,400,889 | Polymorphic Vectors Without Object Slicing [C++] | I am trying to store a number of objects which are derived from a base class in a std::array(or any other container) without object slicing.
The desired output from the code snippet below is:
Hi from child1!
Hi from child2!
And the code:
#include <iostream>
#include <array>
#include <memory>
class Base {
public:
void hello() {
std::cout << "This shouldn't print\n";
}
};
class Child1 : public Base {
public:
void hello() {
std::cout << "Hi from child 1!\n";
}
};
class Child2 : public Base {
public:
void hello() {
std::cout << "Hi from child 2!\n";
}
};
std::array<std::unique_ptr<Base>, 2> array = {std::make_unique<Child1>(Child1()), std::make_unique<Child2>(Child2()) };
int main() {
for (auto &i : array) {
i->hello();
}
}
The output I actually get from the code is:
This shouldn't print
This shouldn't print
Obviously the derived objects have been sliced. Is there any way to avoid this?
Thanks in advance for any advice you can offer.
|
Obviously the derived objects have been sliced.
Actually, no. They are not being sliced. You are doing the correct thing in storing base-class pointers to derived-class objects in your array.
No, the code doesn't work the way you want, not because of object slicing, but because you simply did not mark hello() as virtual in Base and as override in the derived classes. So, when you call i->hello() inside your loop, there is no polymorphic dispatch being performed.
Also, you are using std::make_unique() incorrectly. The parameters of make_unique<T>() are passed as-is to the constructor of T. In this case, you are copy-constructing your Child1/Child2 classes from temporary Child1/Child2 objects, which is not necessary. You can get rid of the temporaries.
You are also lacking a virtual destructor in Base. Which will cause undefined behavior when your array goes out of scope and the unique_ptrs try to call delete on their Base* pointers. Only the Base destructor will be called, but not the Child1/Child2 destructors.
Try this instead:
#include <iostream>
#include <array>
#include <memory>
class Base {
public:
virtual ~Base() = default;
virtual void hello() {
std::cout << "This shouldn't print\n";
}
};
class Child1 : public Base {
public:
void hello() override {
std::cout << "Hi from child 1!\n";
}
};
class Child2 : public Base {
public:
void hello() override {
std::cout << "Hi from child 2!\n";
}
};
int main() {
std::array<std::unique_ptr<Base>, 2> array = {
std::make_unique<Child1>(),
std::make_unique<Child2>()
};
for (auto &i : array) {
i->hello();
}
}
Online Demo
|
71,401,084 | 71,404,002 | Extract an autonomous chunk of the dependency graph of a huge CPP project? | Consider Chromium codebase. It's huge, around 4gb of pure code, if I'm not mistaken. But however humongous it may be, it's still modular in its nature. And it implements a lot of interesting features in its internals.
What I mean is for example I'd like to extract websocket implementation out of the sources, but it's not easy to do by hand. Ok, if we go to https://github.com/chromium/chromium/tree/main/net/websockets we'll see lots of header files. To compile the code as a "library" we're gonna need them + their implementation in .cpp files . But the trick is that these header files include other header files in other directories of the chromium project. And those in their turn include others...
BUT if there are no circular dependencies we should be able to get to the root of this tree, where header files won't include anything (or will include already compiled libraries), which should mean that all the needed files for this dependency subtree are in place, so we can compile a chunk of the original codebase separate from the rest of it.
That's the idea. At least in theory.
Does anyone know how it could be done? I've found this repo and this repo, but they only show the dependency graph and do not have the functionality to extract a tree from it.
There should be a tool already, I suppose. It's just hard to word it out to google. Or perhaps I'm mistaken and this approach wouldn't really work?
| Your compiler is almost surely capable of extracting this dependency information so that it can be used to help the build system figure out incremental builds. In gcc, for instance, we have the -MMD flag.
Suppose we have four compilation units, ball.cpp, football.cpp, basketball.cpp, and hockey.cpp. Each source file includes a header file of the same name. Also, football.hpp and basketball.hpp each include ball.hpp.
If we run
g++ -MMD -c -o football.o football.cpp
g++ -MMD -c -o basketball.o basketball.cpp
g++ -MMD -c -o hockey.o hockey.cpp
g++ -MMD -c -o ball.o ball.cpp
then this will produce, in addition to the object files, some files with names like basketball.d that contain dependency information like
basketball.o: basketball.cpp basketball.h ball.h
It's simple enough to read these into, say, a python script, and then just take the union of all the dependencies of the files you want to include.
EDIT: In fact, python may even be overkill. In the situation above, if you wanted to get all dependencies for anything containing the word "ball," you could do something like
$ cat *.d | awk -F: '$1 ~ "ball" { print $2 }' | xargs -n 1 echo | sort | uniq
which will output
ball.cpp
ball.h
basketball.cpp
basketball.h
football.cpp
football.h
If you're not used to reading UNIX pipelines, this:
Concatenates all the *.d files in the current directory;
Goes through them line-by-line, splitting each line into fields delimited by : characters;
Prints out the second field (i.e. the list of dependencies) for any line where the first field (i.e. the target) matches the regex "ball";
Splits the results into individual lines;
Sorts the resulting lines; and
Throws out any duplicates.
You can see that this produced a list of everything the ball-related files depend on, but skipped hockey.cpp and hockey.hpp which aren't dependencies of any file with "ball" in its name. (Of course in your case you might use "websockets" instead of "ball," and if there is some directory structure instead of everything being in the root directory you may have to do a bit to compensate for that.)
|
71,401,614 | 72,354,866 | How to Precompile <bits/stdc++.h> header file in ubuntu 20.04 / 22.04? | Is there any way to precompile the <bits/stdc++.h> header file in ubuntu 20.04 like we can do in Windows OS so that I can execute programs faster in my Sublime text editor?
I use the FastOlympicCoding extension for fast execution, but I miss the old way of using an input-output file. I searched everywhere but didn't find any 'layman' approach to do that.
| So, After having help from @TedLyngmo's answer and doing a little bit more research, I decided to answer the question myself with more clear steps.
PS: This answer will be more relatable to those who are using sublime with their custom build file and are on Linux OS (Ubuntu).
You need to find where stdc++.h header file is present, so open the terminal and use the command:
find /usr/include -name 'stdc++.h'
Output:
/usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h
Go to the above location and open the terminal there and now we are ready to precompile bits/stdc++.h header file.
Use the following command:
sudo g++ -std=c++17 stdc++.h
You'll observe stdc++.h.gch file is now created implying that precompiling is done.
PS: You need to use sudo as we need root privileges when g++ makes stdc++.h.gch file.
NOTE: Here as I was using the c++17 version in my custom build file so I mentioned c++17, you can use whatever version you are using.
It worked perfectly for me so I hope it helps you too!
|
71,402,386 | 71,402,444 | Cannot convert from const_Ty2* to ValueType* | template <typename ValueType> ValueType* RadixTree<ValueType>::search(std::string key) const {
typename std::map<std::string, ValueType>::const_iterator it = radixTree.find(key);
if (it == radixTree.end())
return nullptr;
return &(it->second);
}
Hello! above is my code which is a placeholder for my radixTree implementation. I don't understand why I need the typename before the std::map on the second line, and why &(it->second) would end up returning a const_Ty2*. I thought that in this case, const_Ty2 and ValueType were equivalent. The variable radixTree is currently a Map, and although I want to replace this with my radixTree implementation, I also want to understand the problem I'm getting right now. Any help would be greatly appreciated. Thank you!
Follow up:
I'm also getting an issue w/ this method
template <typename ValueType> void RadixTree<ValueType>::insert(std::string key, const ValueType& value) {
radixTree.insert(key, value);
}
and radixTree is declared as
std::map<std::string,ValueType> radixTree;
This method gives me a really long error that I can't quite understand.
std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>,std::pair<const std::string,ValueType> &&)': cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>
Can someone help me w/ this too? Thank you again!
| Your function is const and you're correctly using a const_iterator. This means that it->second is also const. When you do &it->second that becomes a const pointer which cannot be implicitly converted to a non-const pointer (such a conversion discards the const qualifier).
It's unclear why you want a non-const pointer to an internal value. I have to presume it's an error. You should change the return type to const ValueType*.
Regarding the edit you just made to your question:
radixTree.insert(key, value);
The message is telling you that the function arguments are wrong. Check the documentation for the insert function. You'll find that it requires a value_type which is a std::pair<const Key, T>. The useful part of the error is here:
cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>
There it is trying to match a call that has two arguments, which the overload resolution is trying to resolve it to insert(const_iterator hint, const value_type &value). That should tell you something is wrong.
Try this:
radixTree.insert(std::make_pair(key, value));
|
71,402,605 | 71,402,636 | Copy Constructor Error With a Template Linked List Class : no matching function for call to 'Node<int>::Node()' | I'm trying to make a copy constructor for a linked list but I'm not sure how to fix this error and I've been looking for hours. The error is:
no matching function for call to 'Node::Node()'
Here is the code:
template <class T>
class Node //node is the name of class, not specific
{
public:
T data; //t data allows for any type of variable
Node *next; //pointer to a node
Node(T Data) //assign data value
{
data = Data; //makes data = NV parameter
next = nullptr; //makes next = to nullptr
}
};
template <class T>
class LinkedList
{
private:
Node<T> * head, *tail; //// typedef Node* head // -- head = Node* -- //// typedef Node* nodePtr = Node* ////
public:
LinkedList() //constructor for Linked List
{
head = nullptr;
tail = nullptr;
}
LinkedList(LinkedList& copy)
{
head = nullptr;
tail = nullptr;
Node<T>* Curr = copy.head;
while(Curr) //while not at end of list
{
//val = copyHead->data;
Node<T>* newCpy = new Node<T>;
newCpy->data = Curr->data;
newCpy->next = nullptr;
if(head == nullptr)
{
head = tail = newCpy;
}
else
{
tail->next = newCpy;
tail = newCpy;
}
}
}
~LinkedList()
{
while (head)
{
Node<T>* tmp = head;
head = head->next;
delete(tmp);
}
head = nullptr;
}
| The class Node does not have the default constructor. It has only the following constructor
Node(T Data) //assign data value
{
data = Data; //makes data = NV parameter
next = nullptr; //makes next = to nullptr
}
And in this statement
Node<T>* newCpy = new Node<T>;
there is used the default constructor that is absent.
At least instead of these three statements
//val = copyHead->data;
Node<T>* newCpy = new Node<T>;
newCpy->data = Curr->data;
newCpy->next = nullptr;
you need to write
//val = copyHead->data;
Node<T>* newCpy = new Node<T>( Curr->data );
Pay attention to that within the while loop
while(Curr)
{
//...
}
the pointer Curr is not changed. So the loop is infinite if Curr is not a null pointer
It seems you forgot to insert this statement
Curr = Curr->next;
before the closing brace of the loop.
|
71,402,872 | 71,403,055 | Question about operator new overload and exception | Why this code snippet ouputs a lot of "here"?
I think the program should terminate when after throw std::invalid_argument( "fool" ); has been called.
#include <memory>
#include <iostream>
void* operator new(std::size_t size)
{
std::cout << "here" << std::endl;
throw std::invalid_argument( "fool" ); //commit out this, there would be many many ouputs
return std::malloc(size);
}
void operator delete(void* ptr)
{
return free(ptr);
}
int main()
{
//std::unique_ptr<int> point2int(new int(999));
int* rawpoint2int = new int(666);
}
| The documentation for std::invalid_argument holds the clue:
Because copying std::invalid_argument is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking std::string&&: it would have to copy the content anyway.
You can see that the string argument is copied by design. This means that re-entering new is pretty much guaranteed if you are throwing this exception in this way.
You should also be aware that malloc can return nullptr which will violate the design of operator new which should either return a valid pointer or throw.
The normal kind of exception to throw in this case is std::bad_alloc. I cannot imagine why you are wanting to throw std::invalid_argument. I thought perhaps you were encountering this issue in a constructor somewhere and decided to test the allocation itself.
Technically you can resolve the problem by passing a default-constructed string as the argument:
// ... but, why would you do this?!! :(
throw std::invalid_argument(std::string()); // will not allocate
Eww, yucky. I recommend you find a more appropriate exception to throw (if you actually need one), or create your own non-allocating exception.
|
71,404,743 | 71,405,801 | C++ getline function missing the first line of txt file | I have written a function to read from .txt file and build a linked list, but the function missed the first line of the file. Anyone have any idea why that happens?
output:
//empty line
gmail
San Francisco
123456
.txt file
person1
gmail
San Francisco
123456
readFile function
void list::readFile(std::string fileName){
fstream fs;
string dummy = "";
string firstline;
record * previous = new record;
record * temp = new record;
int recordCount = 0;
fs.open(fileName, ios::in | ios::binary);
do{
std::getline(fs, temp->name);
std::getline(fs, temp->email);
std::getline(fs, temp->address);
fs >> temp->phoneNo;
std::getline(fs, dummy);
recordCount++;
if(head == NULL){
head = temp;
previous = temp;
tail = temp;
} else {
previous->next = temp;
previous = temp;
tail = temp;
}
} while(!fs.eof());
// } else {
// cout << "there's no record in the file yet." << endl;
// }
cout << head->name << endl;
cout << head->address <<endl;
cout << head->email << endl;
cout << head->phoneNo << endl;
}
| You create a single node so every iteration through the loop you overwrite the previously read values.
In the second iteration of the while loop your first call to getline presumably fails and sets the value of name to an empty string. As the stream is now in a failed state the rest of your reads are ignored and finally the loop breaks at the end of the loop.
This might be closer to what you wanted:
int recordCount = 0;
fs.open(fileName, ios::in | ios::binary);
while(fs) {
record * temp = new record;
std::getline(fs, temp->name);
std::getline(fs, temp->email);
std::getline(fs, temp->address);
fs >> temp->phoneNo;
if (!fs) {
// Reading failed, delete the temporary and exit the loop
delete temp;
break;
}
std::getline(fs, dummy);
recordCount++;
if(head == NULL){
head = temp;
previous = temp;
tail = temp;
} else {
previous->next = temp;
previous = temp;
tail = temp;
}
}
Your code could be made memory leak safer by using smart pointers to ensure temp is never leaked even if exceptions are thrown.
|
71,404,856 | 71,404,857 | How to make proxying const/ref/volatile qualification without duplication in C++? | Say I want to write some "proxy" object for a callable, e.g. to add some feature that happens before the wrapped callable is invoked. Further, say I want to be const-correct, so that the proxy has an accessible non-const operator() only if the wrapped callable does. Then I need to do something like this, defining two versions of the operator and using SFINAE:
template <typename F>
struct Proxy {
F wrapped;
template <typename = std::enable_if_t<std::is_invocable_v<F&>>>
auto operator()();
template <typename = std::enable_if_t<std::is_invocable_v<const F&>>>
auto operator()() const;
};
This is annoying enough, but if I also want to proxy ref qualifications now I need for overloads, which is really getting excessive. Heaven help me if I also want to proxy volatile qualfiication.
Is there a shortcut to make this less awful? I seem to recall there was at least a feature proposed for addition to the standard.
| The proposed feature I was thinking of was P0847R7 ("Deducing this"), which was accepted for C++23. There are some useful slides here. I don't have a compiler to check this with, but I believe my four operators could be written as one with something like the following:
template <typename F>
struct Proxy {
F wrapped;
template <typename Me>
requires std::invocable<std::like_t<Me, F>>
auto operator()(this Me&& me);
};
(The type requirement here uses the hypothetical like_t metafunction assumed by P0847R7. See this question.)
|
71,404,906 | 71,412,204 | In C++ is there a proposed type traits helper for "copying" reference category and cv-qualification? | For the SFINAE in the hypothetical call operator in this answer I need a type trait that "copies" reference category and const/volatile qualifications from one type to another:
template <typename T, typename U>
using copy_category_and_qualifications_t = [...];
copy_category_and_qualifications_t<int, char> // char
copy_category_and_qualifications_t<const int&, char> // const char&
copy_category_and_qualifications_t<volatile int&&, char> // volatile char&&
I seem to recall some proposed addition to type_traits for this. Does anybody have a reference to this proposal, or know if it was added for C++20 or C++23?
| P1450 called this copy_cvref and clone_cvref (the former just applies the qualifiers to the 2nd parameter, the latter first removes the qualifiers from the 2nd parameter). The former is useful, I don't think I've ever personally had a need for the latter.
P0847 uses like_t and forward_like in a few contexts, like_t there is basically P1450's copy_cvref (the latter is... a significantly better name). forward_like is separately proposed in P2445 (though without the other type trait helper).
|
71,405,497 | 71,405,948 | C++ Vector Operations | Is there any alternative for this? Performing a vector operation in multiples on certain condition?
i want to perform erase vector operation (n-1) times, just deleting only first element in a particular vector on a given if condition.
is it possible to do like this
if ( ret.size() == n ){
(n-1)*order.erase(order.begin());
(n-1)*quantity.erase(quantity.begin());
(n-1)*price.erase(price.begin());
}
I am currently doing this
if ( ret.size() == 2 ){
order.erase(order.begin());
quantity.erase(quantity.begin());
price.erase(price.begin());
}
if ( ret.size() == 3 ){
order.erase(order.begin());
order.erase(order.begin());
quantity.erase(quantity.begin());
quantity.erase(quantity.begin());
price.erase(price.begin());
price.erase(price.begin());
}
| order.erase( order.begin(), order.begin() + ( ret.size() - 1 ) );
Needs prior checking of ret.size() vs. order.size() of course, but it seems your code can assert that from context.
That being said, when you are repeatedly erasing from the beginning of your vectors, perhaps your vectors are sorted the wrong way, or you might be better off with std::deque, performance-wise.
Edit: From the comments, it appears that your actual problem is "how to remove all but the last element of a vector". There are a number of ways to do this, like
// actually erasing all but the last
order.erase( order.begin(), order.end() - 1 );
...or...
// creating a new vector with the last element of the old
order = vector< ... >{ order.back() };
(The elipsis here standing for the type of your order vector, not the actual elipsis -- you will have to fill in that part.)
|
71,405,806 | 71,453,562 | CMake one build directory for multiple projects with seperate context | I'm trying to build multiple projects within one build directory with the following structure:
|------ CMakeLists.txt (The main Cmake)
|
|------ ProjectAPP
| |----- .c/h files
| |----- sdh_config.h
| |----- CMakeList.txt
|
|------ ProjectDFU
| |----- .c/h files
| |----- sdh_config.h
| |----- CMakeList.txt
|
|-------- SDK
| |---- SDK used by both projects
The idea would be to build two independent projects, both built on top of one single SDK. Note that both projects rely on a different configuration of the SDK, done by their respective sdk_config.h.
The main CMakeList.txt looks like this:
cmake_minimum_required(VERSION 3.22)
project(project)
add_dependency(ProjectAPP)
add_dependency(ProjectDFU)
add_custom_target(app DEPENDS ${exec_target_app}
...
)
add_custom_target(dfu DEPENDS ${exec_target_dfu}
...
)
add_custom_target(merge DEPENDS app dfu
...
)
Basically my only use of building the two projects in the same place is that I'm then able to have targets depending on both executables so I can then do something with that.
My problem:
The SDK, cmake based, is fragmented in hundreds of small libraries like this:
add_library(lib INTERFACE
"file1.c"
"file2.c"
)
Most of theses libraries will be used by both projects but with different build parameters (cf. sdk_config.h).
Where I'm at right now, I'm getting the following error:
add_library cannot create target "lib" because another target with the same name already exists.
The existing target is an interface library created in source directory "ProjectAPP".
See documentation for policy CMP0002 for more details.
My question:
What would be the best way to isolate both projects in two different build contexts while still being able to have dependencies on each project at root level?
Thank you in advance for any help.
| Answering my own question, I'm not sure if it'ss the best way to handle this but cmake ExternalProject solved my problem.
|
71,406,224 | 71,412,198 | Running pgc++ programs on Cluster | I tried to run the below OPenACC program on cluster:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
#pragma acc parallel loop
for (int i=0; i<1000; i++)
{
//cout << i << endl;
printf("%d ", i);
}
return 0;
}
The PBS Script for the above code:
#PBS -e errorlog1.err
#PBS -o logfilehello.log
#PBS -q rupesh_gpuq
#PBS -l select=1:ncpus=1:ngpus=1
tpdir=`echo $PBS_JOBID | cut -f 1 -d .`
tempdir=$HOME/scratch/job$tpdir
mkdir -p $tempdir
cd $tempdir
cp -R $PBS_O_WORKDIR/* .
module load nvhpc-compiler
#module load cuda10.1
#module load gcc10.3.0
#module load nvhpc-21.11
#module load nvhpc-pgicompiler
#module load gcc920
pgc++ sssp.cpp
./a.out > output.txt
rm *.out
mv * $PBS_O_WORKDIR/.
rmdir $tempdir
~
After submmitting the above job to que, I get the following error log:
"sssp.cpp", line 2: catastrophic error: cannot open source file "iostream" #include <iostream>
^
1 catastrophic error detected in the compilation of "sssp.cpp". Compilation terminated.
I tried running C programs on pgcc and they work fine. Running c++ programs on pgc++ is throwing error. What could be the reason?
|
What could be the reason?
In order to be interoperable with g++, pgc++ (aka nvc++) uses the g++ STL and system header files. Since the location of these headers can vary, on installation a configuration file, "localrc", is created to store these locations.
What could be happening here is that on install, a single system install was selected and hence the generated localrc is for the system from which the compilers were installed, not the remote system.
If this is the case, consider re-installing with the "network" option. In this case, the creation of the localrc is delayed until the first compiler invocation with a unique localrc generated for each system.
Another possibility is that creating of the localrc file failed for some unknown reason. Possibly a permission issue. To check, you can run the 'makelocalrc' utility to see if any errors occurred.
Note for newer versions of nvc++, we are moving away from using pre-generated config files and instead determining these config items each time the compiler is invoked. The pervious concern being the overhead involved in generating the config, but this has become less of a problem.
|
71,406,688 | 71,406,799 | Can a reference prolong the lifetime of any member data of a class which is returned by a mamber function | class sample
{
std::string mString;
public:
void Set(const std::string &s)
{
mString = s;
}
//std::string Get() const
const std::string& Get() const
{
return mString;
}
};
Let's say I have such a class as above and now I use this class like this:
sample *p = new sample;
p->Set("abcdefg");
const std::string& ref = p->Get();
delete p;
p = nullptr;
std::cout << ref << std::endl;
As you see, the member function Get returns a reference, which is assigned to the outer reference ref. After that, the whole object is deleted.
However, it seems that this code works without any error.
I'm a little confused. It could run just because I'm lucky or it's the reference ref that prolongs the lifetime of the member variable mString?
| No, lifetime extension by reference binding applies only to temporary objects materialized from prvalues.
Objects created with new never have their lifetime extended past delete.
What you are seeing here is just a manifestation of undefined behavior. ref is dangling after delete p; and therefore reading from it in the cout statement has undefined behavior.
If Get was returning by-value (std::string Get() const), then it would be true that the temporary materialized from the return value of the function would have its lifetime extended to that of the reference ref.
And in that case the program behavior would be well-defined.
Similarly if the sample object had automatic storage duration, the reference would not extent its lifetime or the lifetime of one of its subobjects either:
/* DO NOT USE: Undefined behavior */
const std::string& ref = []() -> const std::string& {
sample s;
p.Set("abcdefg");
return s->Get();
// lifetime of s ends with function returning
}();
/* UNDEFINED BEHAVIOR */
std::cout << ref << std::endl;
Here it is the lambda's return type that would need to be changed from const std::string& to std::string to avoid the UB. Only the first reference binding can extent lifetime and therefore changing the return type of Get would not be sufficient in this case.
|
71,406,787 | 71,407,138 | Is providing a deleter explicitly required when storing array types inside smart pointers? | According to this paper, one of the common mistakes developers make ( #3 ) is using a smart pointer with array types; Mainly because the operator delete will be called instead of delete[], leaving the program with a memory leak.
Depite that; looking up default deleter in the C++ reference, the following code is there:
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
// {
// std::shared_ptr<int> shared_bad(new int[10]);
// } // the destructor calls delete, undefined behavior
{
std::shared_ptr<int> shared_good(new int[10], std::default_delete<int[]>());
} // the destructor calls delete[], ok
{
std::unique_ptr<int> ptr(new int(5));
} // unique_ptr<int> uses default_delete<int>
{
std::unique_ptr<int[]> ptr(new int[10]);
} // unique_ptr<int[]> uses default_delete<int[]>
// default_delete can be used anywhere a delete functor is needed
std::vector<int*> v;
for(int n = 0; n < 100; ++n)
v.push_back(new int(n));
std::for_each(v.begin(), v.end(), std::default_delete<int>());
}
Which directly contradicts that; But this might be because of different C++ standards; Is this the case, or is #3 in the paper simply untrue?
Does a deleter needs to be provided explicitly when using arrays with smart pointers, or does it depend on the c++ standard ( e.g. different behaviour in C++11 or c++17; c++20 ); or the platform (e.g. gcc, MSVC etc.. )?
| If I understand correctly, you seem to think that the example 4 contradicts the paper, and the paper recommends using example 2. This is not what the paper is saying.
Example 1 is undefined behavior, as described in the paper: "Using smart pointers, such as auto_ptr, unique_ptr, shared_ptr, with arrays is also incorrect."
Example 2 works correctly, however using a custom deleter is not mentioned in the paper at all.
Example 3 creates pointer to single int. This is not related to the paper.
Example 4 creates pointer to int[], which is mentioned in the paper as a valid usage: "If using of a smart pointer is required for an array, it is possible to use -- a unique_ptr<T[]> specialization."
|
71,406,883 | 71,407,443 | c++: undefined reference to `Json::Value::Value(Json::ValueType)' | I installed jsoncpp on ubuntu with 'sudo apt-get install libjsoncpp-dev' and tried to run a minimalistic test program:
#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>
int main()
{
ifstream file("example.json");
Json::Value value;
Json::Reader reader;
reader.parse(file,value);
cout << value << endl;
}
I'm using a makefile to compile my code with the following flags:
CC=g++
CXXFLAGS=-std=c++17 -fopenmp -O3 -ljsoncpp
The following errors occur:
/usr/bin/ld: /tmp/cc4MbV6f.o: in function `Test_JsonWriter()':
test.cpp:(.text+0x5865): undefined reference to `Json::Value::Value(Json::ValueType)'
/usr/bin/ld: test.cpp:(.text+0x5872): undefined reference to `Json::Reader::Reader()'
/usr/bin/ld: test.cpp:(.text+0x5885): undefined reference to `Json::Reader::parse(std::istream&, Json::Value&, bool)'
/usr/bin/ld: test.cpp:(.text+0x5894): undefined reference to `Json::operator<<(std::ostream&, Json::Value const&)'
/usr/bin/ld: test.cpp:(.text+0x5a9f): undefined reference to `Json::Value::~Value()'
/usr/bin/ld: /tmp/cc4MbV6f.o: in function `Test_JsonWriter() [clone .cold]':
test.cpp:(.text.unlikely+0x6bf): undefined reference to `Json::Value::~Value()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:21: test] Error 1
I also made sure to update all packages etc. Also including '#include <jsoncpp/json/value.h>' doesn't help either.
Any idea what is wrong? Thanks for the help.
| The comment by user17732522 has solved my issue!
The flags are placed incorrectly:
"-ljsoncpp must be placed after the names of the .cpp files or .o files on the compiler invocation" -user17732522
|
71,406,952 | 71,407,500 | Cmake project set LANGUAGES from variable | currently I've got the following project definition :
set(supported_languages "CXX OBJC OBJCXX")
project(
myProj
VERSION ${ver}
LANGUAGES ${supported_languages})
where supported_languages is defined as string of parameters delimited by space
(i.e. CXX OBJC OBJCXX)
However, it fails since cmake expect to get a list and this is the error I get
CMake Error: Could not find cmake module file: CMakeDetermineCXX OBJC OBJCXXCompiler.cmake
So I've tried to convert it to list list(${supported_languages}) but it still doesn't work.
I wonder what is the best practice to make it work ?
| that error is because (") characterer
lets try this
set(supported_languages CXX OBJC OBJCXX)
project(
myProj
VERSION ${ver}
LANGUAGES ${supported_languages})
|
71,407,174 | 71,408,392 | Testing templated classes with functions defined in CPP file | For a project that I am working on, I need to mock certain classes for testing to test different behaviours of functions. For testing I use gtest. Because I am working on a game, the speed and efficiency of the code is of the essence. Because of this requirement I do not want to mock my classes by using virtual functions, but I want to mock my classes with templates, so the implementation of the classes will be defined at compile time and I do not lose performance at run time. Furthermore, because I want to have the least amount of code bloat in my other header/source files I want to split my files into headers and source files, so that some of the includes can be set in the source file. This approach however comes with a couple of problems.
Because the templated functions are defined in a source file, there will need to be an explicit definition of the classes in the source file. Otherwise these templated functions will throw an 'undefined external symbol' error at compile time. This would not be a problem if I did not have two different projects, one for the game and one for testing, as I can't make an explicit definition of a mock in the test project.
I have tried a couple of solutions, but all of them have drawbacks. I will try to demonstrate what I have done with the following piece of code: (I know and use GMock, but this is an easier example)
//Game project
//Foo.h
<template class Bar>
class Foo
{
public:
Bar bar;
bool ExampleFunction();
}
//Foo.cpp
#include "Foo.h"
<template class Bar>
bool Foo::ExampleFunction()
{
return bar.Func() > 10;
}
//Testing project
//BarMock.h
class BarMock
{
public:
int Func();
int value;
}
//BarMock.cpp
#include "BarMock.h"
Bar::Func()
{
return value;
}
//TestFoo.cpp
#include "Foo.h"
TEST(Tests, TestExample)
{
Foo<BarMock> mocked;
mocked.bar.value = 100;
ASSERT_TRUE(mocked.ExampleFunction());
}
Solution 1: Include cpp file in testing project
This is already error prone, as including a cpp file is usually a no go. But if I only include the cpp file ONCE somewhere in the testing project it will not give me the 'c function already defined' error. This in my opinion is not a solid solution (although it is the solution I am currently using), because if I do need a templated class in 2 locations of my testing project this will (almost) always give an error.
//TestFoo.cpp
#include "Foo.h"
#include "Foo.cpp" // error prone, but does compile
TEST(Tests, TestExample)
{
Foo<BarMock> mocked;
mocked.bar.value = 100;
ASSERT_TRUE(mocked.ExampleFunction());
}
Solution 2: Create definitions in header file
This is less error prone, but comes with some other drawbacks. Like I have stated before I want to keep the bloat to a minimum, but with this solution I will also include all of the headers of the Foo header (say I need in Foo and include foo somewhere, then in somewhere I will also have ).
//Game project
//Foo.h
<template class Bar>
class Foo
{
public:
Bar bar;
bool ExampleFunction()
{
return bar.Func() > 10;
}
}
//Foo.cpp removed
Solution 3: Create virtual functions for mocks
This is my least favourite option, but it should be mentioned. Like I have stated before, this comes with a runtime performance hit and I do not want to change most of my functions to virtual functions. But in this way you will not get errors.
//BarMock.h
class BarMock
{
public:
int Func() override;
int value;
}
//BarMock.cpp
#include "BarMock.h"
Bar::Func() override
{
return value;
}
Which one of these options is the best? Is there any method that I have missed? I would love to hear someone's opinion about this as I could not find a 'good' solution online.
| A variation of solution #1 by renaming the files:
Foo.h
#pragma once // or/and header guards
<template class Bar>
class Foo
{
public:
Bar bar;
bool ExampleFunction();
};
Foo.inl (or other extension .inc, .ixx, ...)
#pragma once // or/and header guards
#include "Foo.h"
template <class Bar>
bool Foo<Bar>::ExampleFunction()
{
return bar.Func() > 10;
}
Foo.cpp
#include "Foo.h"
#include "Foo.inc"
#include "Bar.h"
// explicit instantiation
template <> struct Foo<Bar>;
FooTest.cpp
#include "Foo.h"
#include "Foo.inc"
#include "BarMock.h"
// Testing code...
|
71,407,289 | 71,408,772 | Saxon .NET with C++ CLI | I had an idea to use C++ CLI to interact with the Saxon .NET interface . The problem is that every single example on Saxonica is with C# , and not C++ . can you give me an example that caches an XML file , and using Xslt filepaths to transform it using C++ CLI to use the .NET interface ???
Also pls dont give me workarounds that dont use C++ CLI
| A minimal sample using Saxon .NET HE 10 (tested with 10.6 initially, now updated to 10.7) run on Windows against .NET framework 4.8 is e.g.
#include "pch.h"
using namespace System;
using namespace Saxon::Api;
int main(array<System::String ^> ^args)
{
Processor^ processor = gcnew Processor();
Console::WriteLine(processor->ProductVersion);
DocumentBuilder^ docBuilder = processor->NewDocumentBuilder();
Uri^ baseUri = gcnew Uri(System::Environment::CurrentDirectory + "\\");
XdmNode^ inputDoc = docBuilder->Build(gcnew Uri(baseUri, "input-sample1.xml"));
XsltCompiler^ xsltCompiler = processor->NewXsltCompiler();
xsltCompiler->BaseUri = baseUri;
XsltExecutable^ xsltExecutable = xsltCompiler->Compile(gcnew Uri(baseUri, "sheet1.xsl"));
Xslt30Transformer^ xslt30Transformer = xsltExecutable->Load30();
xslt30Transformer->ApplyTemplates(inputDoc, processor->NewSerializer(Console::Out));
return 0;
}
Example project at https://github.com/martin-honnen/SaxonHECLIExample1.
To write to a file instead, use e.g.
FileStream^ resultStream = File::OpenWrite("result1.xml");
xslt30Transformer->ApplyTemplates(inputDoc, processor->NewSerializer(resultStream));
resultStream->Close();
instead of xslt30Transformer->ApplyTemplates(inputDoc, processor->NewSerializer(Console::Out));; example adaption is at https://github.com/martin-honnen/SaxonHECLIExample1/tree/WriteToFileInsteadOfConsole
|
71,407,360 | 71,407,536 | how to define functor as third template class of map? | I am trying to define a map::key_comparator type, but I have no idea how to write the class type of functor std::less and std::greater.
// not compilable
using MapTree = std::map<int, string, std::map::key_compare >;
void funct(MapTree& a) {
a.push_back({1, "a"});
a.push_back({3, "d"});
a.push_back({10, "b"});
};
// usage
std::map<int, string, std::less<int>> s;
funct(s); // should produce s sorted in order of less
std::map<int, string, std::greater<int>> c;
funct(c); // should produce c sorted in order of greater
| You need to make it a template; different std::map instantiations are distinct types.
If you want specific key and value types, use a partial specialization.
template<typename Order>
using MapTree = std::map<int, string, Order>;
template<typename Order>
void funct(MapTree<Order>& a) {
// ...
|
71,408,568 | 71,409,362 | ELF symbol name occurs twice (.data.rel.ro and .bss) | in my library (ELF arm64, Android) I see the same mangled symbol name twice (names changed):
>> nm --format sysv libAPP.so.dbg | grep _ZL15s_symbolNameXYs
_ZL15s_symbolNameXYs|0000000003a9c758| d | OBJECT|0000000000000578| |.data.rel.ro
_ZL15s_symbolNameXYs|0000000016604940| b | OBJECT|00000000000005c0| |.bss
I thought names must be unique? what is the reason for that?
I dont have the C/C++ code for the library, if you know what code generates this I would be very happy.
Thanks
Update:
also this happens, which makes even less sense to me:
>> nm --format sysv --defined-only libAPP.so.dbg | grep _ZL12aisomes_list
_ZL12aisomes_list |0000000000834780| r | OBJECT|0000000000000030| |.rodata
_ZL12aisomes_list |0000000000834980| r | OBJECT|0000000000000030| |.rodata
| Lower case letters in the symbol type (in your example, d, b, and r) indicate local symbols. These are not subject to linkage and may hence appear multiple times in the same binary. There is nothing wrong with that.
The main source of such symbols are local symbols in object files. The linker just transfers the local symbols of all object files involved into the symbol table of the binary without linking them together. So most likely, multiple object files defined a local symbol named _ZL15s_symbolNameXYs.
|
71,408,644 | 71,428,556 | Extend an interface whilst not having to reimplement its functions | I'm struggling with interface inheritance a little. What I'm trying to achieve is that I would like to extend an interface, whilst not having to reimplement all of its functions by reusing the function implementations from an implementation of the parent interface. Is this even possible?
So suppose I have two interfaces, from which the second (IB) inherits from the first (IA)
class IA
{
public:
virtual void funcA() const = 0;
};
class IB : public IA
{
public:
virtual void funcB() const = 0;
};
class AImpl : public IA
{
public:
virtual void funcA() const override {std::cout << "funcA from AImpl" << std::endl;};
};
class BImpl: public IB
{
public:
virtual void funcA() const override {std::cout << "funcA from BImpl" << std::endl;};
virtual void funcB() const override {std::cout << "funcB" << std::endl;};
};
int main()
{
BImpl b = BImpl();
b.funcA();
b.funcB();
return 0;
}
which obviously gives me the expected output
funcA from BImpl
funcB
However, what I'd rather like to have is that BImpl uses the implementation of funcA from AImpl (as if it would only inherit from AImpl):
funcA from AImpl
funcB
I tried to have BImpl inherit from IB and AImpl, but that dosn't work (BImpl becomes abstract if I don't implement funcA again). The reason why I don't have BImpl inherit only from AImpl and add funcB is that I'd like to have a separate interface (IB) to code against for objects of type BImpl which, at the same time, allows me to call funcA without casting the objects to type IA (hence the interface inheritance).
// EDIT START (10th March)
That is, I'd like my business logic to look like this
int main()
{
IB* b = new BImpl();
b->funcA();
b->funcB();
return 0;
}
which requires IB to inherit from IA.
// EDIT END
Any ideas? Ideally, I would not even have to make funcA in BImpl a wrapper for funcA in AImpl (as said, as if I was inheriting from AImpl alone)
| Use virtual inheritance to take advantage of function dominance rules.
I'm rusty on how exactly dominance works, but it happens to do the right thing in this case.
#include <iostream>
class IA
{
public:
virtual void funcA() const = 0;
};
class IB : public virtual IA
{
public:
virtual void funcB() const = 0;
};
class AImpl : public virtual IA
{
public:
void funcA() const override {std::cout << "funcA" << std::endl;};
};
class BImpl : public AImpl, public IB
{
public:
void funcB() const override {std::cout << "funcB" << std::endl;};
};
int main()
{
BImpl b;
b.funcA(); // funcA
b.funcB(); // funcB
return 0;
}
|
71,408,718 | 71,453,554 | Is use in an unused default member initializer still an odr-use? | Is use in a default member initializer still an odr-use, even if the default member initializer is not used by any constructor?
For example, is this program ill-formed because g<A> is odr-used and therefore its definition implicitly instantiated?
template<typename T>
void g() { sizeof(T); }
struct A;
struct B {
B() : i{} {};
int i = (&g<A>, 0);
};
int main() { }
MSVC thinks no. Clang, GCC and ICC think yes. https://godbolt.org/z/zrr9oEdfe
| As stated in the comments, g<A> is odr-used. However, there is a definition for it available, so there is no non-diagnosable violation here; MSVC is wrong to accept it. (This is true even without the constructor declaration; the implicitly declared B::B() is never defined, but the default member initializer is still an odr-use like it is here.)
|
71,408,938 | 71,409,105 | Conditionally defined variable (static if) | In multiple cases I would want to use something like
template<bool condition>
struct S
{
int value;
if constexpr(condition) /*#if condition*/
double my_extra_member_variable;
/*#endif*/
}
or
if constexpr(sizeof...(Ts) != 0)
// define something extra ( a tuple or so )
This is possible with preprocessor flags, but we want to be the "cool kids" that don't use preprocessor flags, but rather metaprogramming
It could also work with specilizations in some cases, but assume you have multiple conditions, and multiple member variables that need to be conditionally activated, it could get nasty quite fast.
I tried
constexpr in_series_production_mode = false;
struct dummy{ dummy(auto& x){}; operator=(auto& x){return *this;} }; /*1 byte*/
struct debug_data_t { /* lots of parameters with big size*/};
template <typename T>
using maybe_empty = typename std::conditional<in_series_production_mode ,T,dummy>::type;
maybe_empty<debug_data_t> my_debugging_variable;
But with that you still get 1 byte for the unused dummy variable. While if you used #if of something similar you would have needed 0 bytes.
Does anybody know a better practice for that?
| In C++20, the "good enough" solution is with the [[no_unique_address]] attribute
struct empty_t {};
template<bool condition>
struct S {
[[no_unique_address]]] std::conditional_t<condition, double, empty_t> var;
};
It's not perfect because var is always defined, but it will not take any space. Note that if there are multiple variables, you will need them to be different types, e.g.
template<int>
struct empty_t {};
template<bool condition>
struct S {
[[no_unique_address]]] std::conditional_t<condition, double, empty_t<0>> var;
[[no_unique_address]]] std::conditional_t<condition, double, empty_t<1>> rav;
};
|
71,409,168 | 71,410,855 | How to pass 2d numpy array to C++ pybind11? | In C++ pybind11 wrapper:
.def("calcSomething",
[](py::array_t<double> const & arr1,
py::array_t<double> const & arr2)
{
// do calculation
}
)
In python:
example.calcSomething(
arr1=np.full((10, 2), 20, dtype='float64'),
arr2=np.full((10, 2), 100, dtype='float64')
)
And I got this error message:
ValueError: array has incorrect number of dimensions: 2; expected 1
So how should I pass 2d or nd array to pybind11?
| In pybind11 array_t is an n-dimensional array, just like a numpy array.
So there are no restrictions on dimensionality.
The error message is probably coming from somewhere else. Not from pybind11.
At least the code you show should not cause this behavior.
|
71,409,301 | 71,409,737 | error: invalid use of member <...> in static member function | I'm encountering this error when I'm trying to use the content of my map 'freq' declared as a class variable, inside my comparator function for sorting the vector(using map to sort the vector elements by frequency). Can anyone highlight where am i going wrong and what should I do?
Here's the code:
class Solution {
map<int, int> freq;
public:
static bool comp(int a, int b){
if(a!=b){
int c1 = freq[a];
int c2 = freq[b];
if(c1!=c2)
return c1<c2;
else{
return a>b;
}
}
return a>b;
}
vector<int> frequencySort(vector<int>& nums) {
for(int i:nums){
freq[i]++;
}
sort(nums.begin(), nums.end(), comp);
return nums;
}
};
Error is:
Line 6: Char 22: error: invalid use of member 'freq' in static member function
int c1 = freq[a];
^~~~
| static functions cannot access member objects. But if you make comp a non-static member function, you can no longer pass it to sort.
A solution is to make comp non-static and wrap it in a lambda in the call to sort, something like:
class Solution {
map<int, int> freq;
public:
bool comp(int a, int b){
if(a!=b){
int c1 = freq[a];
int c2 = freq[b];
if(c1!=c2)
return c1<c2;
else{
return a>b;
}
}
return a>b;
}
vector<int> frequencySort(vector<int>& nums) {
for(int i:nums){
freq[i]++;
}
sort(nums.begin(), nums.end(), [this](int a, int b) { return comp(a,b); });
return nums;
}
};
|
71,409,432 | 71,409,562 | Standard hash with variadic template | I have the following code:
namespace foo {
template<typename ...Types>
class Pi {
};
}
namespace std {
template<> //line offending gcc 8.3.1
template<typename ...Types>
struct hash<foo::Pi<Types...>> {
std::size_t operator()( const foo::Pi<Types...>& s ) const noexcept {
return 0;
}
};
}
int main() {
return 0;
}
Using gcc 8.3.1 I receive the error too much parameters template-parametr-list, while using gcc 4.8.3 it works. If I remove the commented line above it works, is it correct however?
| The newer GCC version is correct.
template<> is not valid syntax here. It is only used for explicit specialization of a template.
What you are doing here is partial specialization of std::hash, since you are not specializing for just one specific type, but all types that could be instantiated from foo::Pi. Without template<> you have the correct syntax for partial specialization.
|
71,409,758 | 71,411,209 | using libfmt to format to a string | using libfmt to print to a file is very convenient:
auto file = fmt::output_file(filename);
file.print(...);
But how can I format to a memory buffer, ultimatiley converting to a string? I would imagine something like
auto buf = some_buffer_object{};
buf.print(...);
std::string s = buf.get_string();
But I can find no such buffer type in the documentation (fmt::memory_buffer seems related, but does not work like this).
Important: I need multiple calls to print, so auto s = fmt::format(...) is not an option.
|
how can I format to a memory buffer, ultimatiley converting to a string?
Use format_to and print to an iterator the appends to a string.
|
71,409,810 | 71,417,692 | Meaning of std::forward<std::decay_t<F>>(f) | I have a question about the code written in https://koturn.hatenablog.com/entry/2018/06/10/060000
When I pass a left value reference, if I do not remove the reference with std::decay_t, I get an error.
Here is the error message
'error: 'operator()' is not a member of 'main()::<lambda(auto:11, int)>&
I don't understand why it is necessary to exclude the left value reference.
I would like to know what this error means.
#include <iostream>
#include <utility>
template <typename F>
class
FixPoint : private F
{
public:
explicit constexpr FixPoint(F&& f) noexcept
: F{std::forward<F>(f)}
{}
template <typename... Args>
constexpr decltype(auto)
operator()(Args&&... args) const
{
return F::operator()(*this, std::forward<Args>(args)...);
}
}; // class FixPoint
namespace
{
template <typename F>
inline constexpr decltype(auto)
makeFixPoint(F&& f) noexcept
{
return FixPoint<std::decay_t<F>>{std::forward<std::decay_t<F>>(f)};
}
} // namespace
int
main()
{
auto body = [](auto f, int n) -> int {
return n < 2 ? n : (f(n - 1) + f(n - 2));
};
auto result = makeFixPoint(body)(10);
std::cout << result << std::endl;
}
| ,The code you have shared is toxic.
template <typename F>
class FixPoint : private F
{
public:
explicit constexpr FixPoint(F&& f)
what this means is that we expect F to be a value type (because inheriting from a reference isn't possible). In addition, we will only accept rvalues -- we will only move from another F.
: F{std::forward<F>(f)}
{}
this std::forward<F> is pointless; this indicates that the person writing this code thinks they are perfect forwarding: they are not. The only legal types F are value types (not references), and if F is a value type F&& is always an rvalue reference, and thus std::forward<F> is always equivalent to std::move.
There are cases where you want to
template<class X>
struct wrap1 {
X&& x;
wrap1(X&& xin):x(std::forward<X>(xin)){}
};
or even
template<class X>
struct wrap2 {
X x;
wrap2(X&& xin):x(std::forward<X>(xin)){}
};
so the above code is similar to some use cases, but it isn't one of those use cases. (The difference here is that X or X&& is the type of a member, not a base class; base classes cannot be references).
The use for wrap2 is when you want to "lifetime extend" rvalues, and simply take references to lvalues. The use for wrap1 is when you want to continue the perfect forwarding of some expression (wrap1 style objects are generally unsafe to keep around for more than a single line of code; wrap2 are safe so long as they don't outlive any lvalue passed to them).
template <typename F>
inline constexpr decltype(auto)
makeFixPoint(F&& f) noexcept
{
return FixPoint<std::decay_t<F>>{std::forward<std::decay_t<F>>(f)};
}
Ok more red flags here. inline constexpr is a sign of nonsense; constexpr functions are always inline. There could be some compilers who treat the extra inline as meaning something, so not a guarantee of a problem.
return FixPoint<std::decay_t<F>>{std::forward<std::decay_t<F>>(f)};
std::forward is a conditional move. It moves if there is an rvalue or value type passed to it. decay is guaranteed to return a value type. So we just threw out the conditional part of the operation, and made it into a raw move.
return FixPoint<std::decay_t<F>>{std::move(f)};
this is a simpler one that has the same meaning.
At this point you'll probably see the danger:
template <typename F>
constexpr decltype(auto)
makeFixPoint(F&& f) noexcept
{
return FixPoint<std::decay_t<F>>{std::move(f)};
}
we are unconditionally moving from the makeFixPoint argument. There is nothing about the name makeFixPoint that says "I move from the argument", and it accept forwarding references; so it will silently consume an lvalue and move-from it.
This is very rude.
So a sensible version of the code is:
template <typename F>
class FixPoint : private F
{
public:
template<class U,
class dU = std::decay_t<U>,
std::enable_if_t<!std::is_same_v<dU, FixPoint> && std::is_same_v<dU, F>, bool> = true
>
explicit constexpr FixPoint(U&& u) noexcept
: F{std::forward<U>(u)}
{}
[SNIP]
namespace
{
template <typename F>
constexpr FixPoint<std::decay_t<F>>
makeFixPoint(F&& f) noexcept
{
return FixPoint<std::decay_t<F>>{std::forward<F>(f)};
}
} // namespace
that cleans things up a bit.
|
71,410,231 | 71,413,981 | Windows 10 custom credential provider | recently I'm trying to make a custom credential provider for windows 10 and I ended up with a sample code provided by Microsoft for Windows 8.1 (https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/credential-provider/). I've tried to make it work on my computer but I can't! It just compiles and makes a `SampleIcredentialProviderV2.dll but it's not working. I click on the registry file within the project folder but it's still not showing up on my login page. Does anyone have experience with this code? how can I make this work?
thanks.
| Most likely windows can't find your dll or your credential provider has not been properly registered.
There are two things to understand to know how a credential provider is created.
First, all registered credential providers on a computer can be found in this registry location :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers
All the subkeys are the GUID (or CLSID) that uniquely identify a COM object, but also a credential provider since they have to implements the IFactory/IUnknown COM interface. Things like {25CBB996-92ED-457e-B28C-4774084BD562}.
Windows will iterate through all those CLSID and if not filtered will try to create an instance of the corresponding credential provider.
In order to do so, it will look into
HKEY_CLASSES_ROOT\CLSID
All the subkeys here represents a COM object. Your credential provider CLSID must be present here too. And here comes the second part, inside it there is another subkey, InProcServer32, containing a default value representing where to find the dll associated with this CLSID.
It can either be just the dll name but then it has to be in your PATH environment variable or in the windows/system32 folder, or it can be a full filepath.
|
71,410,293 | 71,410,448 | C++ BOOST Unit Tests: Invert BOOST_CHECK_EQUAL for not equal | Is there a way to check for inequality when writing Unit Tests with BOOST?
There is a macro BOOST_CHECK_EQUAL, however there does not appear to be a BOOST_CHECK_NOT_EQUAL macro.
I assume it must be possible to check for inequality in a BOOST Unit Test? I could not find anything from a duckduckgo search however.
| The macro you're looking for is BOOST_CHECK_NE:
BOOST_CHECK_NE(a,b);
BOOST_CHECK_EQUAL(a,b);
|
71,410,527 | 71,410,830 | How to avoid text in C++ to be outputted vertically? | I need this to read a file and copy it into another file while modifying numbers, everything works except it copies and displays everything in vertical line. Is there a way how to avoid this? For loop seems to be a problem, but what should be added/changed without changing everything else?
Output should be:
9as 3
12as342sd
5678acv
#include <iostream>
#include <fstream>
#include <ctype.h>
using namespace std;
int main()
{
string line;
//For writing text file
//Creating ofstream & ifstream class object
ifstream ini_file {"f.txt"};
ofstream out_file {"f1.txt"};
if(ini_file && out_file){
while(getline(ini_file,line)){
// read each character in input string
for (char ch : line) {
// if current character is a digit
if (isdigit(ch)){
if(ch!=57){ch++;}
else if (ch=57){ch=48;}}
out_file << ch << "\n";}}
cout << "Copy Finished \n";
} else {
//Something went wrong
printf("Cannot read File");
}
//Closing file
ini_file.close();
out_file.close();
return 0;
}
| Learn to split code to smaller pieces.
Take a look on that:
#include <cctype>
#include <fstream>
#include <iostream>
char increaseDigit(char ch) {
if (std::isdigit(ch)) {
ch = ch == '9' ? '0' : ch + 1;
}
return ch;
}
void increaseDigitsIn(std::string& s)
{
for (auto& ch : s) {
ch = increaseDigit(ch);
}
}
void increaseDigitsInStreams(std::istream& in, std::ostream& out)
{
std::string line;
while(out && std::getline(in, line)) {
increaseDigitsIn(line);
out << line << '\n';
}
}
int main()
{
std::ifstream ini_file { "f.txt" };
std::ofstream out_file { "f1.txt" };
increaseDigitsInStreams(ini_file, out_file);
return 0;
}
|
71,410,580 | 71,414,140 | ran2() numerical recipe implementation. Passing void pointer as function parameter | I'm trying to implement the ran2() method from Numerical Recipes. I found an implementation [here] 1 that I'm trying to get working.
I'm first trying to use the ran2_get_double(void* vstate) function working but I've never used void pointers as a parameter before and I don't know how it works even if I have experience with pointers/references.
This is what I have so far in my main (cpp) file after a bit of trial and error:
double y{ 1.0 };
for (int i{ 0 }; i < 100; i++) {
double* z{ &y };
random_numbers.push_back(ran2_get_double(z));
}
This part of the code works, I get a series of random numbers, but at the end I get the error message:
Stack around the variable 'y' was corrupted.
I've looked around a bit and I suspect this has to do with memory management of the pointer but I'm really not sure where the issue is exactly. Can anyone spot the issue or suggest the best way to use the ran2() implementation here with its void parameter functions? Thanks
| The ran2_get_double() function takes a ran2_state_t in form of a void * as argument but you are passing a pointer to a double. This then causes a buffer overflow that corrupts your memory.
You need to create a ran2_state_t object and initialize it using ran2_set.
The functions should really just take a ran2_state_t * as argument so errors like this don't happen. Or in the c++ world a ran2_state_t&. Even better make it an object that retains it's own state and ran2_set becomes the constructor.
|
71,410,801 | 71,410,942 | How can I declare multiple function pointer types in one typedef declaration? | I can do
typedef int a, b;
but I can't do something like
typedef void(*the_name_1, *the_name_2)(...);
Is there a way do to typedef 2 function pointer types at the same time ?
| Multiple declaration in C/C++ is misleading as * is linked to variable and not to the type:
typedef int a, *b, (*c)();
static_assert(std::is_same_v<int, a>);
static_assert(std::is_same_v<int*, b>);
static_assert(std::is_same_v<int (*)(), c>);
So your one-liner would be
typedef void(*the_name_1)(...), (*the_name_2)(...);
|
71,410,939 | 71,411,576 | C++ initialize array class with default value | I want to create an open hash table.
And i want to use an array of lists, where the size of the array is a template parameter, but the problem is i don't know how to pass an allocator to all of the list instances, and i cannot use vector, because i will need another allocator for list allocation (alloception), is there a way to initialize a whole array of lists with the same value?
I know i can initialize like this list<int> mylist[] = {{allocator}, {allocator}, {allocator}}
But the idea is to have size as a template variable.
Example:
template<typename KEY, typename VAL, typename ALLOC=std::allocator<struct _internal>, size_t TBL_SIZE=100>
class open_hash_table{
private:
std::list<struct _internal, ALLOC=ALLOC> _table[TBL_SIZE];
public:
open_hash_table(ALLOC allocator=ALLOC())
:_table({allocator, allocator ... allocator}){}
};
P.s. my compiler supports upto c++11
| This uses C++14 for std::make_index_sequence and the std::index_sequence it produces but you can make your own implementation as shown here. Using a delegating constructor you can add another constructor that takes an index_sequence so you can then expand the sequence and get a variadic list of values like
template<typename KEY, typename VAL, typename ALLOC=std::allocator<struct _internal>, size_t TBL_SIZE=100>
class open_hash_table{
private:
std::list<struct _internal, ALLOC> _table[TBL_SIZE];
template <std::size_t... Is>
open_hash_table(ALLOC allocator, std::index_sequence<Is...>)
: _table{ std::list<struct _internal, ALLOC>{((void)Is, allocator)}... } {}
public:
open_hash_table(ALLOC allocator=ALLOC())
: open_hash_table(allocator, std::make_index_sequence<TBL_SIZE>{}) {}
};
Your public constructor will call the private helper constructor and pass along an index_sequence that will have TBL_SIZE number of elements in it. Then in the delegating constructor the ((void)Is, allocator) part uses the comma operator to use each element of the index_sequence but we discard that in instead let the expression resolve to allocator. The (void)Is part casts the result of Is to void to suppress that it is unused. We have to use std::list<struct _internal, ALLOC>{ ... } as well because the constructor that takes an allocator is explicit so the type needs to be specified, no implicit conversion allowed.
|
71,411,741 | 71,412,559 | Reading numbers from a text file with letters and whitespace | I am having trouble with the formatting of my C++ assignment. I am working on a File I/O assignment and I have a text file with letters, numbers and whitespace. I want my program to read the numbers from the text file and display in the same format as the text file. Right now, my code is outputting the numbers but as a line instead of number values.
Here is the text file:
dsfj kdf 87 98.5 4vb
jfkd 9 jfkds000 94.3hjf
98.4 jd84. kfd
Here is the desired output:
We found the following magic numbers in test2.txt:
87 98.5 4 9 0 94.3 98.4 84
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char ans;
cout << "Welcome to Number Finder!\n";
cout << "============================\n";
do{
char in_file_name[20];
char c;
ifstream in_stream;
cout << "Which file do you want us to find numbers at?\n";
cin >> in_file_name;
cout << endl;
cout << "We found the follow magic numbers in " << in_file_name << ": \n";
in_stream.open(in_file_name);
if(in_stream.fail()){
cout << in_file_name << " is not found.\n";
}
in_stream.get(c);
while (!in_stream.eof()){
if(isdigit(c)){
cout << fixed;
cout.precision(2);
cout << c << " ";
}
in_stream.get(c);
}
double num;
while(in_stream >> num){
cout << fixed;
cout.precision(2);
cout << num << " ";
}
cout << endl;
cout << "-----";
cout << endl;
cout << "Do you want to process another file? \n";
cin >> ans;
in_stream.close();
} while (ans== 'Y' || ans=='y');
cout << "Thank you for using the Number Finder! Bye for now!";
return 0;
}
| Assuming that your goal is not to retain the accuracy of the double values in the file, one way to do this is to read the line in as a string, and remove any characters that are not digits, except whitespace and the ..
Once you do that, then it's very simple using std::istringstream to output the values:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
int main()
{
std::string line;
// Read the entire line
while (std::getline(std::cin, line))
{
// erase all non-digits, except for whitespace and the '.'
line.erase(std::remove_if(line.begin(), line.end(),
[](char ch) { return !std::isdigit(ch) && !std::isspace(ch) && ch != '.'; }), line.end());
// Now use the resulting line and read in the values
std::istringstream strm(line);
double oneValue;
while (strm >> oneValue)
std::cout << oneValue << " ";
}
}
Output:
87 98.5 4 9 0 94.3 98.4 84
Live Example
|
71,411,946 | 71,412,035 | Would an unordered_set in c++ find the values in this data in constant time? | Suppose I have a list of vertices in a graph. This list corresponds to a path in the graph and before adding another vertex I need to check if it is already present in the path or not.
I was thinking of adding all the vertices in an unordered set and then using the find function. The documentation states that it runs in constant time in an average case. Would it still run in constant time in this case?
If not, is there a way to store a list of vertices and find if a vertex exists in the list or not in constant time?
| The std::unordered_set type has expected O(1) lookups regardless of what data you store in it, so yes, in this case you should expect to see lookups taking time O(1).
One possible caveat: the O(1) here refers to the number of equality comparisons and hashes computed. If comparing two nodes for equality takes a variable amount of time, or if your hash function takes a variable amount of time, then the total cost might exceed O(1).
Another possible caveat: the expected O(1) runtime assumes you have a “good” hash function. If you wrote your own custom hash function and it’s a “weak” hash function, then the runtime might exceed O(1) due to hash collisions.
|
71,412,512 | 71,412,580 | Add element from map to pair only if the value doesn't already exist (C++) | I am trying to add the elements from a map to a pair vector, and then sort the vector according to the value, but i dont want to add elements that have the same value, and i can't figure out how to make such an if statement.
The map contains the amount of times a word was repeated in the input in main() and the word itself, and i want to sort the vector that has the map elements, but i dont want to repeat words that have been repeated the same amount of times.
This is what i have so far:
bool compara(pair<string, unsigned int>& a,
pair<string, unsigned int>& b)
{
return a.second > b.second;
}
void sortP(map<string, unsigned int> &M, unsigned int x)
{
vector<pair<string, unsigned int> > A;
for (auto& it : M) {
if(find(A.begin(), A.end(), it.second) == A.end()) // this is the part that
A.push_back(it); // doesn't work
}
sort(A.begin(), A.end(), compara);
for (auto& it : A) {
cout << it.second << "\t"
<< it.first << endl;
}
cout << endl << endl;
// this is where i want to output the element of the vector that appears on the 'x'
// position, after it was sorted
}
I apologize if the terminology isn't exactly correct, i have just started getting accustomed to working with maps and pairs.
| Since you are searching through a vector of pairs, you need to use std::find_if() instead of std::find() to find a vector element that matches a particular field of the pair, eg:
for (auto& it : M) {
if (find_if(A.begin(), A.end(), [&](pair<string, unsigned int>& p){ return p.second == it.second; }) == A.end())
A.push_back(it);
}
Alternatively, you could just use another map instead of a vector, using it.second as the key type, and letting the map handle the sorting and duplicate handling for you.
|
71,412,812 | 71,413,704 | Can we create std::istringstream object from a reversed std::string | I am learning C++ using recommended C++ books. In particular, i read about std::istringstream and saw the following example:
std::string s("some string");
std::istringstream ss(s);
std::string word;
while(ss >> word)
{
std::cout<<word <<" ";
}
Actual Output
some string
Desired Output
string some
My question is that how can we create the above std::istringstream object ss using the reversed string(that contains the word in the reverse order as shown in the desired output)? I looked at std::istringstream's constructors but couldn't find one that takes iterators so that i can pass str.back() and str.begin() instead of passing a std::string.
| You can pass iterators to the istringstream constructor indirectly if you use a temporary string:
#include <sstream>
#include <iostream>
int main()
{
std::string s{"Hello World\n"};
std::istringstream ss({s.rbegin(),s.rend()});
std::string word;
while(ss >> word)
{
std::cout<<word <<" ";
}
}
Output:
dlroW olleH
Though thats reversing the string, not words. If you want to print words in reverse order a istringstream alone does not help much. You can use some container to store the extracted words and then print them in reverse:
#include <sstream>
#include <iostream>
#include <vector>
int main()
{
std::string s{"Hello World\n"};
std::istringstream ss(s);
std::string word;
std::vector<std::string> words;
while(ss >> word)
{
words.push_back(word);
}
for (auto it = words.rbegin(); it != words.rend(); ++it) std::cout << *it << " ";
}
Output:
World Hello
|
71,413,350 | 71,414,670 | C++ set limit on maximum memory allocation? | I am writing a program in x86 architecture (for technical reasons I cannot use x64). I have designed my program such that it uses under 4GB of RAM memory. However, when I allocate memory for large std::vectors I notice that the constructors allocate more memory than necessary and later trim the memory down to the proper amount (tested on smaller memory requirements to be able to observe that). This is a problem, since the brief moment when more RAM is allocated than necessary is crashing the program due to >4GB RAM usage.
Is there a way to prevent the program from dynamically allocating more than a given amount of RAM? If so, how can one set this property in a Visual Studio solution?
| Turns out, the standard vector constructor is briefly allocating additional memory to perform a copy operation, as mentioned by Peter Cordes in a comment. That's why doing:
vector<vector<struct>> myVector(M, vector<struct>(N))
may lead to memory allocation problems.
The workarounds that worked for me are:
If required vector size is known before compilation, the following does not produce a memory spike:
vector<array<struct,N>> myVector(M)
If the vector size needs to stay dynamical, the suggestion of Mansoor in the comments also does not produce a memory spike:
vector<vector<struct>> myVector(M)
for(int i=0;i<M;i++){
myVector[i].reserve(N);
myVector[i].resize(N);
}
|
71,413,742 | 71,413,992 | Getting Releasing unheld lock CriticalSection in Windows C++ code | I'm getting a warning "Releasing unheld lock 'csCriticalSection'" at the 2nd try below.
Here is my code, but without all the ADO code. I don't know why I'm getting this warning, because if the Execute() function fails, the catch will run a LeaveCriticalSection function. If the Execute() function succeeds, I call LeaveCriticalSection.
#include <windows.h>
#include <synchapi.h>
#include <comdef.h>
#include <conio.h>
CRITICAL_SECTION csCriticalSection;
_ConnectionPtr connectioncreate = nullptr;
_RecordsetPtr recordset = nullptr;
int main()
{
InitializeCriticalSectionAndSpinCount(&csCriticalSection, 4000);
// *** all ADO code here ***
//
// *** all ADO code here ***
BOOL bRanLeaveCriticalSection = FALSE;
try
{
EnterCriticalSection(&csCriticalSection);
// Run an SQL command with ADO.
/*
connectioncreate->BeginTrans();
connectioncreate->Execute(sSQL.data(), nullptr, adCmdText);
connectioncreate->CommitTrans();
*/
LeaveCriticalSection(&csCriticalSection);
bRanLeaveCriticalSection = TRUE;
}
catch (CONST _com_error& err)
{
connectioncreate->CommitTrans();
if (bRanLeaveCriticalSection == FALSE)
LeaveCriticalSection(&csCriticalSection);
}
try
{
// From compiler at the next line "if (recordset)":
// Warning C26117 Releasing unheld lock 'csCriticalSection'
if (recordset)
if (recordset->State == adStateOpen)
recordset->Close();
}
catch (CONST _com_error& err)
{
err;
}
_getch();
}
Can anyone help me to for the reason why I'm getting this warning and how to fix it?
| You are not initializing csCriticalSection before using it, eg:
...
CRITICAL_SECTION csCriticalSection;
...
int main()
{
InitializeCriticalSection(&csCriticalSection); // <-- ADD THIS
...
DeleteCriticalSection(&csCriticalSection); // <-- ADD THIS
}
But also, you really shouldn't be using bRanLeaveCriticalSection at all, this is just bad code design.
You can use a __try/__finally block instead (if your compiler supports that), eg:
...
CRITICAL_SECTION csCriticalSection;
...
int main()
{
...
try
{
EnterCriticalSection(&csCriticalSection);
__try
{
// Run an SQL command with ADO.
}
__finally
{
LeaveCriticalSection(&csCriticalSection);
}
}
catch (CONST _com_error& err)
{
...
}
...
}
However, the best option is to use an RAII wrapper instead, let it call EnterCriticalSection() and LeaveCriticalSection() for you, eg:
struct CRITICAL_SECTION_LOCK
{
CRITICAL_SECTION &m_cs;
CRITICAL_SECTION_LOCK(CRITICAL_SECTION &cs) : m_cs(cs) {
EnterCriticalSection(&m_cs);
}
~CRITICAL_SECTION_LOCK() {
LeaveCriticalSection(&m_cs);
}
};
...
CRITICAL_SECTION csCriticalSection;
int main()
{
...
try
{
CRITICAL_SECTION_LOCK lock(csCriticalSection);
// Run an SQL command with ADO.
}
catch (CONST _com_error& err)
{
...
}
...
}
Or better, use a C++ std::mutex instead, with a proper RAII lock such as std::lock_guard, eg:
#include <mutex>
std::mutex mtx;
...
int main()
{
try
{
std::lock_guard<std::mutex> lock(mtx);
// Run an SQL command with ADO.
}
catch (CONST _com_error& err)
{
...
}
...
}
|
71,414,121 | 71,419,820 | How to write a multi-dimensional array of structs to disk using MPI I/O? | I am trying to write an array of complex numbers to disk using MPI I/O. In particular, I am trying to achieve this using the function MPI_File_set_view so that I can generalise my code for higher dimensions. Please see my attempt below.
struct complex
{
float real=0;
float imag=0;
};
int main(int argc, char* argv[])
{
/* Initialise MPI parallel branch */
int id, nprocs;
MPI_Init(&argc, &argv);
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm, &id);
MPI_Comm_size(comm, &nprocs);
/* Create a datatype to represent structs of complex numbers */
MPI_Datatype MPI_Complex;
const int lengths[2] = { 1, 1 };
MPI_Datatype types[2] = { MPI_FLOAT, MPI_FLOAT };
MPI_Aint displacements[2], base_address;
complex dummy_complex;
MPI_Get_address(&dummy_complex, &base_address);
MPI_Get_address(&dummy_complex.real, &displacements[0]);
MPI_Get_address(&dummy_complex.imag, &displacements[1]);
displacements[0] = MPI_Aint_diff(displacements[0], base_address);
displacements[1] = MPI_Aint_diff(displacements[1], base_address);
MPI_Type_create_struct(2, lengths, displacements, types, &MPI_Complex);
MPI_Type_commit(&MPI_Complex);
/* Create a datatype to represent local arrays as subarrays of a global array */
MPI_Datatype MPI_Complex_array;
const int global_size[1] = { 100 };
const int local_size[1] = { (id < nprocs-1 ? 100/nprocs : 100/nprocs + 100%nprocs) };
const int glo_coord_start[1] = { id * (100/nprocs) };
MPI_Type_create_subarray(1, global_size, local_size, glo_coord_start, MPI_ORDER_C,
MPI_Complex, &MPI_Complex_array);
MPI_Type_commit(&MPI_Complex_array);
/* Define and populate an array of complex numbers */
complex *z = (complex*) malloc( sizeof(complex) * local_size[0] );
/* ...other stuff here... */
/* Write local data out to disk concurrently */
MPI_Offset offset = 0;
MPI_File file;
MPI_File_open(comm, "complex_nums.dat", MPI_MODE_CREATE|MPI_MODE_WRONLY, MPI_INFO_NULL, &file);
MPI_File_set_view(file, offset, MPI_Complex, MPI_Complex_array, "external", MPI_INFO_NULL);
MPI_File_write_all(file, z, local_size[0], MPI_Complex, MPI_STATUS_IGNORE);
MPI_File_close(&file);
/* ...more stuff here... */
}
However, with the above code, only the local data from the process labelled id = 0 is being saved to disk. What am I doing wrong and how can I fix this? Thank you.
N.B. Please note that for this one dimensional example, I can avoid the problem by giving up on MPI_File_set_view and using something simpler like MPI_File_write_at_all. Nevertheless, I have not solved the underlying problem because I still don't understand why the above code does not work, and I would like a solution that can be generalised for multi-dimensional arrays. Your help is much appreciated in this regard. Thank you.
| The default behavior is not to abort when a MPI-IO subroutine fails.
So unless you change this default behavior, you should always test the error code returned by MPI-IO subroutines.
In your case, MPI_File_set_view() fails because external is not a valid data representation.
I guess this is a typo and you meant external32.
|
71,414,888 | 71,415,981 | C++: How to pass data from parent to child in a lambda inside a recursive function | I want to iterate over a data structure and collect the paths of the elements. I'd like to do it in a way where the iteration over the structure is as generic as possible (see void WithAllMembersRecursively(..)) and the operation on the structure is inserted as an parameter.
The code below will return:
C
C::B
C::B::A
But the goal is:
C
C::B
C::A
Is there a way to design the lambda and its args to achieve the desired result?
Notes:
Yes, I'm aware that the reason for the continous stacking is caused by string& fullPath in the lambda. Beacause it FullPath is passed by reference.
Using string fullPath on the other hand will result in another wrong result because FullPath ("") is passed by value and thus every lambda call will only see the empty string:
C
B
A
The class and the data tree can not be modified to insert additional information.
The current sub-optimal solution that I settled on for my project so far has the assignment and passing of the path from parent to child in the recursive method. But that is something that I'd like to get rid off to allow others to use the recursive method in conjunction with their logic:
template<typename F, typename... Args>
void WithAllMembersRecursively(MyElement* pElement, string parentPath, const F& f, Args&&... args)
{
string newPath = parentPath.empty() ? pElement->mName : parentPath + "::" + pElement->mName;
f(pDOInterface, newPath, std::forward<Args>(args)...);
for (auto pMember: pElement->mMembers)
{
WithAllMembersRecursively(pMember, newPath, f, std::forward<Args>(args)...);
}
}
Code Example:
#include <iostream>
#include <vector>
using namespace std;
class MyElement
{
public:
MyElement(string name) : mName(name) {}
void AddElement(MyElement* elem) { mMembers.emplace_back(elem); }
string mName;
vector<MyElement*> mMembers;
};
template<typename F, typename... Args>
void WithAllMembersRecursively(MyElement * pElem, const F & f, Args&&... args)
{
f(pElem, args...);
for (auto pMember : pElem->mMembers)
{
WithAllMembersRecursively(pMember, f, std::forward<Args>(args)...);
}
}
int main()
{
MyElement C("C");
MyElement B("B");
MyElement A("A");
C.AddElement(&B);
C.AddElement(&A);
vector<string> AllPaths;
string FullPath = "";
WithAllMembersRecursively(&C, [&AllPaths](MyElement* elem, string& fullPath) {
fullPath = fullPath.empty() ? elem->mName : fullPath + "::" + elem->mName;
AllPaths.emplace_back(fullPath);
}, FullPath);
for (auto e : AllPaths)
{
cout << e << endl;
}
return 0;
}
| You need some way of popping an item from the path when the recursive traversal finishes with an item completely.
The current call to f is essentially a "pre-visit" call, then the visit happens which is the main recursive function iterating over all children and recursively visiting. If you also add a post-visit call you will have enough flexibility to pop from the running state without changing any other code.
One way to do this is to pass in another functor object to do the pop. The following will give you the output you want.
#include <iostream>
#include <vector>
using namespace std;
class MyElement
{
public:
MyElement(string name) : mName(name) {}
void AddElement(MyElement* elem) { mMembers.emplace_back(elem); }
string mName;
vector<MyElement*> mMembers;
};
template<typename C, typename F, typename... Args>
void WithAllMembersRecursively(MyElement* pElem, const C& post_visit, const F& pre_visit, Args&&... args)
{
pre_visit(pElem, args...);
for (auto pMember : pElem->mMembers) {
WithAllMembersRecursively(pMember, clear, f, std::forward<Args>(args)...);
}
post_visit();
}
int main()
{
MyElement mC("mC");
MyElement mCmB("mB");
MyElement mCmBmA("mA");
MyElement mCmBmRevA("mrevA");
MyElement mCmRevB("mRevB");
MyElement mCmRevBmA("mA");
MyElement mCmRevBmRevA("mrevA");
mCmRevB.AddElement(&mCmRevBmA);
mCmRevB.AddElement(&mCmRevBmRevA);
mCmB.AddElement(&mCmBmA);
mCmB.AddElement(&mCmBmRevA);
mC.AddElement(&mCmB);
mC.AddElement(&mCmRevB);
vector<string> AllPaths;
string FullPath = "";
WithAllMembersRecursively(&mC,
[&FullPath]() {
auto iter = FullPath.find_last_of("::");
if (iter == FullPath.size()) {
return;
}
FullPath = FullPath.substr(0, iter-1);
},
[&AllPaths](MyElement* elem, string& fullPath) {
fullPath = fullPath.empty() ? elem->mName : fullPath + "::" + elem->mName;
AllPaths.emplace_back(fullPath);
},
FullPath
);
for (auto e : AllPaths)
{
cout << e << endl;
}
return 0;
}
|
71,415,131 | 71,415,952 | Method already defined when using new version of Visual Studio | The following files are part of my C++ project.
// DpValue.h
class DpValue {
public:
class RElement {
public:
virtual bool operator==(RElement const &Other) const = 0;
};
};
template<class T>
class DpElement : public DpValue::RElement {
public:
virtual bool operator==(DpValue::RElement const &Other) const { ... }
};
// DpValue.cpp
#include <DpValue.h>
template<>
bool DpElement<DpValue>::operator==(DpValue::RElement const &Other) const { ... }
// DpType.cpp
#include <DpValue.h>
...
It compiles fine in Visual Studio 2015. I'm in the process of updating to Visual Studio 2022, and there I get the following linker error:
Code: LNK2005
Description: "public: virtual bool __cdecl DpElement<class DpValue>::operator==(class DpValue::RElement const &)const " (??8?$DpElement@VDpValue@@@@UEBA_NAEBVRElement@DpValue@@@Z) already defined in DpKernel64Dbg.lib(DpValue.obj)
Project: DpDiagram
File: DpKernel64Dbg.lib(DpType.obj)
From my understanding, the method is defined in DpValue.obj, which is correct. But then it is defined again in DpType.obj! What might cause this?
There are of course lots of other code and files in my project, but I've included everything that I think is relevant for the error here.
| I think the only thing you are missing is a declaration of the explicit specialization in the header file. It must appear before any point that would implicitly instantiate the class specialization (since the function is virtual). In the presence of the explicit specialization declaration the implicit instantiation should be suppressed.
So add in DpValue.h after the definition of DpElement:
template<>
bool DpElement<DpValue>::operator==(DpValue::RElement const &Other) const;
It must follow the class template definition immediately to avoid accidental implicit instantiations of the class, which could also implicitly instantiate the virtual member function's definition.
See also Explicit specialization of member function template in source file.
|
71,415,873 | 71,417,374 | How to start Qt Designer "detached" in Visual Studio? | In previous version of Qt Tools for Visual Studio, when opening an .ui file, Visual Designer started normally, in it's own main window. Now it starts as a docked window inside the Visual Studio IDE, and I have to press the "Detach" link every time. Is there any setting to start Qt Designer "detached" by default?
| Just set Run in detached window to True in extension options:
|
71,416,027 | 71,417,042 | Avoiding wasted CPU cycles while waiting for input | My program is waiting for the F4 hotkey to be pressed in order to exit.
I am calling Sleep(1) because without this, I am using 18% of my CPU. Is this the correct way to do this? My gut is telling me there is a better way.
I know that keyboard inputs are interrupt-based, but is there any way to make a thread sleep until a keyboard state change is registered?
#include <Windows.h>
#include <iostream>
#include <thread>
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
while (!(GetAsyncKeyState(VK_F4) >> 15)) {
Sleep(1); // Sleep for 1 ms to avoid wasting CPU
}
return 0;
}
| Look into RegisterHotKey, UnRegisterHotkey, GetMessage, TranslateMessage and DispatchMessage like
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
RegisterHotKey(0, 1, MOD_NOREPEAT, VK_F4);
MSG msg;
while (GetMessage(&msg, 0, 0, 0) != 0) // TODO: error handling
{
if (msg.message == WM_HOTKEY)
{
if (msg.wParam == 1) {
break;
}
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnregisterHotKey(0, 1);
return 0;
}
GetMessage() will block until it receives a window message, which wakes it up. Get a copy of Process Explorer, look into the process details and see it not using a single CPU cycle while it's waiting.
|
71,416,623 | 71,416,964 | Variadic construction with per-argument type deduction | I have a class Processor that I'd like to be able to, using C++14 or below (C++17, 20, etc ideas very welcome too for information and posterity, but the problem is specifically C++14):
Take a variadic list for construction, each element of which can be:
"values" of basically any type, or
Handlers: some kind of polymorphic type that has a do_handle member function.
Internally convert that heterogeneously-typed list into some kind of container of only Handlers, using the relevant "value" constructor for "values", and just copying things that come in as Handlers
Which can later be iterated over with some other context (in the below case it's an int, but that could be anything, e.g. other Processor state).
// Handler base class
class Handler {
public:
// "handle" something, somehow
virtual int handle_thing(int foo) const = 0;
}
// Imagine there are "some" Handler derived classes of various kinds
// and say we construct by some factories which look something roughly like the following.
// Factories aren't critical, what's important is you can
// dispatch a given type to a suitable `Handler` implementation
// Factory: copy-constructs a copy of the given handler
// (may use a std::enable_if, whatever)
template<typename SomeHandler>
std::unique_ptr<Handler> make_handler(SomeHandler handler) {
return std::make_unique<SomeHandler>(handler);
}
// Factory: create a handler for some other type
template<typename ValueType>
std::unique_ptr<Handler> make_handler(ValueType value) {
retun std::make_unique<ValueHandler<ValueType>>(value);
}
template<typename ...Types>
class Processor {
public:
// Some number of
Processor(Types&&... args) {
// Something like this pseudo-code:
// for (arg in args) {
// // Construct some suitable handler somehow
// m_handlers.push_back(make_handler(arg));
// }
}
// use the handlers somehow (accumulation here is just an example)
int do_process(int foo) {
int acc = 0;
for (const auto& handler: m_handlers) {
acc += handler->handle_thing(foo);
}
return acc;
}
private:
// Some kind of container of per-argument handlers
// Polymorphism probably indicates container-of-unique_ptr
// but not specifically needed to be so
std::vector<std::unique_ptr<Handler>> m_handlers;
}
My basic problem is that I don't know how to go from the heterogenous construction arguments of types Types&&... to an element-by-element construction of a Handler based on the type of each element.
I have tried to construct a std::tuple<Types...>, but that doesn't really seem to help me very much, since it's not obvious how to sensible iterate that and get the resulting Handler container.
I have also thought about constructing the m_handlers container like this:
std::vector<Handler*, sizeof...(params)> list {args...};
But since the individual handlers are actually different types, it's not obvious to me that that can be done.
| In C++11 and C++14 you can use brace-enclosed initializers to expand and handle variadic arguments. So in your case you could do
Processor(Types&&... args) {
int dummy[] = { (m_handlers.push_back(make_handler(args)), 0)... };
}
Since C++17 you can also use a fold expression with the comma operator to achieve the same effect:
Processor(Types&&... args) {
(m_handlers.push_back(make_handler(args)), ...);
}
|
71,416,824 | 71,423,733 | Use the value of strongly typed enum as index in boost::mpl::map | I am using a C++ map structure defined similar to std::map<Foo, std::any> for storing attributes of a compiler symbol table. The Foo is a strongly typed enum, such as enum class Foo {ENUM}. After casting some other types to std::any, I need std::any_cast to cast it back if I access the entry by the Foo::ENUM key. The type parameter of std::any_cast is tied to Foo::ENUM.
That being said, I want something for automatically determining the type parameter for std::any_cast based on Foo::ENUM as following:
std::map<Foo, std::any> m;
const auto x = std::any_cast<some_magic(Foo::ENUM)::type>(m[Foo::ENUM]);
Here is my current implementation:
#include <iostream>
#include <string>
#include <vector>
#include <type_traits>
#include <any>
#include <map>
#define CAT(x, y) CAT_(x, y)
#define CAT_(x, y) x ## y
#define ENABLE_ENUM_TO_TYPE(enum_class_name) \
template <enum_class_name> struct CAT(enum_class_name, _enum_to_type);
#define ENUM_TYPE_PAIR(enum_class_name, enum_key, type_) \
template <> struct CAT(enum_class_name, _enum_to_type)<enum_class_name::enum_key> {using type = type_;};
enum class Foo {
A1, A2
};
enum class Bar {
B1, B2, B3
};
ENABLE_ENUM_TO_TYPE(Foo);
ENABLE_ENUM_TO_TYPE(Bar);
ENUM_TYPE_PAIR(Foo, A1, int);
ENUM_TYPE_PAIR(Foo, A2, double);
ENUM_TYPE_PAIR(Bar, B1, std::string);
ENUM_TYPE_PAIR(Bar, B2, std::vector<int>);
template <auto T1>
constexpr auto enum_to_type_impl() {
#define COMPARE_ENUM_CLASS(enum_class_name) \
if constexpr (std::is_same_v<decltype(T1), enum_class_name>) { return CAT(enum_class_name, _enum_to_type)<T1>{};} else
COMPARE_ENUM_CLASS(Foo)
COMPARE_ENUM_CLASS(Bar)
#undef COMPARE_ENUM_CLASS
{}
}
template <auto EnumVal>
struct enum_to_type {
using type = typename decltype(enum_to_type_impl<EnumVal>())::type;
};
int main() {
std::map<Bar, std::any> m;
m[Bar::B1] = std::string{"Hello"};
std::cout << std::any_cast<enum_to_type<Bar::B1>::type>(m[Bar::B1]) << std::endl;
return 0;
}
However, my code above is still cumbersome. I look into the boost mpl library but apparently it does not offer something like mpl::enum_, and I have tried the following code but it does not work:
#include <boost/mpl/map.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/at.hpp>
#include <string>
#include <iostream>
enum class Bar {
C1, C2
};
template <auto EnumVal> struct enum_
{
using type = enum_;
using value_type = decltype(EnumVal);
typedef mpl_::integral_c_tag tag;
};
typedef boost::mpl::map<
boost::mpl::pair<enum_<Bar::C1>, std::string>,
boost::mpl::pair<enum_<Bar::C2>, int>
> m;
int main() {
boost::mpl::at<m, enum_<Bar::C1>>::type x;
return 0;
}
When compiling the code above, I get the following error message:
main.cpp: In function ‘int main()’:
main.cpp:24:38: error: incomplete type ‘boost::mpl::at<boost::mpl::map<boost::mpl::pair<enum_<Bar::C1>, std::__cxx11::basic_string<char> >, boost::mpl::pair<enum_<Bar::C2>, int> >, enum_<Bar::C1> >’ used in nested name specifier
24 | boost::mpl::at<m, enum_<Bar::C1>>::type x;
Any ideas? Is the data type for boost::mpl::map extensible?
EDIT:
I have added #include <boost/mpl/at.hpp> in the above code snipet following the accepted answer, and it works properly.
As for the boost::mp11 solution, my code is on https://godbolt.org/z/KvjecnTe3, but gcc fails to compile it, and I have submitted an issue on https://github.com/boostorg/mp11/issues/72.
| You need to include #include <boost/mpl/at.hpp>. Also, I wouldn't recommend using boost::mpl - it's really slow to compile. Your "cumbersome" solution is fastest IMHO, and if you don't like it you might like to look towards boost::mp11 or any other "more modern" metaprogramming library.
|
71,417,003 | 71,418,013 | Best way to define number is unsigned char in c++ | I had some code that when simplified is essentially this
unsigned char a=255;
unsigned char b=0;
while (a+1==b) {//do something}
Now since 255+1=0 with unsigned chars I was expecting it to do something but it didn't because it promoted everything to int. I can make it work by replacing a+1 with either (unsigned char)(a+1) or (a+1)%256.
What would be the best way to tell the compiler that I don't want the types to be changed? Or should I just be doing 1 of the ways I know works?
| According to This cppreference.com page, "arithmetic operators don't accept types smaller than int as arguments." That said, your proposed solution of (unsigned char)(a + 1) is enough to keep this promotion from happening and a will roll over to 0. Using the modulo operator is more explicit but it introduces an additional operation in the machine code. It's a balance between clarity and performance.
|
71,417,403 | 71,417,431 | Why does declaring an instance pointer with new keyword inside a function causes problems and undefined behaviour? | I am learning C++ and came across something interesting while solving challenges on the platform HackerRank. The code is from the Linked List problem. The goal is to display the linked list with the display method in the Solution class. I noticed that I have to use the new keyword while initializing a class instance for this to work otherwise the code does not detect the end of the list. Please see the following two codes and their respective outputs.
Why is the end of the linked list is not detected correctly when the new keyword is not used as in the second code example? I read on the internet that it is discouraged to use new as the pointers will need to be explicitly deleted afterwards to avoid a memory leak, so I am pretty confused.
Both codes use the same following input:
Input
4
2
3
4
1
Code 1
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head,int data)
{
//Complete this method
Node* new_node = new Node(data); //Check this line
if (head) {
Node *current = head;
while(current->next) {
current = current->next;
}
current->next = new_node;
}
else
{
head = new_node;
}
// Node** pp = &head;
// while (*pp) {
// pp = &((*pp)->next);
// }
// *pp = new Node(data);
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
Output 1 (correct)
2 3 4 1
Code 2
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head,int data)
{
//Complete this method
Node new_node(data);
if (head) {
Node *current = head;
while(current->next) {
current = current->next;
}
current->next = &new_node;
}
else
{
head = &new_node;
}
// Node** pp = &head;
// while (*pp) {
// pp = &((*pp)->next);
// }
// *pp = new Node(data);
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
Output 2 (incorrect)
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1....
| While it's true that using new requires explicit deallocation, this also means that if you are not using new, then somehow the lifetime of the object is already managed implicitly.
This is what happens in your second scenario:
Node new_node(data);
head = &new_node;
Here you are actually taking the address of a local variable and assign it to a global variable. But the local variable itself ceases to exist whenthe function returns and the address you stored is no longer valid.
When you use new, instead, the memory for the object is allocated in a standalone heap and persists as long as you don't delete it.
PS. In c++ you can (and should) use nullptr instead that NULL
|
71,417,771 | 71,417,875 | Overwrite read-only contents of uint16_t array with ntohs() | I have a data array which is populated from the network device in big endian format. The processor on the host is an intel processor, therefore by default little endian.
I am trying to overwrite the contents of the data array received from the network device (little endian) to that of the host (big endian), however receive an lvalue error saying the structure is read only.
For simplicity sake, assume that there is just one iteration.
My code is as follows:
class FFT_Data{
private:
uint16_t data[16384];
public:
const uint16_t* Data (void) const {
return (const uint16_t*)data;
}
const void* DataBE2LE(void) const { // conversion function
// (const uint16_t*)ntohs(*data); // originally i thought this was right
data = (const uint16_t*)ntohs(*data);
}
}
and then this simplified main:
int main()
{
FFT_Data fft;
// data is received from network device
fft.DataBE2LE(); // want to convert data array from BE to LE just once
SomeFunctionThatDoesStuffWithData(fft.Data()); // function that then processes BE data.
return 0;
}
So in the above, I originally had the idea that a single line function that just did (const uint16_t*)ntohs(*data) would be enough to modify the data array as I am operating on a pointer, however I don't think that's right as ntohs returns a uint16_t.
Then trying to overwrite the contents of data with data = (const uint16_t*)ntohs(*data); fails as data is a private variable and thus read only:
Compile error: FFT_Data::data' in read-only structure
| DataBE2LE() is marked as const on the end of its declaration, so its this pointer is a pointer to a const FFT_Data object, and thus its data members are implicitly const and can't be modified.
Since DataBE2LE() wants to modify the content of data, simply remove the const qualifier from the end of DataBE2LE().
Also, the return type of DataBE2LE() should be void, not (const) void* since you are not returning anything.
class FFT_Data{
private:
uint16_t data[16384];
public:
const uint16_t* Data() const {
return data;
}
void DataBE2LE() {
*data = ntohs(*data);
}
};
|
71,417,921 | 71,417,961 | would shared_ptr be aware of intermittence reference? | by intermittence reference I mean the following
shared_ptr<int> a = new int(100);
int* i = a;
shared_ptr<int> b = i;
would the reference count of b be two?
also if it is aware, would still be valid in the following code?
//
shared_ptr<int> a = new int(100);
{// workspace
int* i = a;
shared_ptr<int> b = i;
}// end of workspace
If no to above question, how could I achieve it?
I would to make my memory allocation safe by using smart pointer. I have a data structure tree that would create new tree nodes (pointers to allocated memory) that is either inserted into tree or passed out.
If it is within the tree, no problem, I can control the life cycle. If it is passed out, then I have no control.
| The version you wrote in your example will not compile. But to answer the spirit of what I think your question is here is an example
#include <memory>
int main() {
std::shared_ptr<int> a = std::make_shared<int>(100);
int* i = a.get();
std::shared_ptr<int> b(i);
}
This does not have a and b related as far as reference counting. Instead they both (mistakenly) take ownership of the same underlying pointer, pointed at by i and will result in a double free or corruption when a falls out of scope since they both try to delete it.
The correct way for both shared_ptr to reference the same underlying pointer and have correct reference counting behavior is simply
#include <memory>
int main() {
std::shared_ptr<int> a = std::make_shared<int>(100);
std::shared_ptr<int> b = a;
}
|
71,418,053 | 71,418,160 | Using arrays instead of vectors in C | Program should find smallest enclosing circle of two points.
EXAMPLE:
(1,1) (2,2)
The smallest circle for these two points would be the circle with center(1.5, 1,5) and radius 0.71. This is just a representation of that on a graph:
Two points inside a circle
Here's the problem solution:
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
const double INF = 1e18;
struct Point {
double X, Y;
};
struct Circle {
Point C;
double R;
};
double dist(const Point& a, const Point& b)
{ return sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2)); }
int is_inside(const Circle& c, const Point& p)
{ return dist(c.C, p) <= c.R; }
Circle circle_from(const Point& A, const Point& B)
{
Point C = { (A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 };
return { C, dist(A, B) / 2.0 };
}
int is_valid_circle(const Circle& c, const vector<Point>& P)
{
for (const Point& p : P)
if (!is_inside(c, p)) return 0;
return 1;
}
Circle minimum_enclosing_circle(const vector<Point>& P)
{
int n = (int)P.size();
if (n == 0)
return { { 0, 0 }, 0 };
if (n == 1)
return { P[0], 0 };
Circle mec = { { 0, 0 }, INF };
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Circle tmp = circle_from(P[i], P[j]);
if (tmp.R < mec.R && is_valid_circle(tmp, P))
mec = tmp;
}
}
return mec;
}
int main() {
Circle mec = minimum_enclosing_circle({
{1, 1},
{2, 2},
});
printf("(%.2f,%.2f) %.2f", mec.C.X, mec.C.Y, mec.R);
return 0;
}
int main() {
Circle mec = minimum_enclosing_circle({
{1, 1},
{2, 2},
});
printf("(%.2f,%.2f) %.2f", mec.C.X, mec.C.Y, mec.R);
return 0;
}
Problem with this code is using vectors for calculations. How could this be written without using vectors and with using C arrays?
| normal array in c don't have some method like size() , in your code you need to pass size parameter with pointer instead of vector::size() and -> it can work well
int is_valid_circle(const Circle c, const Point* P, size_t size)
{
for(int i = 0; i < size ; i++)
{
if (!is_inside(c, P[i])) return 0;
}
return 1;
}
Circle minimum_enclosing_circle(const Point* P, size_t size)
{
int n = size;
if (n == 0)
return { { 0, 0 }, 0 };
if (n == 1)
return { P[0], 0 };
Circle mec = { { 0, 0 }, INF };
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Circle tmp = circle_from(P[i], P[j]);
if (tmp.R < mec.R && is_valid_circle(tmp, P, size))
mec = tmp;
}
}
return mec;
}
tested at : https://godbolt.org/z/xWTqfqxsn
|
71,418,154 | 71,427,303 | CLion can find the MinGW64, but it takes no effect. I still can't run C/C++ programs | After I download the CLion, I configure MinGW-64 also.
I've tried almost everything online, and they're surprisingly consistent, but they still don't solve my problem.
I know it's just a simple configuration issue, but I spent the whole day and still couldn't solve it.
Can someone help me? I'd appreciate it.
| In order to compile the c/c++ file, none of Cygwin and MinGW can be ignore!
Thanks for the brother's (@long.kl) suggest!
just do as follows pictures, your c/c++ compile can work too.
Note that the order
|
71,419,083 | 71,422,041 | Generate random 128 bit in c++ without boost | I have a datatype of size 128 bit, and I like to generate a random value without using boost or any third party headers/libraries.
I wrote the below code snippet and it's working fine, but I want to know if there are any issues/pitfalls with the approach.
#include <stdlib.h>
#include <time.h>
#include <array>
#include <iostream>
#include <random>
int main() {
constexpr int size = 16;
std::array<std::uint8_t, size> randomID;
std::mt19937_64 gen_{std::random_device{}()};
std::uniform_int_distribution<std::uint8_t> dis_{1};
for (int i = 0; i < randomID.size(); i++) {
randomID[i] = dis_(gen_);
std::cout << unsigned(randomID[i]) << " ";
}
return 0;
}
| One issue with the posted approach is that it will never generate a 0 octet.
std::uniform_int_distribution<std::uint8_t> dis_{1};
// ^ the range will be [1, 255]
You could also use a distribution of uint64_t and spread the bits in the array
std::uniform_int_distribution<std::uint64_t> dis_{};
for ( size_t i{}; i < randomID.size(); i += 8 )
{
auto r{ dis_(gen_) };
for ( unsigned j{}; j < 8; ++j )
{
randomID[i + j] = (r >> (j * 8)) & 0xFF;
std::cout << unsigned(randomID[i + j]) << " ";
}
}
Consider also using a std::seed_seq to initialize std::mt19937.
std::random_device rd{};
std::seed_seq ss{ rd(), rd(), rd() };
// ^^^^^^^^^^^^^^^^ Increase the entropy.
std::mt19937_64 gen_{ ss };
|
71,419,220 | 71,419,584 | Question about returning an unique_ptr from a function | As per the document, which says that
We already have implicit moves for local values and function
parameters in a return statement. The following code compiles just
fine:
std::unique_ptr<T> f(std::unique_ptr<T> ptr) {
return ptr;
}
However, the following code does not compile
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return ptr;
}
Instead, you must type
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return std::move(ptr);
}
Here are my questions:
1.There is no copy ctor for std::unique_ptr<T> indeed, there should not a function could accept a parameter declared as std::unique_ptr<T>. See this code snippet, it does not compile.
#include <memory>
class FooImage{};
std::unique_ptr<FooImage> FoolFunc(std::unique_ptr<FooImage> foo)
{
return foo;
}
int main()
{
std::unique_ptr<FooImage> uniq_ptr(new FooImage);
FoolFunc(uniq_ptr);
}
2.why
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return ptr;
}
does not compile?
Could somebody shed some light on this matter?
|
1.There is no copy ctor for std::unique_ptr<T> indeed, there should not a function could accept a parameter declared as
std::unique_ptr<T>.
In fact, this is ok as long as you move the original std::unique_ptr to this local parameter
FoolFunc(std::move(uniq_ptr)); // ok
FoolFunc(std::unique_ptr<FooImage>{new FooImage}); // also ok
2.why
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }
does not compile?
Although the type of ptr is an rvalue reference, it is itself an lvalue, so return ptr will call the copy ctor, you need to use std::move to cast ptr to an rvalue again
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return std::move(ptr);
}
|
71,419,276 | 71,432,895 | What is a good pattern for array template compatibility? | I would like to create objects having a variable-length array of elements, and have them be compatible in a base/derived-class sense. In C, one could put an indeterminate array at the end of a struct and then just malloc the object to contain the full array:
struct foo {
int n;
double x[];
} ;
struct foo *foo1 = (foo *)malloc( sizeof( foo ) + sizeof( double[4] ) );
struct foo *foo2 = (foo *)malloc( sizeof( foo ) + sizeof( double[100] ) );
In c++, it seems like you could do:
template <unsigned I>
class foo {
public:
int n;
double x[I];
} ;
but:
auto foo1 = new foo<4>( );
auto foo2 = new foo<100>( );
if (foo1 == foo2) cerr << "incompatible pointers";
You can do it with a common base class, but is that necessary? I just want to use foo1 and foo2, where each object knows the length of its array.
My application is for an ESP32 microcontroller running FreeRTOS. It has limited, non-virtual RAM and a slightly complicated allocation system because of differing capabilities of various chunks of memory (some is slower, some can't contain executable code, some can't be accessed by DMA, etc.) So allocating multiple chunks for pieces of an object (for example, by using std::vector for the array of double at the end) becomes complicated.
I know the length of the double array at object construction time, but I would like the header and the array to be in a single allocated block of memory (so it can have the characteristics I need for it to have later).
The C-style way of doing it would be fine, but it would be nice to have C++ features like iteration over the array (for various objects, which will each have different numbers of doubles). Plus, a native C++ solution would allow me to have objects in the x[] array, instead of fooling around with placement new in raw allocated memory. So, for example:
auto a[] = { new foo<5>( ), new foo<10>( ), new foo<15>( ) };
for (auto i : a)
for (auto j : i.x)
cout << log10( j ); // prints 40 logs of doubles
(I expect that's got C++ syntax errors, but hopefully it communicates the idea. I can figure out the syntax for that, if I could get all the foos into a common container.)
| As a low-level C++ developer, I understand exactly what you need, and sadly, there is no replacement for flexible array members in standard C++, with or without templates. You have to keep using flexible array members via compiler extensions.
They are not included in the language since in their current form, they are essentially a hack. They don't do well with inheritance or composition.
The problem with templates is that, the flexible array version has a common type of arrays of all sizes. That means you can place them in arrays, have non-template functions take them as parameters etc:
foo* make_foo(int n);
foo* foos[] = { make_foo(1); make_foo(2); make_foo(3); }; // ok
void take_foo(foo*);
With the template version, types foo<1> and foo<2> are completely unrelated, so you cannot put them in arrays or have non-template functions that take them:
template <int N>
foo<N>* make_foo();
auto foos[] = { make_foo<1>(), make_foo<2>(), make_foo<3>() }; // ill-formed
template <int N>
void take_foo(foo<N>*);
std::array won't help in this discussion, and inheriting from one will still have the problem of having unrelated types.
However, since this is still C++ (albeit non-standard), you can at least have some additional niceties:
template <class T>
struct flex_array {
int n;
T data[];
T* begin() { return &data[0]; }
T* end() { return begin() + n; }
};
void iterate(flex_array<double>& f) {
for (double j : f) {
cout << log10(j); // print however many doubles are in f
}
}
|
71,419,557 | 71,419,647 | Control rate of function calls per second | An operation takes 65ms to complete. It needs to be triggered 'numOpr' times at a specific target operations per second.
How do we control the operation to be trigged at a specific rate?
Below is a sample that I tried but it doesn't seem to care about target operations per second. It is always at ~15ops at all valid targetOps values.
Target Environment : gcc5.x, C++11
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
float ops;
//target number of operations
const std::intmax_t targetOPS = 10;
//number of operations
const std::size_t numOpr = 20;
std::chrono::duration<double, std::ratio<1, targetOPS>> timeBetweenOperation;
std::chrono::time_point<std::chrono::steady_clock, decltype(timeBetweenOperation)> tp;
std::chrono::time_point<std::chrono::high_resolution_clock> started = std::chrono::high_resolution_clock::now();
//need to run some operation 10 times at specific intervals
for(size_t i= 0; i<numOpr;i++){
//Some operation taking 65ms
std::this_thread::sleep_for(std::chrono::milliseconds(65));
//delay between each operation if required to reach targetOPS
tp = std::chrono::steady_clock::now() + timeBetweenOperation;
std::this_thread::sleep_until(tp);
}
std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
auto dt_us = std::chrono::duration_cast<std::chrono::microseconds> (now - started).count ();
if (dt_us > 0)
{
ops = numOpr * 1000000.0 / dt_us;
}
else
{
ops = 0.0;
}
std::cout<<"Operations per second: "<< ops <<std::endl;
std::cout<<"Target operations per second: ~"<< targetOPS <<std::endl;
}
| Problem #1 is that you didn't initialize timeBetweenOperation, so it will be set to 0 ticks at your 1/N rate. Thus, you are always adding 0. You can fix that by initializing it:
std::chrono::duration<double, std::ratio<1, targetOPS>> timeBetweenOperation(1);
Problem #2 is the way you are doing the sleep_until. You are sleeping until now plus the interval, so you'll always get 65ms PLUS your 100ms gab, resulting in 6 ops per second. If you want the operation N times per second, you'll need to grab now BEFORE you do the 65ms operation.
for(size_t i= 0; i<numOpr;i++){
//Compute target endpoint
tp = std::chrono::steady_clock::now() + timeBetweenOperation;
// Some operation taking 65ms
std::this_thread::sleep_for(std::chrono::milliseconds(65));
std::this_thread::sleep_until(tp);
}
|
71,420,262 | 71,420,350 | C++ Template specialization with variable template parameter count | I have the problem, that i have a template<typename R, typename... ArgTs> class that should have a function R call(ArgTs... args). The Problem is, that i need a special case, where R is void. I already tried std::is_same<...> with constexpr but this is not possible as i use c++11.
Here i have broken down the problem to the two functions and how i think it sould look like:
template <typename R, typename... ArgTs>
R call(Callable<R, ArgTs...> *_callback, SemaphoreHandle_t _mutex, ArgTs... args) {
xSemaphoreTakeRecursive(_mutex, portMAX_DELAY);
if (_callback != nullptr) {
if (_callback->isAlive()) {
R returnVal = _callback->call(args...);
xSemaphoreGiveRecursive(_mutex);
return returnVal;
}
}
xSemaphoreGiveRecursive(_mutex);
return (R)0;
}
template <typename... ArgTs>
void call<void, ArgTs...>(Callable<void, ArgTs...> *_callback, SemaphoreHandle_t _mutex,
ArgTs... args) {
xSemaphoreTakeRecursive(_mutex, portMAX_DELAY);
if (_callback != nullptr) {
if (_callback->isAlive()) {
_callback->call(args...);
}
}
xSemaphoreGiveRecursive(_mutex);
}
The compiler gives this error: error: non-type partial specialization 'call<void, ArgTs ...>' is not allowed
I understand why, as the two templates are basically the same, as they accept as many parameters as you want, but how can i solve this problem?
The function should also be inside of a class as method (template class ...), but with the two functions i wrote i could build only a wrapper inside the class to make the template thing simpler.
| Function templates can't be partial specified, you can overload them.
template <typename R, typename... ArgTs>
typename std::enable_if<!std::is_same<R, void>::value, R>::type
call(Callable<R, ArgTs...> *_callback, SemaphoreHandle_t _mutex, ArgTs... args) {
...
}
template <typename... ArgTs>
void
call(Callable<void, ArgTs...> *_callback, SemaphoreHandle_t _mutex, ArgTs... args) {
...
}
Or if you still need the template parameter R for the 2nd function template, you can add the std::enable_if check for it too.
template <typename R, typename... ArgTs>
typename std::enable_if<std::is_same<R, void>::value, R>::type
call(Callable<R, ArgTs...> *_callback, SemaphoreHandle_t _mutex, ArgTs... args) {
...
}
|
71,420,403 | 71,420,777 | Why my answer is getting accepted with set but not with vector? | Question is We have to find if there is any sub array whose sum is zero.Return true if possible and false if not.
Time contraint:3 seconds
This is the code using unordered set getting accepted .
bool subArrayExists(int arr[], int n)
{
//Your code here
int sum=0;
unordered_set<int>s;
for(int i=0;i<n;i++){
sum=sum+arr[i];
if(sum==0||s.find(sum)!=s.end()){
return true;
}
s.insert(sum);
}
return false;
}
This is the vector solution which is giving tle.
bool subArrayExists(int arr[], int n)
{
//Your code here
int sum=0;
vector<int>v;
for(int i=0;i<n;i++){
sum=sum+arr[i];
if(sum==0||find(v.begin(),v.end(),sum)!=v.end()){
return true;
}
v.push_back(sum);
}
return false;
}
| This line
if(sum==0||s.find(sum)!=s.end()){
is very different from this line
if(sum==0||find(v.begin(),v.end(),sum)!=v.end()){
First, a unordered_set does not store the same element twice. In general this would make a difference, though as you stop when you encounter the first duplicate, the number of elements in the vector and in the set are the same here.
Next, std::unordered_set::find has average constant complexity while std::find is linear. std::unordered_set::find can make use of the internal structure of the set, thats why it exists in the first place. You don't want to use std::find with a unordered set, because that would be less performant. With the unordered set your algorithm is O(N) with the vector it is O(1 + 2 + 3 + ... + N) which is O(N^2).
Note that the version with the unodered set could be made even faster. Currently you are searching the element twice. Once here s.find(sum) and another time when inserting it. You could do it both at once when you use the return value from unodered_set::insert. It returns a pair of an iterator (pointing to the element) and a bool that indicates whether the element was inserted. When that bool is false, the element was already present before:
sum=sum+arr[i];
auto ret = s.insert(sum);
if(sum==0 || ret.second == false){
return true;
}
|
71,420,687 | 71,422,030 | How to return class by value with prohibited copying? | I have the following class and I just want to add a few simple function wrappers to return an instance of this class with some arguments/common initialization, just not to do it for each instantiation:
struct myClass
{
myClass(arg1, arg2, arg3, arg4 );
myClass( myClassconst& ) = delete;
myClass& operator=( myClass const& ) = delete;
void doSomething();
};
// it is possible to simply return it
myClass createMyClass1234()
{
return myClass( 1, 2, 3, 4 );
}
But is it possible to do this?
I actually don't want to copy it, just want to simplify this class creating with some initial actions.
// Error - copy ctor is deleted
myClass createMyClass1234andDoSomething()
{
myClass ret( 1, 2, 3, 4 );
ret.doSomething();
return ret;
}
Can I move it somehow? I know, that I can return the pointer, but is it possible not to use dynamic memory?
| Simply add a move constructor:
myClass( myClass &&) = default;
You probably also want move assignment operator, but adding that one line will make your question code to work.
Depending on what your real class is, you may of course actually have to write some code, instead of just defaulting these. Look up rule of 0/3/5, it's one of the cornerstones of writing classes with modern C++. Since you are deleting the copy constructor, you should follow rule of 5, ideally just having = default for all of these.
|
71,420,900 | 71,440,391 | LNK1104: cannot open file 'libboost_python27-vc142-mt-x64-1_71.lib' while boost_python version is 1.72 | I'm using cmake and Visual Studio 2019 to build my project. My boost version is 1.72 and I generated file libboost_python27-vc142-mt-x64-1_72.lib in directory boost_1_72_0\stage\lib with b2.exe.
I generated .sln file with cmake. Then I build the project in Visual Studio 2019. However,
it ended up with an error LNK1104: cannot open file 'libboost_python27-vc142-mt-x64-1_71.lib'
I really can't understand why it asks for libboost_python of version 1_71 instead of 1_72. I never introduced a version 1.71 request in any file. So how should it be like that? And how can I make it work?
My CMakeLists.txt file:
project(framecore)
cmake_minimum_required(VERSION 3.20)
message(STATUS "Configuring framecore")
set(Boost_USE_STATIC_LIBS ON)
# windows
if(MSVC)
# this although can be set by system variable Boost_INCLUDE_DIR etc
set(Boost_INCLUDE_DIR F:/boost_1_72_0)
set(Boost_LIBRARY_DIR F:/boost_1_72_0/stage/lib)
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(PythonLibs 2.7 REQUIRED)
find_package(Boost REQUIRED COMPONENTS system)
find_package(Boost REQUIRED COMPONENTS container)
find_package(Boost REQUIRED COMPONENTS python27)
file(GLOB_RECURSE SRC src/core/*.cpp
src/wraps/*.cpp)
file(GLOB_RECURSE SRC_HEADER src/core/*.hpp
src/core/*.h
src/wraps/*.hpp
src/wraps/*.h)
include_directories(src)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${PYTHON_INCLUDE_DIRS})
message(STATUS "Boost Include path: ${Boost_INCLUDE_DIRS}")
message(STATUS "Python2.7 Include path: ${PYTHON_INCLUDE_DIRS}")
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBOOST_PYTHON_STATIC_LIB -DBOOST_USE_WINDOWS_H /bigobj")
set(CMAKE_LINK_FLAGS "${CMAKE_LINK_FLAGS} /verbose:lib")
endif()
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build/output)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build/output)
add_library(${PROJECT_NAME} SHARED ${SRC_HEADER} ${SRC})
# set target library's prefix suffix
if(MSVC)
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "")
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".pyd")
endif()
message(STATUS "Boost_PYTHON27_LIBRARY: ${Boost_PYTHON27_LIBRARY}")
# optimized;F:/boost_1_72_0/stage/lib/libboost_python27-vc142-mt-x64-1_72.lib;debug;F:/boost_1_72_0/stage/lib/libboost_python27-vc142-mt-gd-x64-1_72.lib
target_link_libraries(${PROJECT_NAME} ${Boost_PYTHON27_LIBRARY})
target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARY})
target_link_libraries(${PROJECT_NAME} ${Boost_SYSTEM_LIBRARY})
target_link_libraries(${PROJECT_NAME} ${Boost_CONTAINER_LIBRARY})
| I know the reason now. There is another boost directory with some header files in my project folder. I wrongly included the boost directory and made a dependency on boost 1.71....
|
71,421,528 | 71,434,960 | How to convert std::vector<std::pair<double, double>> dataVector to Eigen::MatrixXd rtData(dataVector.size(), 2) | Is there a fast way to make conversion below?
use "std::vector<std::pair<double, double>> dataVector" to initialize "Eigen::MatrixXd rtData(dataVector.size(), 2)"
| Assuming sizeof(std::pair<int,int>) == 2*sizeof(int) (i.e., std::pair is not adding any padding) you can use an Eigen::Map of a row-major integer matrix, then cast it to double. Something like this:
typedef Eigen::Matrix<int, Eigen::Dynamic, 2, Eigen::RowMajor> MatrixX2i_r;
Eigen::MatrixXd rtData
= Eigen::Map<MatrixX2i_r const>(&(dataVector[0].first), dataVector.size(), 2).cast<double>();
You can also use that expression directly without storing it into a MatrixXd (conversion will happen on the fly, every time the expression is used -- so if you use rtData multiple times, it could still be better to store it once).
|
71,422,055 | 71,455,461 | Using glslang to extract all uniform delcarations in a glsl file? | I want to do some glsl parsing, in particular I want to find all uniform declarations, that includes SSBOS, samplers and images.
To my understanding glslang provides access to the AST, meaning it can be a a robust time saver to avoid writing a brittle parser yourself.
However I don't see a lot of documentation for the library on the git repo. There are some unit tests which gives me some generic idea of how it works but I am still not sure how I would iterate over the AST to find the text blocks corresponding to uniforms.
I basically need to export them to a different file.
| TIntermTraverser is the way to go.
In practice, you will define your custom traverser class by inheriting TIntermTraverser.
For more details, read the doc comments on the top of the definition of TIntermTraverser.
TIntermTraverser is used globally in the glslang project, so examining how it is used in the project will be a good help to understand the usage.
glslang/MachineIndependent/intermOut.cpp is a good starting point, I think.
I wrote the sample code for you, which is shown below.
void glslang_refrection(const std::string& fpath) {
glslang::InitializeProcess();
{
auto src = file::read_file(fpath);
const char* const sources[] = {src.c_str()};
const int sourceLengths[] = {static_cast<int>(src.size())};
const char* sourceNames[] = {""};
const int sources_num = 1;
const auto shader_stage = EShLanguage::EShLangCompute;
glslang::TShader shader{shader_stage};
shader.setStringsWithLengthsAndNames(sources, sourceLengths, sourceNames, sources_num);
shader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450);
shader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_0);
TBuiltInResource default_builtin_resources{};
shader.parse(&default_builtin_resources, 450, ECoreProfile, false, true, EShMsgDefault);
class RefrectionTraverser : public glslang::TIntermTraverser {
public:
virtual void visitSymbol(glslang::TIntermSymbol* symbol) override {
if (symbol->getQualifier().isUniformOrBuffer()) {
auto name = symbol->getName();
auto qualifier = symbol->getQualifier();
fprintf(stderr, "%s: %s\n", name.c_str(),
glslang::GetStorageQualifierString(qualifier.storage));
if (qualifier.hasLocation()) {
fprintf(stderr, " loc: %d\n", qualifier.layoutLocation);
}
if (qualifier.hasBinding()) {
fprintf(stderr, " binding: %d\n", qualifier.layoutBinding);
}
if (qualifier.hasPacking()) {
fprintf(stderr, " packing: %s\n",
glslang::TQualifier::getLayoutPackingString(
qualifier.layoutPacking));
}
}
}
};
RefrectionTraverser traverser;
auto root = shader.getIntermediate()->getTreeRoot();
root->traverse(&traverser);
}
glslang::FinalizeProcess();
}
For the following compute shader, you will get the result below.
#version 450 core
layout(std430, binding = 2) buffer TestBuffer {
int type;
float value;
};
layout(location = 2) uniform float u_time;
layout(binding = 1, std140) uniform MainBlock { vec3 data; } u_block;
void main() {}
anon@0: buffer
binding: 2
packing: std430
u_time: uniform
loc: 2
u_block: uniform
binding: 1
packing: std140
|
71,422,259 | 71,422,281 | Creating an array of string_view elements throws error: unable to find string literal operator ‘operator""sv’ with | I have the following (modified) code where I want to create an array of string_view type objects.
I see this error when compiling corresponding to each line
unable to find string literal operator ‘operator""sv’ with ‘const char [8]’, ‘long unsigned int’ arguments
"Sensor2"sv,
The code:
#include <iostream>
#include <array>
#include <string_view>
struct Abc
{
static constexpr std::array<std::string_view, 6> SomeValues = {
"Sensor1"sv,
"Sensor2"sv,
"Actuator1"sv,
"Actuator2"sv,
"Cpu1"sv,
"Cpu2"sv
};
};
int main()
{
Abc abc;
std::cout<<abc.SomeValues[3];
return 0;
}
| You need using namespace std::literals;.
See also this question.
|
71,422,608 | 71,423,440 | Transparent passing C++ variadic call parameters to ostream output operator | I have written myself the following function:
template <class Stream>
inline Stream& Print(Stream& in) { return in;}
template <class Stream, class Arg1, class... Args>
inline Stream& Print(Stream& sout, Arg1&& arg1, Args&&... args)
{
sout << arg1;
return Print(sout, args...);
}
It should make it useful to replace code like:
cout << "This took " << ns << " seconds with " << np << " packets.\n";
with
Print(cout, "This took ", ns, " seconds with ", np, " packets.\n");
And everything works fine, except that this function doesn't "tolerate" some manipulators. What is funny, only some of them. If you replace, for example, " packets.\n" with " packets.", endl, it will no longer compile. Although hex or setw(20) is fine. Where is the problem?
| std::endl is a function template.
So it cannot be deduced as for overloaded functions.
static_cast<std::ostream& (*)(std::ostream&)>(&std::endl)
would select correct overload.
using Manipulator = std::ostream& (*)(std::ostream&);
Print(std::cout, "This took ", ns, " seconds with ", np, " packets.", Manipulator(std::endl));
Demo
Since C++14, you might even not hard code type of stream with an helper:
template <typename T>
struct ManipulatorImpl
{
ManipulatorImpl(T t) : t(t) {}
T t;
};
template <typename T>
std::ostream& operator << (std::ostream& os, ManipulatorImpl<T> m)
{
return m.t(os);
}
template <typename T>
ManipulatorImpl<T> make_ManipulatorImpl(T t) { return {t}; }
#define Manipulator(name) make_ManipulatorImpl([](auto& os) -> decltype((name)(os)) { return (name)(os); })
Demo
|
71,422,977 | 71,517,899 | Why tesseract::ResultIterator breaks Chinese word into separate words? | I have such picture:
Chinese characters
I want to find location of "简体中文", but for some reason with ResultIteratorLevel::RIL_WORD the ResultIterator breaks it like this:
word: "简体"
word: "中"
word: "文"
I don't understand why this happens. I've tried a lot of options, different page segmentation modes, but no luck. However, when I use getUTF8Text() with specified coordinates it returns the correct "简体中文" Chinese text.
How I can get the correct result using the ResultIterator?
Versions:
tesseract 5.0.0
leptonica-1.78.0
libgif 5.1.9 : libjpeg 8d (libjpeg-turbo 2.0.3) : libpng 1.6.37 : libtiff 4.1.0 : zlib 1.2.11 : libwebp 0.6.1 : libopenjp2 2.3.1
Found AVX512BW
Found AVX512F
Found AVX2
Found AVX
Found FMA
Found SSE4.1
Found OpenMP 201511
Full code:
#include <iostream>
#include <leptonica/allheaders.h>
#include <tesseract/baseapi.h>
int main() {
const char *pattern = "简体中文";
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
Pix *image = pixRead("chinese_characters.png");
if (api->Init("/usr/local/share/tessdata/", "chi_sim")) {
fprintf(stderr, "Could not initialize tesseract.\n");
exit(1);
}
api->SetImage(image);
api->Recognize(0);
tesseract::ResultIterator *ri = api->GetIterator();
tesseract::PageIteratorLevel level = tesseract::RIL_WORD;
if (ri != 0) {
do {
const char *word = ri->GetUTF8Text(level);
float conf = ri->Confidence(level);
int x1, y1, x2, y2;
ri->BoundingBox(level, &x1, &y1, &x2, &y2);
printf("word: '%s'; conf: %.2f; BoundingBox: %d,%d,%d,%d;\n", word, conf,
x1, y1, x2, y2);
} while (ri->Next(level));
}
// Destroy used object and release memory
api->End();
delete api;
pixDestroy(&image);
return 0;
}
Full output:
word: '单词'; conf: 94.69; BoundingBox: 170,226,270,275;
word: '“单词'; conf: 55.34; BoundingBox: 390,226,490,275;
word: '单词'; conf: 88.91; BoundingBox: 610,226,710,275;
word: '单词'; conf: 92.26; BoundingBox: 830,226,930,275;
word: '简体'; conf: 96.09; BoundingBox: 95,372,199,421;
word: '中'; conf: 93.13; BoundingBox: 228,372,291,421;
word: '文'; conf: 48.71; BoundingBox: 290,368,348,444;
word: '”单词'; conf: 48.71; BoundingBox: 393,375,493,424;
word: '单词'; conf: 91.40; BoundingBox: 613,375,713,424;
word: '单词'; conf: 86.79; BoundingBox: 833,375,933,424;
word: '单词'; conf: 57.25; BoundingBox: 1053,375,1153,424;
word: '单词'; conf: 94.69; BoundingBox: 174,520,274,569;
word: '“单词'; conf: 55.34; BoundingBox: 394,520,494,569;
word: '单词'; conf: 88.91; BoundingBox: 614,520,714,569;
word: '单词'; conf: 92.26; BoundingBox: 834,520,934,569;
| Actually this is a correct behavior, because in Chinese some specific symbols may be as separate words. If you want to recognize such symbols together without spaces then just use the tesseract::RIL_SYMBOL instead of tesseract::RIL_WORD. Thus, you can iterate through each symbol one by one.
|
71,423,128 | 71,423,352 | How can I static assert to disallow "mixed endianness" in a non-templated member function | I am using 2 x std::uint64_t and 1 x std::uint32_t in a high performance implementation of of operator<=> in a struct conataining a std::array<std::byte, 20>.
I am trying to make it cross compiler and architecture compatible.
As part of that I am trying to outright reject any architecture with std::endian::native which is not std::endian::little or std::endian::big.
I think I am running foul of the "static_assert must depend on a template parameter rule", as the struct and the member function are not templated.
std::strong_ordering operator<=>(const pawned_pw& rhs) const {
static_assert(sizeof(std::uint64_t) == 8);
static_assert(sizeof(std::uint32_t) == 4);
if constexpr (std::endian::native == std::endian::little) {
// c++23 will have std::byteswap, so we won't need this
#ifdef _MSC_VER
#define BYTE_SWAP_32 _byteswap_ulong
#define BYTE_SWAP_64 _byteswap_uint64
#else
#define BYTE_SWAP_32 __builtin_bswap32
#define BYTE_SWAP_64 __builtin_bswap64
#endif
// this compiles to a load and `bswap` which should be fast
// measured > 33% faster than hash < rhs.hash, which compiles to `memcmp`
std::uint64_t head = BYTE_SWAP_64(*(std::uint64_t*)(&hash[0])); // NOLINT
std::uint64_t rhs_head = BYTE_SWAP_64(*(std::uint64_t*)(&rhs.hash[0])); // NOLINT
if (head != rhs_head) return head <=> rhs_head;
std::uint64_t mid = BYTE_SWAP_64(*(std::uint64_t*)(&hash[8])); // NOLINT
std::uint64_t rhs_mid = BYTE_SWAP_64(*(std::uint64_t*)(&rhs.hash[8])); // NOLINT
if (mid != rhs_mid) return mid <=> rhs_mid;
std::uint32_t tail = BYTE_SWAP_32(*(std::uint32_t*)(&hash[16])); // NOLINT
std::uint32_t rhs_tail = BYTE_SWAP_32(*(std::uint32_t*)(&rhs.hash[16])); // NOLINT
return tail <=> rhs_tail;
} else if constexpr (std::endian::native == std::endian::big) {
// can use big_endian directly
std::uint64_t head = *(std::uint64_t*)(&hash[0]); // NOLINT
std::uint64_t rhs_head = *(std::uint64_t*)(&rhs.hash[0]); // NOLINT
if (head != rhs_head) return head <=> rhs_head;
std::uint64_t mid = *(std::uint64_t*)(&hash[8]); // NOLINT
std::uint64_t rhs_mid = *(std::uint64_t*)(&rhs.hash[8]); // NOLINT
if (mid != rhs_mid) return mid <=> rhs_mid;
std::uint32_t tail = *(std::uint32_t*)(&hash[16]); // NOLINT
std::uint32_t rhs_tail = *(std::uint32_t*)(&rhs.hash[16]); // NOLINT
return tail <=> rhs_tail;
} else {
static_assert(std::endian::native != std::endian::big &&
std::endian::native != std::endian::little,
"mixed-endianess architectures are not supported");
}
}
I guess I could just fall back instead of static_assert
} else {
// fall back to the slow way
hash <=> rhs.hash;
}
| I suggest asserting that it's either big or little endian:
#include <bit>
#include <compare>
struct pawned_pw {
std::strong_ordering operator<=>(const pawned_pw& rhs) const {
static_assert(std::endian::native == std::endian::big ||
std::endian::native == std::endian::little,
"mixed-endianess architectures are not supported");
if constexpr (std::endian::native == std::endian::little) {
return ...;
} else {
// big
return ...;
}
}
};
|
71,423,188 | 71,441,767 | Codeql c c++ ql queries | I want to statically check the vulnerabilities of c c++ code with codeql, such as: double free, array out of bounds, resource Allocates,releases unpaired etc., where can I get a ql scripts to use.
This SDK:https://github.com/github/codeql is too chaos,too many,can I got a comprehensive ql scripts?
if I write the ql queries myself,Whether to learn relevant grammar?
Wanna some answers,thanks a lot~! ^_^
| It highly depends on the context in which you want to use CodeQL. The license only permits you to use it on open source projects and for academic research (read the complete license for more information). If you want to add CodeQL code scanning to your GitHub repository, you can take a look at About code scanning with CodeQL.
If you want to write queries yourself, the documentation is probably a good place to start. They also have a guide for getting started with CodeQL for C and C++, and tutorials. The language reference might be useful as well, but probably only once you have become familiar with it a bit.
The CodeQL query help for C and C++ might be helpful as well, to see which queries already exist, and also how they are implemented. But of course it does not hurt to try to implement them yourself as well to get some practice.
|
71,423,398 | 71,565,667 | C++ 20 coroutines with PyBind11 | I'm trying to get a simple C++ 20 based generator pattern work with PyBind11. This is the code:
#include <pybind11/pybind11.h>
#include <coroutine>
#include <iostream>
struct Generator2 {
Generator2(){}
struct Promise;
using promise_type=Promise;
std::coroutine_handle<Promise> coro;
Generator2(std::coroutine_handle<Promise> h): coro(h) {}
~Generator2() {
if(coro)
coro.destroy();
}
int value() {
return coro.promise().val;
}
bool next() {
std::cout<<"calling coro.resume()";
coro.resume();
std::cout<<"coro.resume() called";
return !coro.done();
}
struct Promise {
void unhandled_exception() {std::rethrow_exception(std::move(std::current_exception()));}
int val;
Generator2 get_return_object() {
return Generator2{std::coroutine_handle<Promise>::from_promise(*this)};
}
std::suspend_always initial_suspend() {
return {};
}
std::suspend_always yield_value(int x) {
val=x;
return {};
}
std::suspend_never return_void() {
return {};
}
std::suspend_always final_suspend() noexcept {
return {};
}
};
};
Generator2 myCoroutineFunction() {
for(int i = 0; i < 100; ++i) {
co_yield i;
}
}
class Gen{
private:
Generator2 myCoroutineResult;
public:
Gen(){
myCoroutineResult = myCoroutineFunction();
}
int next(){
return (myCoroutineResult.next());
}
};
PYBIND11_MODULE(cmake_example, m) {
pybind11::class_<Gen>(m, "Gen")
.def(pybind11::init())
.def("next", &Gen::next);
}
However I'm getting an error:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Could c++ coroutines, coroutine_handles, co_yield etc. be a low-level thing that is not supported by PyBind11 yet?
| Even though PyBind11 does not support coroutines directly, your problem does not mix coroutine and pybind code since you are hiding the coroutine behind Gen anyway.
The problem is that your Generator2 type uses the compiler provided copy and move constructors.
This line:
myCoroutineResult = myCoroutineFunction();
Creates a coroutine handle when you call myCoroutineFunction, and puts it in the temporary Generator2 in the right hand side. Then, you initialize myCoroutineResult from the right hand side generator. All is well, but then the temporary gets destroyed. Your destructor checks whether the handle is valid or not:
~Generator2() {
if(coro)
coro.destroy();
}
But in your implementation, the coro member of the member generator gets copied from the temporary without resetting the temporary's coro member. So the coroutine itself gets destroyed once you initialize myCoroutineResult, and you are holding onto a dangling coroutine handle. Remember that std::coroutine_handles behave like a raw pointer.
Essentially, you have a violation of the rule of 5. You have a custom destructor, but no copy/move constructors or assignment operators. Since you cannot copy construct a coroutine, you can ignore the copy constructors but you need to provide move constructors/assigment operators:
Generator2(Generator2&& rhs) : coro{std::exchange(rhs.coro, nullptr)} {
// rhs will not delete our coroutine,
// since we put nullptr to its coro member
}
Generator2& operator=(Generator2&& rhs) {
if (&rhs == this) {
return *this;
}
if (coro) {
coro.destroy();
}
coro = std::exchange(rhs.coro, nullptr);
return *this;
}
Also, use member initialization list to initialize members instead of assigning them within the constructor body. So instead of this:
Gen(){
myCoroutineResult = myCoroutineFunction();
}
Use this:
Gen() : myCoroutineResult{myCoroutineFunction()} {}
The reasoning can be seen even in this answer. The first one calls the assignment operator, which performs a bunch of additional work, whereas the second one calls the move constructor, which is as lean as it gets.
|
71,423,435 | 71,424,793 | Undefined behaviour accessing const ptr sometimes | I have a header file defined as
#pragma once
#include <iostream>
template<int size>
struct B
{
double arr[size * size];
constexpr B() : arr()
{
arr[0] = 1.;
}
};
template<int size>
struct A
{
const double* arr = B<size>().arr;
void print()
{
// including this statement also causes undefined behaviour on subsequent lines
//printf("%i\n", arr);
printf("%f\n", arr[0]);
printf("%f\n", arr[0]); // ???
// prevent optimisation
for (int i = 0; i < size * size; i++)
printf("%f ", arr[i]);
}
};
and call it with
auto a = A<8>();
a.print();
Now this code only runs expectedly when compiled with msvc release mode (all compiled with c++17).
expected output:
1.000000
1.000000
msvc debug:
1.000000
-92559631349317830736831783200707727132248687965119994463780864.000000
gcc via mingw (with and without -g):
1.000000
0.000000
However, this behaviour is inconsistent. The expected output is given if I replace double arr[size * size] with double arr[size] instead. No more problems if I allocate arr on the heap of course.
I looked at the assembly of the msvc debug build but I don't see anything out of the ordinary. Why does this undefined behaviour only occur sometimes?
asm output
decompiled msvc release
| It seems that it was completely coincidental that smaller allocations were always addressed in a spot that would not get erased by the rep stosd instruction present in printf. Not caused by strange compiler optimisations as I first thought it was.
What does the "rep stos" x86 assembly instruction sequence do?
I also have no idea why I decided to do it this way. Not exactly the question I asked but I ultimately wanted a compile time lookup table so the real solution was static inline constexpr auto arr = B<size>() on c++20. Which is why the code looks strange.
|
71,423,523 | 71,424,292 | variadic template: SFINAE on last argument | I have an array (of any rank), and I would like to have an index operator that:
Allows for missing indices, such that the following is equivalent
a(1, 0, 0, 0);
a(1, my::missing);
This in itself if straightforward (see example implementation below): one just recursively adds arg * strides[dim] until my::missing it hit.
Allows automatic prepending of zeros, such that the following is equivalent
a(0, 0, 0, 1);
a(1);
Also this is not hard (see example implementation below): one recursively adds arg * strides[dim + offset].
What I cannot get my head around is: How to combine the two? The implementation of 2. makes me start of the wrong foot for 1. (I'm limited to <= C++14)
Example implementation of "my::missing" without auto pre-pending zeros
enum class my { missing };
template <size_t dim, class S>
inline size_t index_impl(const S&) noexcept
{
return 0;
}
template <size_t dim, class S, class... Args>
inline size_t index_impl(const S& strides, enum my arg, Args... args) noexcept
{
return 0;
}
template <size_t dim, class S, class Arg, class... Args>
inline size_t index_impl(const S& strides, Arg arg, Args... args) noexcept
{
return arg * strides[dim] + index_impl<dim + 1>(strides, args...);
}
template <class S, class Arg, class... Args>
inline size_t index(const S& strides, Arg arg, Args... args)
{
return index_impl<0>(strides, arg, args...);
}
int main()
{
std::vector<size_t> strides = {8, 4, 2 ,1};
std::cout << index(strides, 1, 2, 0, 0) << std::endl;
std::cout << index(strides, 1, 2, my::missing) << std::endl;
}
Example implementation of prepending zeros without "my::missing"
template <size_t dim, class S>
inline size_t index_impl(const S&) noexcept
{
return 0;
}
template <size_t dim, class S, class Arg, class... Args>
inline size_t index_impl(const S& strides, Arg arg, Args... args) noexcept
{
return arg * strides[dim] + index_impl<dim + 1>(strides, args...);
}
template <class S, class Arg, class... Args>
inline size_t index(const S& strides, Arg arg, Args... args)
{
constexpr size_t nargs = sizeof...(Args) + 1;
if (nargs == strides.size())
{
return index_impl<0>(strides, arg, args...);
}
else if (nargs < strides.size())
{
return index_impl<0>(strides.cend() - nargs, arg, args...);
}
return index_impl<0>(strides, arg, args...);
}
int main()
{
std::vector<size_t> strides = {8, 4, 2 ,1};
std::cout << index(strides, 1, 2) << std::endl;
std::cout << index(strides, 0, 0, 1, 2) << std::endl;
}
| In earlier version of this answer I didn't provided full implementation since something was not adding up for me.
If this index should calculate index for flattened multidimensional array then your example implementation is invalid. Problem is hidden since you are comparing two results for index with all indexes provided and shorten version where zero padding is assumed.
Sadly I flowed this pattern in first versions of test in Catch2.
Here is proper test for index of flattened multidimensional array, where last index matches flattened index:
TEST_CASE("index")
{
std::vector<size_t> strides = { 4, 6, 3, 5 };
SECTION("Padding with leading zeros")
{
constexpr auto i0 = 4;
constexpr auto i1 = 2;
constexpr size_t expected = i0 + i1 * 5;
CHECK(index(strides, 0, 0, i1, i0) == expected);
CHECK(index(strides, 0, 0, i1, i0 - 1) == expected - 1); // last index indexes by one
CHECK(index(strides, i1, i0) == expected);
CHECK(index(strides, i1, i0 - 1) == expected - 1);
}
SECTION("Use my::missing to use padding with tailing zeros")
{
constexpr auto i2 = 4;
constexpr auto i3 = 2;
constexpr size_t expected = (i3 * 6 + i2) * 5 * 3;
CHECK(index(strides, i3, i2, 0, 0) == expected);
CHECK(index(strides, i3, i2, my::missing) == expected);
}
}
Now starting from your code and passing those test I've got this implementation:
template <typename T, typename... Ts>
struct last_type_helper {
using type = typename last_type_helper<Ts...>::type;
};
template <typename T>
struct last_type_helper<T> {
using type = T;
};
template <typename... Ts>
using last_type = typename last_type_helper<Ts...>::type;
enum class my { missing };
template <typename... Ts>
constexpr bool LastTypeIsMy = std::is_same<my, last_type<Ts...>>::value;
template <class StrideIter>
size_t index_impl(size_t base, StrideIter)
{
return base;
}
template <class StrideIter>
size_t index_impl(size_t base, StrideIter, my)
{
return base;
}
template <class StrideIter, typename Tn, typename... Ts>
size_t index_impl(size_t base, StrideIter it, Tn xn, Ts... x)
{
return index_impl(base * *it + xn, it + 1, x...);
}
template <class S, class... Args>
size_t index(const S& strides, Args... args)
{
const size_t offset = strides.size() - sizeof...(Args);
const size_t advenceBy = LastTypeIsMy<Args...> ? 0 : offset;
const size_t lastStrides = LastTypeIsMy<Args...> ? offset + 1 : 0;
const size_t tailFactor = std::accumulate(std::end(strides) - lastStrides, std::end(strides),
size_t { 1 }, std::multiplies<> {});
return index_impl(0, std::begin(strides) + advenceBy, args...) * tailFactor;
}
Here is live demo (passing tests).
|
71,423,561 | 71,519,289 | Application of Boost Automatic Differentiation fails | I want to use the boost autodiff functionality to calculate the 2nd derivative of a complicated function.
At the boost help I can take a look on the following example:
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
template <typename T>
T fourth_power(T const& x) {
T x4 = x * x; // retval in operator*() uses x4's memory via NRVO.
x4 *= x4; // No copies of x4 are made within operator*=() even when squaring.
return x4; // x4 uses y's memory in main() via NRVO.
}
int main() {
using namespace boost::math::differentiation;
constexpr unsigned Order = 5; // Highest order derivative to be calculated.
auto const x = make_fvar<double, Order>(2.0); // Find derivatives at x=2.
auto const y = fourth_power(x);
for (unsigned i = 0; i <= Order; ++i)
std::cout << "y.derivative(" << i << ") = " << y.derivative(i) << std::endl;
return 0;
}
I want to use this possibility to calculate a derivative in my class structure but I don't understand how. Here is a simplified code example of my .cxx file. I have a parametric equation which is seperated in two functions to get the x and y-coordinate. radius is a member variable. I want to calculate the second derivative of this parametric equation at a position phi.
#include <boost/math/differentiation/autodiff.hpp>
double
get_x_coordinate(const double phi) const {
return (radius*cos(phi));
}
double
get_y_coordinate(const double phi) const {
return (radius*sin(phi));
}
double
do_something(const double phi) const {
auto const x = boost::math::differentiation::make_fvar<double, 2>(phi);
auto fx = [this](auto x) { return get_x_coordinate(x); };
auto fy = [this](auto x) { return get_y_coordinate(x); };
auto const dx = fx(x);
auto const dy = fy(x);
return (dx.derivative(2)+dy.derivative(2));
}
This example fails because of the following error.
cannot convert argument 1 from boost::math::differentiation::autodiff_v1::detail::fvar<RealType,10>' to 'const double'
I cannot change that get_x_coordinate and get_y_coordinate receive a const double and return a double because I use them in my code at other positions. So I don't really know how to continue.
Also I'm using Visual studio 2017. I ask myself what is the difference between
#include <boost/math/differentiation/autodiff.hpp>
and
#include <boost/math/differentiation/autodiff_cpp11.hpp>
Do I have to use cpp11 if I use VS2017? Both are available in my boost version.
| Functions of interest are to be converted into templates that may accept either double or boost fvar arguments. Note that boost provides custom implementations of trigonometric functions from standard library (such as sin, cos) suitable for fvar:
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
#include <math.h>
constexpr double const radius{4.0};
template <typename T>
T get_x_coordinate(T const & phi)
{
return radius * cos(phi);
}
int main()
{
double const phi{2.0};
auto const x{::boost::math::differentiation::make_fvar<double, 2>(phi)};
auto const dx{get_x_coordinate(x)};
::std::cout << dx.derivative(2) << ::std::endl;
return 0;
}
online compiler
|
71,423,700 | 71,424,305 | C++: Possibility to assign multiple Interfaces | I ran into a strange situation, and I wonder if there is a better way to implement this. I would be very thankful for suggestions.
It comes down to this simple core problem:
//Interface I1 and I2 shall not be combined, since that makes logically no sense
class I1 {
public:
virtual void foo() = 0;
};
class I2 {
public:
virtual void bar() = 0;
};
//Some classes implements both interfaces I1 and I2 (some others don't, but that's not relevant here)
class A : public I1, public I2 {
public:
void foo() override {};
void bar() override {};
};
class B : public I1, public I2 {
public:
void foo() override {};
void bar() override {};
};
//Since there is no logically meaningful parent for I1 and I2, I have to do something like this,
//to access both interfaces of class A and B
struct pair_t {
I1& accessViaI1;
I2& accessViaI2;
};
A a;
B b;
std::deque<pair_t> items;
items.push_back({ a, a });
items.push_back({ b, b });
The code is working and because there are references used for the deque, the performance should be not too bad. But at least the last lines look very strange for me. Does anyone have an idea how to code this? Or maybe an suggestion for the general structure?
The main problem is, I1 and I2 are logically totally separated and independent. But if an objects implements both, I need them both.
Same as for class A and B, it makes no sense to combine them together (neither via inheritance nor as composition)
I can use C++11 and boost.
Many thanks for your help in advance.
| To improve
items.push_back({ a, a });
items.push_back({ b, b });
into
items.push_back({ a });
items.push_back({ b });
You might add constructors to your pair_t
struct pair_t {
pair_t(I1& accessViaI1, I2& accessViaI2) :
accessViaI1(accessViaI1),
accessViaI2(accessViaI2)
{}
template <typename T,
typename std::enable_if<std::is_base_of<I1, T>::value
&& std::is_base_of<I2, T>::value, int>::type = 0>
pair_t(T& t): pair_t(t, t) {}
I1& accessViaI1;
I2& accessViaI2;
};
Demo
|
71,423,721 | 71,423,794 | Vector of objects without a default constructor and iterator | I am learning to use C++ vectors, and I can't quite understand the output of the following program:
#include <iostream>
#include <vector>
using namespace std;
class Custom {
public:
int v;
Custom() = delete;
explicit Custom(int v) : v{v} {};
Custom(const Custom &) : v{4} {
}
friend ostream &operator<<(ostream &os, const Custom &th) {
os << "V is " << th.v << endl;
return os;
}
};
int main(int argc, char *argv[]) {
vector<Custom> c(2, Custom(3));
c[0].v = 5;
for (auto i: c) {
cout << i << endl;
}
}
I expected it to produce the output
V is 5
V is 4
But instead it produces
V is 4
V is 4
Am I missing something obvious? Thanks.
| This range based loop is making copies:
for (auto i: c) {
cout << i << endl;
}
And the copy constructor initializes v to 4 (and does not make a copy):
Custom(const Custom &) : v{4} {
}
You can either implement a proper copy constructor or use references in the loop to get the desired output:
for (const auto& i: c) {
cout << i << endl;
}
I would suggest to do both, because this copy constructor is not doing a copy by any means. The compiler generated copy constructor should be fine:
Custom(const Custom &) = default;
PS: The fact that Custom has a deleted default constructor is not really relevant for the posted code. Nowhere in the code a Custom is default constructed. Also there is no iterator in your code. In the range based loop i is a copy/reference of the elements in the vector, it is not an iterator.
|
71,423,771 | 71,424,311 | How to return the values of the char linked lists and store it as a string? | I created this program that should check the string entered by user in form of characters using doubly linked lists in C++, however I got stuck at the last point in which I should compare the original word with the reversed one to see if the two words are palindrome or not, how to store the content of function display() and reverse() to a string variable so that I can return the value and compare them?
Also, reverse() function doesn't display the reversed word
This is my code:
#include <iostream>
using namespace std;
class Storage {
public:
char lett;
Storage* next;
Storage* prev;
};
void push(char lett1, Storage** head) {
Storage* n = new Storage();
n->lett = lett1;
n->next = NULL;
if (*head == NULL) {
*head = n;
}
else {
n->next = *head;
*head = n;
}
}
void display(Storage* head, int no) {
Storage* s = head;
while (head != NULL) {
int i = 0;
cout << head->lett;
s = head;
head = head->next;
}
}
void reverse(Storage* tail) {
Storage* t = tail;
// Storage* original= tail;
while (t != NULL) {
cout << t->lett;
t = t->prev;
}
}
/*
string checkPalindrome() {
string check;
if ()
check == "Yes";
else
check == "No";
return check;
}
*/
int main() {
Storage* head = NULL; Storage* tail = NULL;;
char lett;
int size;
string result;
cout << ":: Palindrome Program ::\n" << endl;
cout << "Enter total character: ";
cin >> size;
cout << "Enter character: ";
for (int i=0; i < size; i++) {
cin >> lett;
push(lett, &head);
}
cout << "Your word: ";
display(head, size); //compare content of this
cout << "\nReversed word: ";
reverse(tail); // with this
/*
result = checkPalindrome();
cout << "Palindrome: " << result << endl;
*/
return 0;
}
| You have some bugs in your code. First of all my tip is that you need to make a class/struct which will hold the head and tail of your list. For example:
class DLList{
public:
NODE *head;
NODE *tail;
};
Also, as you can see you should have a class for your list nodes, and every node should have a pointer to the next node, and to the node before. Don't forget to make the first node previous pointer to point to NULL, and also the last nodes next pointer. Some other things I noticed is that you forgot to deallocate the dynamic/heap memory. Fix that with using 'free' or consider using smart pointers, so you don't have any memory leaks. At the end, try to avoid using namespace std;. It is considered a bad habit, due to bad performance. Hope it helped you. Here is the not optimized code snippet.
#include <iostream>
using namespace std;
class Storage {
public:
char lett;
Storage* next;
Storage* prev;
};
void push(char lett1, Storage** head, Storage **tail) {
Storage* n = new Storage();
n->lett = lett1;
n->next = NULL;
n->prev = NULL;
if (*head == NULL) {
*head = n;
*tail = n;
}
else {
n->next = *head;
(* head)->prev = n;
*head = n;
}
}
std::string display(Storage* head) {
Storage* s = head;
std::string org = "";
while (s != NULL) {
org += s->lett;
s = s->next;
}
return org;
}
std::string reverse(Storage* tail) {
Storage* t = tail;
std::string rev = "";
// Storage* original= tail;
while (t != NULL) {
rev += t->lett;
t = t->prev;
}
return rev;
}
bool checkPalindrome(Storage* head, Storage* tail) {
return display(head) == reverse(tail);
}
int main() {
Storage* head = NULL; Storage* tail = NULL;;
char lett;
int size;
cout << ":: Palindrome Program ::\n" << endl;
cout << "Enter total character: ";
cin >> size;
cout << "Enter character: ";
for (int i = 0; i < size; i++) {
cin >> lett;
push(lett, &head,&tail);
}
cout << "Your word: ";
cout<<display(head)<<endl; //compare content of this
cout << "\nReversed word: ";
cout<<reverse(tail)<<endl; // with this
cout << "\nPalindrome: " << checkPalindrome(head, tail) << endl;
return 0;
}
|
71,423,851 | 71,436,494 | How to initialize WinRT AudioGraphSettings using WRL ComPtr? | With C++/WinRT the AudioGraphSettings can be easily initialized with its constructor:
AudioGraphSettings settings(AudioRenderCategory::Media);
I'm having trouble to use it inside my WRL project. Below is my implementation
ComPtr<IAudioGraphSettings> settings;
Windows::Foundation::GetActivationFactory(
HStringReference(RuntimeClass_Windows_Media_Audio_AudioGraphSettings).Get(),
&settings
);
The settings still null and I don't know how to initialize it with the required AudioRenderCategory constructor.
If I do it like below, I got access violation crash because it's still null.
settings->put_AudioRenderCategory(AudioRenderCategory::AudioRenderCategory_Media);
| Type activation at the ABI level is more involved than, for example, instantiating types in C++. The admittedly terse documentation outlines the different mechanisms:
WinRT defines three activation mechanisms: direct activation (with no constructor parameters), factory activation (with one or more constructor parameters), and composition activation.
The IAudioGraphSettings type falls into the second category: It instantiates a type based on a single argument of type AudioRenderCategory. Instantiating a type is thus a two-phase process:
Retrieve an activation factory
Use the activation factory to instantiate a type
The code in the question conflates both operations, and the call to GetActivationFactory returns an HRESULT value of 0x80004002, i.e. E_NOINTERFACE. It needs to request the IAudioGraphSettingsFactory interface instead, and subsequently use that factory to instantiate the IAudioGraphSettings type.
The following is a complete implementation that illustrates how to activate an IAudioGraphSettings type:
#include <wrl/wrappers/corewrappers.h>
#include <wrl/client.h>
#include <windows.foundation.h>
#include <windows.media.audio.h>
#include <windows.media.render.h>
#pragma comment(lib, "windowsapp")
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Media::Audio;
using namespace ABI::Windows::Media::Render;
int main()
{
RoInitializeWrapper init { RO_INIT_MULTITHREADED };
HRESULT hr { init };
if (FAILED(hr))
return hr;
// Retrieve activation factory
ComPtr<IAudioGraphSettingsFactory> settings_factory {};
hr = GetActivationFactory(
HStringReference(RuntimeClass_Windows_Media_Audio_AudioGraphSettings).Get(),
&settings_factory);
if (FAILED(hr))
return hr;
// Use activation factory to instantiate type
ComPtr<IAudioGraphSettings> settings {};
hr = settings_factory->Create(AudioRenderCategory_Media, &settings);
if (FAILED(hr))
return hr;
return hr;
}
This is how things look at the ABI level, which is ultimately where the WRL lives. C++/WinRT takes care of all the boilerplate code, and neatly maps parameterized factory activation onto C++ constructor implementations. That's why the C++/WinRT implementation is so much more compact.
|
71,424,114 | 71,424,454 | Suppress compiler error for a single line MSVC19 C++20 | I want to check if a shared_ptr is uninitialized, i.e. if it is a nullptr or if it has a default value (as would be the case if created by using std::make_shared). For this purpose I wrote a code to check if the shared pointer is having a default constructed value of a class/struct. To achieve this, I also need to know if a class/struct defines the operator== and to figure that out I have has_equate. The code to check if a shared pointer is uninitialized is:
template<class L, class R = L>
concept has_equate = requires(const L & lhs, const R & rhs)
{
{ lhs == rhs } -> std::same_as<bool>;
};
template <typename T>
bool isSharedPtrUninitialized(const std::shared_ptr<T>& shared)
{
if(shared) {
if(has_equate<T>) {
T tmp;
if(*shared == tmp)
return true;
}
return false;
}
return true;
}
If I don't define operator== for my class/struct the above line of code gives the following error:
Error C2678 binary '==': no operator found which takes a left-hand operand of type 'T' (or there is no acceptable conversion)
Since I am checking if the operator== exists or not for the class/struct by using has_equate before proceeding to check if the given shared pointer has a default constructed value, I would like to suppress this error for this particular line of code.
What I have tried so far:
template <typename T>
bool isSharedPtrUninitialized(const std::shared_ptr<T>& shared)
{
if(shared) {
if(has_equate<T>) {
T tmp;
#pragma warning(suppress: 2678)
if(*shared == tmp)
return true;
}
return false;
}
return true;
}
#pragma warning(push)
#pragma warning(disable: 2678)
template <typename T>
bool isSharedPtrUninitialized(const std::shared_ptr<T>& shared)
{
if(shared) {
if(has_equate<T>) {
T tmp;
if(*shared == tmp)
return true;
}
return false;
}
return true;
}
#pragma warning(pop)
None of it is working (I assume it is because C2678 is an error and not a warning). Is there a way I could suppress this error for just if(*shared == tmp) line of code or just for the isSharedPtrUninitialized function as I do not want to do this for the entire thing.
| Thanks to @molbdnilo for providing the solution. The working function is:
template <typename T>
bool isSharedPtrUninitialized(const std::shared_ptr<T>& shared)
{
if(shared) {
if constexpr (has_equate<T>) {
T tmp;
if(*shared == tmp)
return true;
}
return false;
}
return true;
}
Using if constexpr instead of if solved the problem for me. If curious about the difference between these two then have a look at the post Difference between "if constexpr()" Vs "if()" on SO.
|
71,424,230 | 71,424,521 | The exe package CLion created cannot be ran | When I try to run the exe package that CLion created, I got an error: libgcc_s_dw2-1.dll not found.
Does anyone know how to fix this?
| If you are using MingW to compile C++ code on Windows, you may like to add the option -static-libstdc++ to link the C++ standard libraries statically. What exactly I mean is following:
For instance adding set(CMAKE_EXE_LINKER_FLAGS "-static") to your cmake file may fix it.
Additionally please also make sure you have set the environment variable correctly for MinGW in your Windows environment variable section. What exactly I mean is following:
C:\MinGW\bin to your system PATH variable
|
71,424,471 | 71,428,075 | How can the symbols be bigger than each other? Or do I not understand something? Could you explain what this code does? | Is it ok to compare symbols with each other?
#include <iostream>
using namespace std;// For Example, Why if "k = 4" it outputs "r o" ? //
int main() {
char word[] = "programming";
int k;
cin >> k;
for (int i = 0; i < k; i++)
if (word[i] > word[i + 1]) {
cout << word[i] << endl;
}
}
| The char data type is an integral type, meaning the underlying value is stored as an integer. Moreover, the integer stored by a char variable is intepreted as an ASCII character.
ASCII specifies a way to map english characters(and some other few symbols) to numbers between 0 and 127. That is, each english character(and some other few symbols) has a corresponding number between 0 and 127. This number is formally called a code point.
For example, the code point for the english character a is 97. Similarly, the code point for the english character H is 72. You can find the list of code points for all the characters here.
The important thing to note here is that the underlying value of a char variable is stored as an integer. Lets take some examples to clarify this,
char var1 = 'a'; //here var1 is stored as the integer 97
char var2 = 'H'; //here var2 is stored as the integer 72
In the above snippet, var1 is stored as the integer 97 because the code point for the english character a is 97. Similarly, var2 is stored as the integer 72 because the english character H corresponds to the code point 72.
Now lets come back to your original question. In particular what happens when k =4.
For k = 4, the for loop will be executed 4 times.
Iteration 0: Here i = 0
The if block basically translates to:
if (word[0] > word[0 + 1]) {
cout << word[0] << endl;
}
which is:
if ('p' > 'r') {
cout << 'p' << endl;
}
which is(using the ascii table):
if (112 > 114) {
cout << 'p' << endl;
}
since the condition inside if is false, the body of the if block will not be executed and you'll get no output.
Iteration 1: Here i = 1
The if block basically translates to:
if (word[1] > word[1 + 1]) {
cout << word[1] << endl;
}
which is:
if ('r' > 'o') {
cout << 'r' << endl;
}
which is(using the ascii table):
if (114 > 111) {
cout << 'r' << endl;
}
since the condition inside if is true, the body of the if block will be executed and you'll get r as output(which is followed by a newline).
Iteration 2: Here i = 2
The if block basically translates to:
if (word[2] > word[2 + 1]) {
cout << word[2] << endl;
}
which is:
if ('o' > 'g') {
cout << 'o' << endl;
}
which is(using the ascii table):
if (111 > 103) {
cout << 'o' << endl;
}
since the condition inside if is true, the body of the if block will be executed and you'll get o as output(which is followed by a newline).
Iteration 3: Here i = 3
The if block basically translates to:
if (word[3] > word[3 + 1]) {
cout << word[3] << endl;
}
which is:
if ('g' > 'r') {
cout << 'g' << endl;
}
which is(using the ascii table):
if (103 > 114) {
cout << 'g' << endl;
}
since the condition inside if is false, the body of the if block will not be executed and you'll get no output.
Hence you get the output:
r
o
|
71,424,837 | 71,425,104 | Can the names of parameters in function definition be same as the name of arguments passed to it in the function call in C++? | Suppose we have a function as given below:
int add(int num1, int num2) {
num1 += num2;
return num1;
}
Now, I call the above function by passing the arguments having the same name as the parameters in the add function.
int num1 = 10;
int num2 = 10;
int result = add(num1, num2)
Is it correct to do so? The code compiles correctly But I am not sure whether I am doing the correct thing or not?
| Yes, the names of the variables you pass in a function call can be the same as the names of the parameters in the function definition. The scope of the function parameters begins and ends in the function block, so the compiler can keep the two (or more) variables defined at different scopes separate, even when they have the same name.
You can call your function by passing variables with the same name (add(num1, num2)), different names (add(x, y)), or no names at all (add(3, 4)).
See the Function parameter scope section in the C++ Scope reference.
|
71,424,982 | 71,764,145 | Landscape Creation C++ UE4.27 | I would like to create a landscape from scratch in unreal engine 4.27 using C++ only. I have only a simple notion of the process, which revolves around GetWorld()->SpawnActor<ALandscape>, ALandscapeProxy::Import(...) and importing a height/weight map.
I used the LandscapeEditorDetailCustomization_NewLandscape::OnCreateButtonClicked() method as a learning ground, but unfortunately I am at an impasse.
From what I have gathered from my searches there not a lot of examples on the matter. Does anyone have a suggestion or an example?
| This is the solution I came up with, with many thanks to ChenHP (or chpsemail) who gave me a solution to this. Firstly, declare the following variables. A better understanding can be found here.
FQuat InRotation
FVector InTranslation
FVector InScale
FTransform LandscapeTransform{InRotation, InTranslation, InScale}
int32 QuadsPerSection
int32 SectionsPerComponent
int32 ComponentCountX
int32 ComponentCountY
int32 QuadsPerComponent
int32 SizeX
int32 SizeY
Create containers for the heights and materials of the landscape:
TArray<FLandscapeImportLayerInfo> MaterialImportLayers
TMap<FGuid, TArray<uint16>> HeightDataPerLayers
TMap<FGuid, TArray<FLandscapeImportLayerInfo>> MaterialLayerDataPerLayers
It is important to note that heights in UE4 are of uint16 type, with 0 the deepest and 65'534 the highest. So for a flat map all height entries should be 32768.
The number of heights is the resolution of the map which is dependent on SizeX and SizeY.
TArray<uint16> HeightData;
HeightData.SetNum(SizeX * SizeY);
for (int32 i = 0; i < HeightData.Num(); i++)
{
HeightData[i] = 32768;
}
Height and material information should then be placed in the corresponding containers and be given a valid FGuid.
HeightDataPerLayers.Add(FGuid(), MoveTemp(HeightData))
MaterialLayerDataPerLayers.Add(FGuid(), MoveTemp(MaterialImportLayers))
At this point the base parameters for the landscape have been set. The ALandscape* Landscape = SpawnActor<ALandscape>() could be called at either point since it just spawns an object that doesn't actually have any information about it. This also applies for setting landscape's fields. Fields that need to be set are presented bellow:
Landscape->bCanHaveLayersContent
Landscape->LandscapeMaterial
Landscape->SetActorTransform
Landscape->StaticLightingLOD
ULandscapeInfo* LandscapeInfo = Landscape->GetLandscapeInfo()
LandscapeInfo->UpdateLayerInfoMap(Landscape)
Landscape->RegisterAllComponents()
Landscape->GetClass()
Landscape->PostEditChangeProperty(MaterialPropertyChangedEvent)
Landscape->PostEditChange()
The actual part where landscape is given form, happens with the invocation of Landscape->Import(...).
A detailed explanation about what the script could look like can be found here with more information on landscape (check the answer for the cpp code).
|
71,425,715 | 71,428,216 | Iterating QList<double> changes list values | I'm trying to convert a double with 4 decimals in a quint32, but when I iterate the list, the values are different.
I added a breakpoint at the first cycle and these are the variables, how can I make "i" to be 112778?
EDIT:
This is the code:
QList<double> list;
list << 11.2778;
list << 11.3467;
list << 11.3926;
list << 11.4531;
list << 11.4451;
list << 11.4625;
list << 11.4579;
list << 11.4375;
list << 11.4167;
list << 11.6285;
list << 11.5625;
list << 11.4427;
list << 11.4278;
list << 11.4063;
list << 11.2500;
for(double value : list)
{
double v = value * 10000;
quint32 i = v;
qDebug() << v << i;
}
I was expecting the numbers to be converted to quint32 without floating point, but that's not the result
| This is just a question of floating point precision in C++, and there are a lot of existing SO questions on the topic. The problem I think arises from the fact that: 11.2778 * 10000 might not get calculated to be exactly 112778. It might think it is 112777.999999999, or whatever. Converting to an int doesn't round to the nearest integer, it just truncates everything after the decimal point. So that's how you can end up with 112777. To fix this, you can simply force it to round:
for(double value : list)
{
double v = value * 10000;
quint32 i = qRound(v); // Round the double to get the best int
qDebug() << value << v << i;
}
|
71,426,048 | 71,426,263 | C++ Linked List Reverse Function Triggers Infinite Loop | I've created a linked list from an array. It works fine. But when I try to reverse the list using the reverseList() function, it starts an infinite loop. When I try to display the list, it displays the last two members repeatedly.
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
node *reverseList(node *h)
{
node *p, *q, *r;
p = h->next;
q = h;
r = NULL;
while (p)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
h = q;
return h;
}
int main()
{
struct node *n, *h, *t;
int arr[] = {2, 5, 9, 6, 8};
n = new node;
t = n;
h = n;
n->data = arr[0];
for (int i = 1; i < 5; i++)
{
n = new node;
n->data = arr[i];
t->next = n;
t = n;
}
n->next = NULL;
node *p = reverseList(h);
while (p)
{
cout << p->data << " ";
p = p->next;
}
return 0;
}
| Within the function reverseList
node *reverseList(node *h)
{
node *p, *q, *r;
p = h->next;
q = h;
r = NULL;
while (p)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
h = q;
return h;
}
initially q->next for the first node pointed to by the pointer h is not set to nullptr. It stays pointing to the second node in the original list.
That is after this statement
q = h;
before the while loop the pointer q->next was not set to nullptr.
Also the function can invoke undefined behavior if the passed argument is a null pointer.
The function can be defined the following way
node * reverseList( node *h )
{
node *q = nullptr;
for ( node *p = h; h != nullptr; p = h )
{
h = h->next;
p->next = q;
q = p;
}
h = q;
return h;
}
Or it would be better to use more meaningful names like for example
node * reverseList( node *head )
{
node *new_head = nullptr;
for ( node *current = head; head != nullptr; current = head )
{
head = head->next;
current->next = new_head;
new_head = current;
}
return new_head;
}
Pay attention to that you need to free all the allocated memory for the list when it is not required any more.
|
71,426,427 | 71,426,987 | How to set build type to 32 bit in Github actions for CMake C++ project | I need to have automated testing on github for a CMake C++ project. For this I want to use a 32 bit Windows machine (some of our packages are only in 32 bit), but I couldn't find an easy method to do this. I have tried to set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER in the environment to the x86 compiler, but that did not do anything.
Is there a keyword that I can add either to github actions environment, or to the CMake so that my project does compile to a 32 bit program on github?
| As stated in the comments from vre the cmake -A Win32 tag works on github! If you also want the host to be x86 run the following command: cmake -S SOURCEFOLDER -B BUILDFOLDER -T host=x86 -A Win32
|
71,427,285 | 71,462,327 | How to extend dims of blob in openvino | Hello from a beginner of OpenVINO. In the official tutorial, the optimal way of taking input for a cascade of networks is
auto output = infer_request1.GetBlob(output_name);
infer_request2.SetBlob(input_name, output);
However, in my case, the output's layout is CHW but the next network's input has an NCHW layout. So how could I reshape, or extend the dims of output effectively? Or is there any better way to feed blob to the next model in my case?
I tried input_info->setLayout(Layout::CHW);, which is taken from openvino's hello_classification example, but it didn't do the job (I think I misunderstood this function).
| Use InferenceEngine::CNNNetwork::reshape to set new input shapes for your first model that does not have batch dimension.
|
71,427,427 | 71,431,896 | Is there a way to get a "total sum" which in my program would be the total amount of calories | This is my code and I am wondering how I can get the sum of the calories of the meals the user inputted and output it to the user at the end.
Below you can see that where I commented in all caps for calCount. That doesn't work for my program and I believe I am wrong and that won't output the sum.
Should I do the sum of calories before main() or in main()?
#include <iostream>
#include <string>
using namespace std;
class CaloriesFoodOne {
private:
int breakfast_Calories;
int lunch_Calories;
int dinner_Calories;
int snack_Calories;
string pickFood;
string dinner;
string lunch;
string breakfast;
string snack;
public:
void calories_FortheDay(void) {
std::cout<< "What food are you entering? (Breakfast, Lunch, Dinner, or Snack)"
<< std::endl;
std::cin >> pickFood;
if (pickFood == "Breakfast") {
std::cout << "What did you eat? " << endl;
std::cin >> breakfast;
std::cout << "Do you know how many calories were in " + breakfast + " ?" << std::endl;
std::cin >> breakfast_Calories;
}
else if (pickFood == "Lunch") {
std::cout << "What did you eat? " << endl;
std::cin >> lunch;
std::cout << "Do you know how many calories were in " + lunch + " ?"
<< std::endl;
std::cin >> lunch_Calories;
}
else if (pickFood == "Dinner") {
std::cout << "What did you eat? " << endl;
std::cin >> dinner;
std::cout << "Do you know how many calories were in " + dinner + " ?"
<< std::endl;
std::cin >> dinner_Calories;
}
else if (pickFood == "Snack") {
std::cout << "What did you eat? " << endl;
std::cin >> snack;
std::cout << "Do you know how many calories were in " + snack + " ?"
<< std::endl;
std::cin >> snack_Calories;
}
}
void display_CalforFood1(void);
};
void CaloriesFoodOne::display_CalforFood1() {
int calCount = breakfast_Calories + lunch_Calories + dinner_Calories + snack_Calories;
std::cout << calCount; //THIS IS WHERE I AM NOT SURE WHAT TO DO TO GET A TOTAL SUM FOR CALORIES
}
int main() {
string eatA;
int number_ofTimesAte;
while(true){
std::cout << "Have you ate today? " << std::endl;
std::cin >> eatA;
if (eatA == "yes") {
std::cout << "How many times have you ate today? " << std::endl;
std::cin >> number_ofTimesAte;
if (number_ofTimesAte == 1) {
while (number_ofTimesAte == 1)
{
CaloriesFoodOne onetime;
onetime.calories_FortheDay();
onetime.display_CalforFood1();
}
} else if (number_ofTimesAte == 2) {
{
CaloriesFoodOne twotime;
for (int i = 0; i < 2; i++) {
twotime.calories_FortheDay();
twotime.display_CalforFood1();
}
}
} else if (number_ofTimesAte == 3) {
while (number_ofTimesAte == 3)
{
CaloriesFoodOne threetime;
threetime.calories_FortheDay();
fourtime.display_CalforFood1();
}
}
} else if (eatA == "no") {
std::cout << "Please come back to this program when you have ate!"
<< std::endl;
break;
} else {
std::cout << "Please enter either 'Yes' or 'No'" << std::endl;
}
}
return 0;
}
| First, you're asking us to read your code and figure out what you're doing wrong. It would really be nice if you took at least half as much time making your question readable. Please take the time to ensure your code is formatted properly so it is easier for us to read.
Next, your main() is crazy.
int main() {
string eatA;
int number_ofTimesAte;
while(true){
std::cout << "Have you ate today? " << std::endl;
std::cin >> eatA;
if (eatA == "yes") {
std::cout << "How many times have you ate today? " << std::endl;
std::cin >> number_ofTimesAte;
if (number_ofTimesAte == 1) {
while (number_ofTimesAte == 1)
{
CaloriesFoodOne onetime;
onetime.calories_FortheDay();
onetime.display_CalforFood1();
}
}
else if (number_ofTimesAte == 2) {
{
CaloriesFoodOne twotime;
for (int i = 0; i < 2; i++) {
twotime.calories_FortheDay();
twotime.display_CalforFood1();
}
}
}
else if (number_ofTimesAte == 3) {
while (number_ofTimesAte == 3)
{
CaloriesFoodOne threetime;
threetime.calories_FortheDay();
fourtime.display_CalforFood1();
}
}
}
else if (eatA == "no") {
std::cout << "Please come back to this program when you have ate!"
<< std::endl;
break;
} else {
std::cout << "Please enter either 'Yes' or 'No'" << std::endl;
}
}
return 0;
}
This is just crazy, with several bugs and a number of basic design issues. First, don't ask for the input inside your class. Grab it from main. But aside from that.
Each of your while loops will run forever because none of them decrement the counter. Let's pick just one:
while (number_ofTimesAte == 3)
{
CaloriesFoodOne threetime;
threetime.calories_FortheDay();
fourtime.display_CalforFood1();
}
You've done nothing to decrement number_ofTimesAte. Which means this for-loop will run forever.
Also, each time you create a new CaloriesFoodOne, which then goes away. So you get the calories for one meal and immediately drop it again. You don't collect all the data for the day.
But you can make this so much simpler:
std::cout << "How many times have you eaten today?" << std::endl;
stc::cin >> number_ofTimesAte;
CaloriesFoodOne calCounter;
for (int index = 0; index < number_ofTimesAte; ++index) {
calCounter.calores_ForTheDay();
}
calCounter.display_CalForFood1();
You'll notice that I do a for-loop over the number of times they said they ate. I use the same copy of calCounter so it stores up all the values as you go. And then outside the loop, I call the counter.
I don't know if this fixes all your problems. The code inside calories_ForTheDay() is also ugly. But this might get you closer.
Please, if you ask more questions, take the time to make your code easy for us to read.
|
71,427,622 | 71,428,254 | Binding a non-const lvalue reference to a deduced non-type template parameter | Consider a function template f that binds a non-const lvalue reference to a deduced non-type template parameter
template <auto N>
void f()
{
auto & n = N;
}
This works when f is instantiated over class types
struct S {};
f<S{}>(); // ok
But doesn't work when instantiated over non class types (as I expected)
f<42>(); // error non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
The same error is emitted if an lvalue argument is used to instantiate f as well
constexpr int i = 42;
f<i>(); // also error
Here's a demo to play with.
This looks like non-type template parameters of class type are lvalues, which seems odd. Where does the standard make a distinction between these kinds of instantiations, and why is there a difference if the argument to the template is of class type?
| The reason for the distinction is because class non-type template parameters weren't always there. Originally, value template parameters could only be pointers, integers, or a few other things. Such parameters were simple and the value was just a single number known at compile-time. As such, making them rvalues (remember: prvalue is C++11) was OK.
Once NTTPs could be more complex object types, you have to start engaging with certain questions. Should you be able to do this:
template<std::array<int, 5> arr>
void func()
{
for(int i: arr)
//stuff
}
The obvious answer is "of course you should." But that would require that you can get a reference to arr itself. That's how range-based for is defined, after all.
Now that can still work. After all, range-based for uses auto&& to store its reference, so it can reference a prvalue. But that has consequences.
Namely, if you create a reference to a prvalue, that causes the materialization of a temporary. A new temporary object distinct from all other objects.
This means that if you use a class NTTP in multiple places, you will get different objects with different addresses and different addresses for their subobjects. And this is something you can detect, since you can get the addresses of their subobjects.
Forcing compile-time code to create temporaries every time you use the name is bad for performance. So two different uses of such a parameter need to result in talking about the same object.
Therefore, class NTTPs need to be lvalues; each use of the name within a template is referring to the same object. But you can't go back and make all existing NTTPs lvalues too; that would break existing code.
So that's where we are.
As for where this is defined, it is in [temp.param]/8:
An id-expression naming a non-type template-parameter of class type T denotes a static storage duration object of type const T, known as a template parameter object, whose value is that of the corresponding template argument after it has been converted to the type of the template-parameter. All such template parameters in the program of the same type with the same value denote the same template parameter object.
|
71,428,013 | 71,429,200 | C++ Iterator ( Next ) | I have this code that i am using to get an idea of how C++ Next iterator work on key value map that has a struct. I can not think of how:
iter->val happens to be 1 when struct value is 0 for key "test"
next->val happens to be 0
Can someone help me understand this please.
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <unordered_map>
#include <set>
#include<unordered_set>
using namespace std;
struct test {
int val;
unordered_set<string> st;
};
int main()
{
list <test> tst;
unordered_map < string , list<test>::iterator > m;
m["test"] = tst.insert(tst.begin() , {0 , {"test"}});
auto iter = m["test"] , next = iter++;
cout << iter->val << endl; // prints 1 . Not sure how
cout << next->val << endl; // prints 0 not sure how also
}
| You first create a struct test with val=0 and st={"test"}. That gets inserted into the list tst, so that has one entry now. The return value is an iterator pointing at the new element and is put into m["test"]. So your unordered map has one entry "test" that is an iterator of tst. And now the fun begins...
auto iter = m["test"];
iter becomes a reference to the iterator pointing at the first element of tst.
auto next = iter++;
Now two things happen: First next gets a copy of iter and now also points at the first element of tst. Secondly iter gets incremented (post increment) to point at the next item in the list. Since there are no more it now points to tst::end().
Now lets answer your question of what happens on the output:
cout << iter->val << endl; // prints 1 . Not sure how
This is undefined behavior. You are not allowed to operator->() end(). It points to somewhere in memory and randomly that contains 0 so you get 0. Lucky your cat didn't get pregnant.
cout << next->val << endl; // prints 0 not sure how also
Since in practice a little UB does no harm your program continues and accesses next. Since next points to the first element of tst that gets accessed. The first element of tst is {.val = 0; .st={"test"}} so next->val outputs 0.
Are you sure you want a unordered_map of iterators instead of an unordered_map of list?
|
71,428,645 | 71,428,819 | Spaceship (<=>) operator with iterator implementation results in error: '+' cannot add two pointers | This is all I have, and of course, the rest of the typical class with constructor, destructor, etc. However, the C++ compiler in Visual Studio 2022 gives me this error:
CS2110 '+' cannot add two pointers.
This makes sense, given my private declaration within this class. However, I am not sure, how this can be resolve properly? In my other implementations, where the actual size isn't a pointer, but a size of type size_t, this has worked perfectly fine.
Private variables:
T* m_ptr;
size_t* m_counter;
Iteration code:
// Implemented C++ 11 range-based support.
iterator begin() noexcept { return m_ptr; }
iterator end() noexcept { return (m_ptr + m_counter); }
const_iterator begin() const noexcept { return const_iterator(m_ptr); }
const_iterator end() const noexcept { return const_iterator(m_ptr + m_counter); }
The code for the spaceship (<=>) operator:
friend auto operator<=>(const SharedPtr& lhs, const SharedPtr& rhs)
{
auto left = lhs.begin();
auto right = rhs.begin();
for (; left != lhs.end() && right != rhs.end(); ++left, ++right) {
if (*left < *right)
return std::strong_ordering::less;
if (*left > *right)
return std::strong_ordering::greater;
}
if (left == lhs.end())
if (right == rhs.end())
return std::strong_ordering::equivalent;
else
return std::strong_ordering::less;
else
return std::strong_ordering::greater;
}
|
CS2110 '+' cannot add two pointers.
T* m_ptr;
size_t* m_counter;
iterator end() noexcept { return (m_ptr + m_counter); }
// ^
const_iterator end() const noexcept { return const_iterator(m_ptr + m_counter); }
// ^
The bug is here. You are attempting to add two pointers. Pointers cannot be added together; this is a meaningless operation and the program is ill-formed.
operator<=> isn't relevant in regard to this bug in other way besides it calls the broken end function.
However, I am not sure, how this can be resolve properly
That depends on what you're trying to do. It depends on what m_ptr and m_counter point to respectively.
If m_ptr points to element of an array, and m_counter points to an integer that denotes the number of successive elements in the array, and your goal is to get a pointer past the number of elements, then you can indirect through the m_counter pointer to get the size, and add that to m_ptr:
iterator end() noexcept { return m_ptr + *m_counter; }
But that raises a new question: Why is m_counter a pointer? Why isn't the size of the array stored by value?
m_counter it is the reference counter.
If m_counter isn't the number of successive elements of the element pointed by m_ptr, then the addition above doesn't make sense and will likely lead to undefined behaviour. In such case, don't do this.
|
71,428,682 | 71,428,856 | Cuda float precision | Will the float loses its precision when a number is small enough (GPU Kernel, RTX 2060)?
Say,
#include <stdio.h>
__global__ void calc()
{
float m1 = 0.1490116119;
float m2 = -0.000000007450580;
float res = m1 + m2;
printf("M1: %.15f M2: %.15f Res: %.15f\n", m1, m2, res);
}
int main()
{
calc<<<1,1>>>();
cudaDeviceSynchronize();
return 0;
}
Results as:
M1: 0.149011611938477 M2: -0.000000007450580 Res: 0.149011611938477
M2 does not matter in this case, which confuses me.
I know that float number may not be as accurate as expected, but I wonder if there is something wrong that float in the order of 1e-9 is ignored.
Assume that if I want to add a very small number to a given variable (called M) gradually, this benchmark would imply that M will not change any more finally?
Thank you very much!
| Your observations are correct and they don't have anything to do with CUDA:
$ cat t1981.cu
#include <stdio.h>
#ifndef DONT_USE_CUDA
__global__ void calc()
#else
int main()
#endif
{
float m1 = 0.1490116119;
float m2 = -0.000000007450580;
float res = m1 + m2;
printf("M1: %.15f M2: %.15f Res: %.15f\n", m1, m2, res);
}
#ifndef DONT_USE_CUDA
int main()
{
calc<<<1,1>>>();
cudaDeviceSynchronize();
return 0;
}
#endif
$ nvcc -o t1981 t1981.cu
$ ./t1981
M1: 0.149011611938477 M2: -0.000000007450580 Res: 0.149011611938477
$ cp t1981.cu t1981.cpp
$ g++ -DDONT_USE_CUDA t1981.cpp -o t1981
$ ./t1981
M1: 0.149011611938477 M2: -0.000000007450580 Res: 0.149011611938477
$
M2 does not matter in this case, which confuses me.
A float quantity corresponds to IEEE 754 32-bit floating point. This number representation has ~23 bits for mantissa representation. 23 bits corresponds to roughly 6 or 7 decimal digits. The way I like to think about this is that there can be about 6 or 7 decimal digits between the most significant digit you want to represent and the least significant digit you want to represent (inclusive).
I know that float number may not be as accurate as expected, but I wonder if there is something wrong that float in the order of 1e-9 is ignored.
It's not that categorically, a number of the order of 1e-9 is ignored. Instead, it's better to conclude that if there are 9 significant digits between the digits in the number(s) that you care about, float may be an insufficient representation. You can easily work with numbers that are in the range of 1e-9, it's just that you may not have good results combining those with numbers in the range of 1e-1, which is what you are trying to do.
Assume that if I want to add a very small number to a given variable (called M) gradually, this benchmark would imply that M will not change any more finally?
Yes, if you want to handle calculations like this, one possible solution would be to switch from float to double. double can handle typically 12-15 or more decimal digits of significance.
There are also other alternatives, such as kahan summations, to deal with problems like this. You could also sort a set of numbers to be added. In a serial fashion, or blockwise in CUDA, adding from smallest to largest may give better results than an unsorted or naive summation.
Also note that a typical parallel reduction effectively performs the pairwise summation approach discussed here and so may perform better than a naive serial running-sum approach.
|
71,429,411 | 71,430,261 | Check if matrix is Lower or Upper Triangular Matrix | Is there an API in Eigen library to check if a matrix is a lower or upper triangular matrix?. Obviously, we can write a function to check this. But I would like to know if Eigen has a way of checking this. When I looked in the documentation, I read about triangular views, but no calls to check if it is lower or upper.
| According to documentation: https://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#title51
matrix.isUpperTriangular();
matrix.isLowerTriangular();
|
71,429,502 | 71,429,648 | Parallel OpenMP loop with continue as a break alternative | I'm referring to this question: Parallel OpenMP loop with break statement
The code suggested here:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(flag) continue;
if(element[i] ...)
{
...
flag=true;
}
}
What are the advantages of using continue? Is it faster than doing the following:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(!flag)
{
if(element[i] ...)
{
...
flag=true;
}
}
}
| After compilation, they are identical at least for the trivial case.
Without continue
With Continue
If you compare the resulting assembly there is no difference between the two. I have taken the liberty of adding a junk condition of halting before 2000.
|
71,429,627 | 71,430,285 | Trying to change a value in a vector bool | I'm reading Stroustrup PPP and while doing an exercise, I found this error.
Why I can't change the value of a vector bool?
#include "std_lib_facilities.h"
int main()
{
vector<bool> vecc(2, true);
vecc[1] = true; // I can't do this, returns error.
return 0;
}
The error:
error: cannot bind non-const lvalue reference of type 'bool&' to an rvalue of type 'bool' return std::vector<T>::operator[](i);
Second, when I try with the int type, the problem does not occur.
#include "std_lib_facilities.h"
int main(){
vector<int> vecc = {true, true};
for(bool x : vecc) {cout<<x<<"\n";}
vecc[1] = false; //ok
for(bool x : vecc){cout<<x<<"\n";}
return 0;
}
Output:
1
1
1
0
Edit:
Probably this is because I was using #include "std_lib_facilities.h"
std_lib_facilities.h
| std_lib_facilities.h defines the following helper template to add a bit of error checking helpful to folks beginning their programming careers:
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
/* #ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n, v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
*/
using std::vector<T>::vector; // inheriting constructor
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
T& operator[](unsigned int i) and its const variant return a reference to T and in this case T is bool. To get the element it calls through to std::vector's operator[] to do the grunt work.
Unfortunately std::vector<bool> is not a proper library container. Because it packs bits rather than storing bools, it can't return a reference to a bool from the element access methods. It doesn't have any bools to reference. Instead it returns a groovy reference class that conceals the bit packing from sight and usually makes life a bit easier. Under most circumstances the element access methods will behave exactly the same way as a regular vector.
But not this time. It's not returning a reference and it's not returning a reference to a bool so the simple pass-through fails to compile.
Common work arounds are to use a std::vector containing some small integer type or an enum or use a std::deque<bool> which can be used largely the same way and doesn't have a bit-backing specialization. If the size is known at compile time, consider using a std::bitset.
|
71,429,692 | 71,430,060 | Reading values of static const data members without definitions: what governs these rules? | Consider the following program:
struct Empty { };
struct NonEmpty { int x{}; };
struct S {
static const Empty e; // declaration
static const NonEmpty n; // declaration
static const int a; // declaration
static const int b{}; // declaration and initializer
};
Empty ge; // declaration & definition
NonEmpty gn; // declaration & definition
int ga; // declaration & definition
int main() {
auto le1 = S::e; // OK
auto ln1 = S::n; // #1 error: undefined reference
auto la1 = S::a; // #2 error: undefined reference
auto lb1 = S::b; // OK
auto le2 = ::ge; // OK
auto ln2 = ::gn; // OK
auto la2 = ::ga; // OK
}
None of the static data members of S are defined, but of the two integral type static data members S::a and S::b the latter specifies a brace-or-equal-initializer at its in-class declaration, as it may, as per [class.static.data]/4. S::e and S::n may not specify brace-or-equal-initializer:s at their in-class declaration.
All these static data members of S have, like their global namespace-scope counterpart variables ge, gn and ga, static storage duration. As per [basic.start.static]/2 they all thus undergo zero initialization as part of static initialization.
The program above is, however, rejected by GCC and Clang (various language versions, various compiler versions) at #1 and #2, when trying to copy-initialize local variables from the S::n and S::a static data members.
I'm assuming the compilers are correct, but I cannot find the normative section which supports this rejection, or maybe rather, why the program accept the case with the empty class static data member S::e. That the case of S::b is accepted "makes sense", but again I can't sort this out normatively (odr-use, conv.lval, basic.life, ... ?).
Question
What normative text explains why the program above rejects reading the value of S::e and S::a as ill-formed, whilst it accepts read the values of S::e (empty) and S::b (initialized)? Say, in N4868.
| [basic.def.odr]/4 governs when a variable is odr-used (requiring a definition).
S::e and S::n are not eligible for exception (4.1) because they have non-reference type. They are not eligible for exception (4.2) because they are not usable in constant expressions because they fail to be potentially-constant, and they do not meet the "non-volatile-qualified non-class type to which the lvalue-to-rvalue conversion is applied" criterion either. They are not eligible for exception (4.3) because they are not discarded either; they are bound to the reference parameters of the copy constructors.
This implies that S::e and S::n are odr-used. You only got a diagnostic for S::n, not S::e. This does not imply that your use of S::e was acceptable. The implementation is not required to diagnose a violation of the ODR. The compilers you have used have probably elided the call to the (trivial) copy constructor of Empty, and generated object files where the linker has no way to know that S::e was supposed to have been defined.
S::b falls under exception (4.2) because it is usable in constant expressions, and the lvalue-to-rvalue conversion is immediately applied (i.e., the expression referring to S::b is "converted" into the value of S::b immediately). It is not odr-used, and does not need a definition.
S::a does not fall under exception (4.2) because its initializing declaration is not reachable, which has made it not usable in constant expressions. It is odr-used, and needs a definition.
|
71,430,480 | 71,430,925 | How does std::map know when two keys are equal when using a custom comparator? | struct StrCmp {
bool operator()(char const *a, char const *b) const
{
return std::strcmp(a, b) < 0;
}
};
// StrCmp specified in map declaration
map<const char *, int, StrCmp> strMap;
char p[] = "Test";
strMap[p] = 5;
cout << strMap["Test"];
In the code above the output is 5... How does the map know that the strings are equal ? The comparator only gives information that the strcmp value is greater.
| Per the std::map documentation on cppreference.com:
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.
Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent (not unique) if neither compares less than the other: !comp(a, b) && !comp(b, a).
|
71,430,924 | 71,431,048 | Is it well defined to access a variable from an outer scope before it is redefined? | This code compiles with no warnings in gcc-11:
int i{ 2 };
{
std::cout << i; //prints 2
int i{ 3 };
std::cout << i; //prints 3
}
Is this well defined or it just happened to work?
|
Is this well defined or it just happened to work?
It is well-defined. The scope of a variable declared inside a {...} block starts at the point of declaration and ends at the closing brace. From this C++17 Draft Standard:
6.3.3 Block scope [basic.scope.block]
1 A name declared in a block (9.3) is local to that
block; it has block scope. Its potential scope begins at its point of
declaration (6.3.2) and ends at the end of its block. A variable
declared at block scope is a local variable.
This code compiles with no warnings in gcc-11
That surprises me. The clang-cl compiler (in Visual Studio 2019, 'borrowing' the /Wall switch from MSVC) gives this:
warning : declaration shadows a local variable [-Wshadow]
Using both -Wall and -Wpedantic in GCC 11.2 doesn't generate this warning; however, explicitly adding -Wshadow does give it. Not sure what "general" -Wxxx switch GCC needs to make it appear.
|
71,432,070 | 71,432,091 | In c++ can you separate the function called based on the template? | I have a function in C++ that works, in theory. What I mean by this, is if the function was converted to a language like Python, it would work just fine because it is not pre-compiled. However, in a language like C++, it throws errors.
This is the function:
template <typename T>
T JSONValue::get(){
if(detect_number::detect<T> == true){
if(type == JSONValueType::Number)
return (T)number.value();
}
else if(detect_string::detect<T> == true){
if(type == JSONValueType::String){return string.value();}
return deparse(*this);
}
else if(detect_chararray::detect<T> == true){
if(type == JSONValueType::String){return string.value().c_str();}
std::string dep = deparse(*this);
return dep.c_str();
}
else if(detect_boolean::detect<T> == true){
if(!(type == JSONValueType::Boolean))
return false;
return boolean.value();
}
else if(is_specialization<T, std::vector>::value){
if(type != JSONValueType::Array){
std::cerr<<"must be an array to do this"<<std::endl;
return T{};
}
T output;
for(int i = 0; i < size(); i++){
output.push_back(array.value().at(i).get<std::decay<decltype(*output.begin())>::type>());
}
return output;
}
return T(0);
}
In the if statements, it detects the type, T which is passed. If it is a number, do this, all through if it is a vector then do this.
The problem is, if a vector is put in as the template parameter, it throws an error because a number cannot be casted to a vector, and so on.
Is there a way to either get the compiler to ignore the error, or fix it so that the compiler does not have to ignore it and it will run?
I remember seeing something a while back that if the type is something in the typename, then run this function, otherwise run this other function.
| In C++17 and later, you can use if constexpr, eg:
if constexpr (detect_number::detect<T>){
// T is a numeric type, do numerical things here...
}
else if constexpr (detect_string::detect<T>){
// T is a string type, do stringy things here...
}
...
if statements are evaluated at runtime, so the entire function has to be syntaxically correct at compile-time, even though only parts of it will actually be used.
But, if constexpr statements are evaluated at compile-time instead. As such, any unused code blocks will be eliminated by the compiler and not evaluated at all. That will allow you use T in different ways in different if constexpr blocks. The compiler will treat your code as if you had written it more like this:
// only when T is a number
template <typename T>
T JSONValue::get(){
if(type == JSONValueType::Number)
return (T)number.value();
}
return T(0);
}
// only when T is a string
template <typename T>
T JSONValue::get(){
if(type == JSONValueType::String){return string.value();}
return deparse(*this);
}
...
Prior to C++17, you would have to use SFINAE or template specialization to accomplish the same thing, eg:
// SFINAE
template <typename T,
typename std::enable_if<detect_number::detect<T>, bool>::type = true
>
T JSONValue::get(){
if(type == JSONValueType::Number)
return (T)number.value();
return T(0);
}
template <typename T,
typename std::enable_if<detect_string::detect<T>, bool>::type = true
>
T JSONValue::get(){
if(type == JSONValueType::String){return string.value();}
return deparse(*this);
}
...
// specialization
template <typename T>
T JSONValue::get(){
return T{};
}
template<>
int JSONValue::get<int>(){
if(type == JSONValueType::Number)
return (T)number.value();
return T(0);
}
template<>
std::string JSONValue::get<std::string>(){
if(type == JSONValueType::String){return string.value();}
return deparse(*this);
}
...
|
71,432,188 | 71,432,463 | How to incrementially concatenate ranges? | Background
What I am trying to do is to implement some classes that represents geometry. Any instance of a geometry class has a method called vertices() that returns a non-owning view of vertices. A geometry class can be expressed in terms of multiple other geometry classes, so the geometry class' vertices()-method would ideally just do something like this (pseudocode):
vertices()
{
return join(part1.vertices(), part2.vertices(), part3.vertices());
}
subject to not copying nor moving vertices.
In C++20 this is something that I believe can be done with ranges & views but I can't figure out how to do it.
My attempt
#include <iostream>
#include <ranges>
#include <vector>
struct Vertex { float x, y, z; };
struct GeometryA {
auto vertices() {
return std::ranges::ref_view(v);
}
std::vector<Vertex> v {{0.0f, 0.0f, 1.0f}};
};
struct GeometryB {
auto vertices() {
return std::ranges::ref_view(v);
}
std::vector<Vertex> v {{0.0f, 1.0f, 0.0f}};
};
struct GeometryC {
auto vertices() {
// OK: All elements of vector are of same type
return std::vector{ a.vertices(), b.vertices(), std::ranges::ref_view(v)} | std::views::join;
}
GeometryA a;
GeometryB b;
std::vector<Vertex> v {{0.0f, 1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}};
};
struct GeometryD {
auto vertices() {
// Compilation fails: Elements of vector have different types
return std::vector{ c.vertices(), std::ranges::ref_view(v)} | std::views::join;
}
GeometryC c;
std::vector<Vertex> v {{1.0f, 0.0f, 1.0f}};
};
int main() {
GeometryD d;
for(Vertex const& vertex : d.vertices()) {
// Should print {0,0,1} {0,1,0} {0,1,1} {1,0,0} {1,0,1}
std::cout << "{" << vertex.x << "," << vertex.y << "," << vertex.z << "} ";
}
return 0;
}
Compilation fails in GeometryD::vertices since I am trying to deduce the template parameter T of the outmost vector from the elements at initialization (c.vertices() and std::ranges::ref_view(v)) but these do not have the same type hence T can't be deduced.
I am at a loss on how to approach this problem.
Question
Is it possible to use the standard ranges library to incrementally concatenate ranges?
I suppose I could gather all vertex-data directly or indirectly owned by a geometry class by using some recursive template-trickery and then just use std::views::join once, but before I get my hands dirty with that I'd like to get some input on my current attempt.
| You can do this using Eric Niebler's Range-v3 library.
Just concat the different range views with ranges::views::concat. E.g., for GeometryC:
return ranges::views::concat(a.vertices(), b.vertices(), v);
[Demo]
Much of the Range-v3's stuff is being gradually adopted by the standard Ranges library, although it seems this feature hasn't made it yet.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.