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
72,220,547
72,221,479
C++ Read txt and put each line into Dynamic Array
I am trying to read input.txt file, and trying to put each line into the array as string (later on I will use each element of array in initializing obj that's why I am putting each line into the array). string* ptr = new string; // Read Mode for Input fstream input; input.open("input.txt", ios::in)...
Don't use arrays; use std::vector. The std::vector behaves like an array and uses Dynamic Memory: std::string s; std::vector<std::string> database; while (std::getline(input, s)) { database.push_back(s); } Keep it simple. :-)
72,220,614
72,220,982
Sort vector of custom template class
Suppose I have a template class ComplexNumber that looks like this: template<typename T> class ComplexNumber { public: ComplexNumber() : A(), B() {} ComplexNumber(const T& r, const T& i) : A(r), B(i) {} ~ComplexNumber(){} void setA(T A1); void SetB(T B1); T getA() const {return A;}; T getB(...
In order to work with std::sort(), your class needs at least operator< defined: bool operator< (const ComplexNumber<T>& other) const { return A < other.A || (A == other.A && B < other.B); } It's also good practice to define operator==, but std::sort() will work with operator< alone. When I make the above addition ...
72,220,745
72,220,913
is there a way of hosting a mysql database using only Qt?
I am trying to make a program that connect many computers into a local MySQL database hosted by a central computer, but the way I found to host a MySQL database is using an External program as Xampp or WampServer. I am Wodering if I can host a MySQL database using only Qt's classes like QTcpServer without the needing o...
No. MySQL needs a MySQL Server process to manage connections, permissions, SQL parsing, storage engines, caching, etc. You can't use a MySQL database without a MySQL Server. You might like to explore using SQLite, which is a free embedded database that can be used without requiring a separate daemon process. SQLite is ...
72,220,948
72,243,167
Find place that causes segmentation fault without IDE
I'm studying one project in C++. It's quite big, build is created with cmake. After installing all dependencies and libs it's the build is done fine. But when I run it, I get Segmentation fault. Here is the thing: There is no IDE, running this project with cmake in VS Code. I wonder if it's possible to find this place ...
I've found a solution for my case and here's what I've done: Installed these VS Code Extensions - CodeLLDB Added Configuration File: Run/'Add Configuration...' The config file was at <root_dit>/.vscode/launch.json and looked like this: { "version": "0.2.0", "configurations": [ { "type": "lldb", "r...
72,221,687
72,222,374
The configuration option popup for debugging a c++ project in Visual Studio Code does not appear
so I want to debug my .cpp program file but when I click on the Run and Debug button and proceed to select my debugging environment (C++ (GDB/LLDB)), the popup to select the configuration option does not even appear at all and the debugging just doesn't start. This is before I click the environment popup: and this is ...
Are you sure you installed the C/C++ Studio Code extension? If you don't get the popup, try writing the json files manually. Create a .vscode folder in your working directory. In there create a file launch.json in which you declare how you run the debugger { "configurations": [ { "name": "Debug", "typ...
72,221,721
72,222,177
Handling custom vector classes
I have come across many occasions where I want to have an item which is selected inside a vector, for this I have written the template class: // a vector wrapper which allows a specific item to be currently selected template<typename T> class VectorSelectable { public: VectorSelectable() {}; VectorSelectable(s...
You mainly need to put the std::vector<std::unique_ptr<T>> in VectorSelectable and hide all the pointer stuff from the interface. With a few small changes to your class, it could look like this: #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include <vector> template <...
72,222,054
72,222,088
Overload == operator for a boost::variant
I have a boost::variant of a bunch of types (int, double, custom class etc) and need to implement an overload for the == operator. How do I go about this? My error is wrt the == operator, complaining that "too few operators for this operation". What am I missing here? I do not see any errors for the << operator. It com...
Your << operator takes two arguments, the stream and the variant. Your operator== takes one argument. If you're defining a free function operator==, the signature should be bool operator==(const someVariant& lhs, const someVariant& rhs).
72,222,245
72,226,903
Is there a more stringent version of std::stoi?
I just discovered (much to my surprise) that the following inputs do not cause std::stoi to throw an exception: 3.14 3.14helloworld Violating the principle of least surprise - since none of these are valid format integer values. Note, perhaps even more surprisingly 3.8 is converted to the value 3. Is there a more stri...
The answer to your question: Is there a more stringent version of std::stoi? is: No, not in the standard library. std::stoi, as described here behaves like explained in CPP reference: Discards any whitespace characters (as identified by calling std::isspace) until the first non-whitespace character is found, then ta...
72,222,249
72,222,309
How can I get this code to make LEDs linked to my arduino flash at either the value the dial outputs, or no more than a determined value?
Before I get started I want to make it clear I am still a beginner in both C++ and Arduino electronics, so the answer may be painfully obvious to someone with even a week more experience than me. But to me, it is a total mystery. Thank you for any help. To begin this is the code: int potPosition; int delayTime; void s...
This delayTime == analogRead(A0); and this delayTime == 16; are comparisons, i.e. delayTime remains uninitialised and you get undefined behaviour. I bet you want to write a value there, as in delayTime = analogRead(A0); or maybe delayTime = potPosition; (same for the other ==). The latter seems more plausible to me, ...
72,222,269
72,222,433
What are the differences between a template and a function pointer for a Strategy design pattern in C++
I'm implementing a Strategy Design Pattern in c++, and I've found a couple of different options I could take. One route would be to use a template, and might look like this: namespace Strategies { struct IsEven { bool doSomething(int x) { return x % 2 == 0; } }; struct IsOdd { bool ...
The main difference is the template version uses "compile time polymorphism" meaning the selection of the strategy happens at compile time and the strategy is part of the type. Thus, the strategy a particular instance of Processor<T> uses must be known at compile time and cannot be changed dynamically after a Processor...
72,222,917
72,223,186
Private compile-time -> run-time adapter. Strange compilation error
Basically, this code fails with a very strange error: <source>:75:29: error: cannot convert 'get_view<main()::<unnamed struct>, run_time::data_view>::operator()(const main()::<unnamed struct>&) const::View::code' from type 'int (get_view<main()::<unnamed struct>, run_time::data_view>::operator()(const main()::<unnamed ...
The problem was caused by an ambiguity during function resolutions: get_view returns a deduced type by value that is a good candidate for template <typename DataT> operator()(const DataT &), thus ignoring the existing overload operator()(const data_view &). Providing an explicit cast before operator's invocation solves...
72,223,257
72,223,338
Template arguments can't be deduced for shared_ptr of class derived from templated base
I'm running into a case where I thought that the compiler would obviously be able to do template argument deduction, but apparently can't. I'd like to know why I have to give explicit template args in this case. Here's a simplified version of what's going on. I have an inheritance hierarchy where the base class is temp...
Derived is a derived class of Base<int>, but std::shared_ptr<Derived> isn't a derived class of std::shared_ptr<Base<int>>. So if you have a function of the form template <typename T> void f(const Base<T>&); and you pass a Derived value to it, the compiler will first notice that it can't match up Base<T> against Derive...
72,223,866
72,231,172
gdb <error reading variable> for any string object
Lets take this very simple program here for example: // test.cpp #include <string> #include <iostream> using namespace std; int main() { string str = "Hello"; cout << str << endl; return 0; } now I compile this code with g++ compiler: g++ -g test.cpp -o test.exe now I am trying to debug this with gdb: g...
First run your program with gdb like so: gdb test.exe Now inside the command line interface run the command: set charset UTF-8 This should temporarily fix your problem. The only inconvenience might be that you need to run this line every time you debug on your command prompt with GDB. I noticed that you are also usin...
72,224,463
72,226,010
Passing an rvalue to a function
I read a lot of information about rvalue links, I understood everything, but I met this example: template<class T, class Arg> T* make_raw_ptr(Arg &&arg) { return new T(arg); }; If you pass rvalue to the make_raw_ptr function without using the my_forward function, when using new T, there will be a copy constructor...
arg itself is an expression that represents an object referred to by arg and its value category is lvalue. It doesn't matter what the type of arg actually is. A name of a variable / function parameter itself is always an lvalue expression. static_cast<A&&>(arg) is an expression that represents the very same object as a...
72,224,660
72,224,865
Compilation error - defining a concrete implementation of templated abstract class
I have an abstract class in my header file: template <class T> class IRepository { public: virtual bool SaveData(Result<T> &r) = 0; //virtual Result<T> & GetData()const = 0; virtual ~IRepository() {} }; I inherit it in the header file itself: template <class T> class Repo1 :publ...
While implementing the template class method outside the class definition, the template class requires template arguments: template <class T> bool Repo1<T>::SaveData(Result<T> &r)
72,224,881
72,225,569
IMG_Load() with jpg returns "unsupported image format"
I'm trying to load images using SDL2-image, it works when I try to load a .png, but it fails to recognize a .jpg My imports: #include <SDL2/SDL.h> #undef main #include <SDL2/SDL_image.h> #include "logger.hpp" And my code: int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { logger::Log(logger::...
Due to operator precedence initRes & flags != flags is equivalent to initRes & (flags != flags) which will always be false. You need to use (initRes & flags) != flags instead. Jpeg support is an optional feature, you need to enable libjpeg-turbo.
72,225,300
72,225,530
Generating compile time functions string for formatting strings with libfmt
I want to create a nice table in stdout. The table has a lot of headers that are mainly compiletime strings. For example: std::cout << fmt::format("|{0:-^80}|\n", "File Information"); The above prints: |-----------------------------File Information------------------------------| I have lots of different type of fills...
The type of the format string and the return type of the function cannot be string_view since the format string is constructed dynamically, using string_view will result in a dangling pointer. In addition, fmt::format requires that the format string must be a constant expression. Instead, you need to use fmt::vformat. ...
72,225,697
72,225,838
How can I encapsulate code dealing with matrices and make it reusable?
At my course we are getting tasks that always start with filling a random matrix size nxm with random numbers. I want to create(a library?, a class?) some structure so than any time I want to generate a matrix A I would need just to input the desired size nxm. In other words, change all this code for something like #...
Below is an outline of what you can do to achieve that: Define a class e.g. MyMatrix. A class can encapsulate data and operations related to it. The class can be placed in separate files (h and cpp). A friendly guide: C++ Classes and Objects - w3schooles. This class should use e.g. a std::vector to hold the data (bett...
72,225,918
72,226,378
How to judge whether the incoming buffer is valid in C++?
In my function, a memory pointer and its size are passed as parameters: int myFun(uintptr_t* mem_ptr, int mem_size) { // Code here } Is there any way to tell if this chunk of memory is really valid? (The Operating System is CentOS Linux release 7.9.2009.)
Don't. Just don't. Even if you could find a way to check whether the pointer can safely be dereferenced, that doesn't mean it points where you think it does! It might point into your call stack, into your read-only code segment, into the static variables of some library that you're using, or any other place in memory t...
72,226,065
72,226,203
Is placement new on a const variable with automatic storage duration legal?
Is the following code legal according to the standard? #include <new> int main() { const int x = 3; new ((void *)&x) int { 15 }; } It seems to me that as long as there is no use of a reference to x it should be valid. As per the c++ standard basic.life 8: a pointer that pointed to the original object, a refer...
Is the following code legal according to the standard? The behaviour of the program is undefined: [basic.life] Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its li...
72,226,451
72,356,738
A windows app calls two C++ DLLs with same name and APIs linking to another DLL
I'm trying to let my C# app run two different version of C++ DLLs at the same time. The two DLLs with same file name and APIs are located in different directories: App -> V1/A.dll -> V1/B.dll -> V2/A.dll -> V2/B.dll From Dynamic-Link Library Search Order, I've learned how to make one A.dll call the B.dll in the sa...
Thanks for Hans Passant's comment. In my previous case, the two different version of A.dll call the same B.dll: App -> V1/A.dll |-> V1/B.dll -> V2/A.dll | V2/B.dll Manifests can be a solution to this: Create manifest file for A.dll project <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns=...
72,226,515
72,226,772
What is the equivalent to JavaScript setInterval in C++?
The following code prints the argument passed to the function foo in every 5 second interval. function foo(arg) { console.log(arg); } setInterval(() => foo(5), 5000); I found this answer: https://stackoverflow.com/a/43373364/13798537 that calls a function at periodic interval, but I couldn't figure out how to call ...
You actually can get pretty close to the javascript syntax: #include <iostream> #include <chrono> #include <thread> #include <functional> #include <memory> #include <atomic> using cancel_token_t = std::atomic_bool; template<typename Fnc> void set_interval(Fnc fun, std::chrono::steady_clock::duration interval, ...
72,226,671
72,226,870
How to initiate multiple structs
I'm fairly new to C++. Have a struct Bbox with a constructor with two arguments x and y which I have just added. Before when the constructor had no arguments I could initiate multiple instances of Bbox by doing this and num_components was the number of instances I wanted to create: Bbox list [num_components]; But how ...
And, to build on @anoop's (excellent) answer, if you use std::vector instead of a C-style array (and you should!), then you can do this: std::vector <Box> make_boxes (int num_boxes) { return std::vector <Box> (num_boxes); } And you would call it thus: auto my_boxes = make_boxes (10); But make_boxes is so trivial ...
72,226,737
72,227,434
up to 20% Numerical error or Bug in ten line code block
Rewriting a single tiny block of code of an application has yielded a considerable performance improvement. The code is 100% sequential, thus there should be no hidden perturbations to the values stored in memory. Double-checking that the results after computation are the same has shown an up-to 20% relative error in t...
Floating point number arithmetic is not distributive. That means there are cases where the following statement is true x * (a + b) != x * a + x * b; If you move the multiplication out of your loop and expect the exact same result, you assume that the distributive law is always true, which it is not. As an example I ca...
72,226,792
72,226,948
Why std::string relational operator comparison result is different for a template and a function?
In the following code, both the template and the function compare two strings and return which one is bigger. However, despite the same code (definition body), the result is different. Now, it might have something to do with taking a string vs string of characters (is it a C++ bug?) - but why is there a difference for ...
The type of the arguments (and thus of the template parameter) in the getBigger("Amber", "John") function call is const char*. Thus, the comparison in that function just compares two pointers, which is not how to properly compare (lexicographically) two C-style strings. In order to force the use of std::string as the a...
72,227,208
72,227,528
CGAL: Hole Filling .exe file is stuck
This is my terminal(result) after running the .exe file. Click the link for the terminal. It doesn't stop or gives an error. It's stuck like this for hours. I got my code from here code, but this is the data (.off) I used.
You are probably trying to fill a hole that is too large or that cannot be filled using the 3D Delaunay triangulation search space (which can happen also if you have pinched holes). In CGAL 5.5 (not yet released but available in master), we added the option do_not_use_cubic_algorithm() (doc here) to not use the cubic s...
72,227,314
72,346,923
[UE4]error LNK2005 on linking libprotobuf
Having a small issue with conflicting libraries while packaging an Unreal Engine 4.27 project. My project contains this gRPC library from google and I followed these steps to build it with CMake and after include it in my Unreal Project. In addition my project requires enabling PixelStreaming plugin. However it seems t...
What solved my issue was migrating to UE5. Using the same steps with aforementioned grpc project, in UE5 new project. Having a libprotobuf.lib in ThirdPary folder within UE5 project the packaging process worked with no LINK conflicts. Not sure why UE packaging did not complain this time but what works, works!
72,227,738
72,227,841
Cant cout item in container with std::any
This script #include <iostream> #include <unordered_map> #include <any> using namespace std; int main() { unordered_map<int, any> test; test[5] = "Hey!"; cout << test[5]; return 0; } Why does it not work? candidate function not viable: no known conversion from 'std::__ndk1::unordered_map<int, std::__n...
Just add a any_cast to test[5]. The main reason for this cast, is to tell the compiler which overloaded function of << is to be called for test[5], << doesn't have any function defined for std::any. Hence, we told the compiler to call const char * or std::string overload function of <<. Always, make sure that sizeof of...
72,227,756
72,228,064
Having problem Understanding fork() hierarchy tree
I have this Code that I can't understand. I understood the basics of fork() but I don't understand the Hierarchical tree for this process. The code is like this: main() { fork(); if(fork()){ printf("A"); } else{ printf("B"); } } The output is A A B B. How does this happen? I get it ...
Okay lets "draw" the process tree created by this program (using P for parent process, and C for child process): fork() ^ / \ | | P C | | /------------/ \------------\ ...
72,227,859
72,227,897
How to call a function at periodic interval that takes in an object as argument in C++?
I want to execute a function at periodic interval that takes an object as argument. I tried this answer: https://stackoverflow.com/a/72226772/13798537 that calls a function at periodic interval which takes an integer as argument, but I couldn't figure out how to call a function at periodic interval that takes an object...
operator() of non-mutable lambda is const. As you capture by copy, you cannot then mutate your captured "member". You probably want to capture by reference instead: set_interval([&window] { foo(window); }, 1000ms, cancel); or if you really want copy, make the lambda mutable: set_interval([window] mutable { foo(window)...
72,227,898
72,228,011
Passing and Returning a 2D array of unknown size in C++
I want to pass and return a 2D array of unknown size but I donot know how to do it. I know how to only return array of unknown size only (array of pointers). I know how to pass array of unknown size(templates) , but passing and returning a 2D array of unknown size at the same time is not working for me. I have the foll...
The problem is that the return type of your function is int** but you are returning array2d which decays to a double (*)[3] due to type decay. Thus, there is a mismatch in the specified return type of the function and the type you're actually returning. To solve this you can either use std::vector or use the placeholde...
72,227,992
72,232,113
How does boost graph dijkstra_shortest_paths pick the shortest path when there are multiple shortest paths between a specific pair of nodes?
I have an unweighted, undirected network of around 50000 nodes, from this network I need to extract the shortest path between any pair of nodes. I used the dijkstra_shortest_paths function from the boost library and it worked fine. Later I realised that between a given pair of nodes A and B, there can be more than one ...
The exact algorithm is documented: DIJKSTRA(G, s, w) for each vertex u in V (This loop is not run in dijkstra_shortest_paths_no_init) d[u] := infinity p[u] := u color[u] := WHITE end for color[s] := GRAY d[s] := 0 INSERT(Q, s) while (Q != Ø) u := EXTRACT-MIN(Q) S := S U { u } for eac...
72,228,010
72,228,823
Return a lambda from a lambda
I want to use a lambda to evaluate (switch-case) some conditions and return a lambda accordingly. const auto lmb1 = []() { printf("1\n"); }; const auto lmb2 = []() { printf("2\n"); }; const auto select = [](auto const &ref) { switch(ref) { case 1: return lmb1; case 2: return lmb2; } };...
The problem is that a lambda, by default, deduce (as an auto function) the returned type and in your lambda you return two different lambdas. Every lambda has a different type, so the compiler can't choose a type for the returned lambda [](auto const &ref) { switch(ref) { case 1: return lmb1; // decltype(lmb...
72,228,883
72,229,038
can you help me to fix this code about bubble sort?
i am newbie, i don't know how to fix it? i don't know how to call function void bubblesort #include<iostream> using namespace std; void bubbleSort(int a[], int n) { for (int i = 0; i < n - 1; i++) for (int j = n - 1; j > i; j--) if (a[j] < a[j - 1]) swap(a[j], a[j - 1]); } in...
When you pass an array as an argument into a function, you simply pass it as if it were a variable. In this case, simply just a would do. This is because arrays "decay" into pointers so a is a "pointer" to your array. In addition, I recommend dividing by the sizeof(a[0]) to get the full length as the sizeof function re...
72,229,332
72,229,448
Left Join C++ MYSQL library
I'm trying to access "category" table with LEFT JOIN. I need to retrieve the field "name" in this table. This is my code: void Product::read(MYSQL *connection) { MYSQL_RES *result; MYSQL_ROW row; if(mysql_query(connection, "SELECT * FROM product LEFT JOIN category ON product.category=category.category_id")) std::c...
You can be more specific about what columns are you selecting and their order. Rather than * you can specify the table_name.column_name (or just column_name if you have no overlaps, or alias_name.column_name if you want to use aliases), so you could try something like: SELECT product.name, product.brand, product.price,...
72,229,562
72,268,206
Compiling a JNI file with c++ postgresql in command prompt getting fatal error
Command executed: g++ -I"C:\Program Files\Java\jdk-16.0.2\include" -I"C:\Program Files\Java\jdk-16.0.2\include\win32" -I"C:\Program Files\libpqxx\include\pqxx" -shared -o hello.dll HelloJNI.cpp pqxx file dir - C:\Program Files\libpqxx\include I have included the path with -I . I am using C++ for the backend connection...
Compile the file in visual studio. Add the paths to the respective fields like additional include directories, linker files in the property. conclude the JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) inside a int main() method to compile since visual studio cannot compile the files without...
72,230,142
72,231,029
How to find the center and radius of an any dimensional sphere giving dims+1 points
given a vector of N-dimensional points. The vector will be of size N+1. Is there a generalized algorithm to find the center and radius of the ND sphere using those points where the sphere intersects every single one of those points?
The same question has been asked on the mathematics stackexchange and has received a constructive answer: Does a set of n+1 points that affinely span R^n lie on a unique (n-1)-sphere? Here is an implementation in python/numpy of the algorithm described at that answer. import numpy as np def find_sphere_through_point...
72,230,186
74,203,195
clang-14: warning: cannot compress debug sections (zlib not installed) [-Wdebug-compression-unavailable] while using address sanitizer
I have a sample C++ program that would cause an obvious segmentation fault. test.cxx: int main() { int* ptr{nullptr}; *ptr = 3; } So I am using address sanitizer to debug it: metal888@ThinkPad:~$ clang++ -g -fsanitize=address -fno-omit-frame-pointer -gz=zlib test.cxx -o vimbin && ./vimbin clang-14: warning: cannot...
What I found out is that the prebuilt versions of clang-14 (and versions that came later) that's found in the LLVM download page are not built properly. The -g compiler flag doesn't include any debug symbols in the binary. And sanitizer needs debug symbols to work. That's why I was getting those errors. So you have 3 o...
72,230,284
72,230,452
Different values for integer
Trying to insert values of square and cube of a number in set st and st1. (Let n = 10^7). After printing, set st is having negative values due to limit of integer but there are no negative values in set st1 even though both 'i' and 'temp' are integers. int n; cin >> n; int temp = 2; set<...
The behaviour of temp * temp < n is undefined if temp * temp overflows the type. Wraparound to negative is commonly observed but even with architectures that do that, optimising compilers are permitted to assume that if a + c < b + c for a constant c then a < b. temp < n / temp is a common refactoring that does not suf...
72,230,477
72,251,972
Visible order of operations with acquire/release fence in C++
I have a following program which uses std::atomic_thread_fences: int data1 = 0; std::atomic<int> data2 = 0; std::atomic<int> state; int main() { state.store(0); data1 = 0; data2 = 0; std::thread t1([&]{ data1 = 1; state.store(1, std::memory_order_release); }); std::thread t2([...
I think that t3 can print 1. I believe the basic issue is that the release fence in t2 is misplaced. It is supposed to be sequenced before the store that is to be "upgraded" to release, so that all earlier loads and stores become visible before the later store does. Here, it has the effect of "upgrading" the state.st...
72,231,235
72,231,511
c++ queue implementation not working as expected
Today I am looking to make my own dequeue in c ++ using pointers. Well, in the program, I want to create two dequeues in which to add different elements. Unfortunately, this is not what happened. On screen i got 6 5 insted only 6. Why?I'm not sure exactly how to make two separate dequeues? I think one of my problems ar...
Such a class might look like this: class /* or struct, if you really want to... */ Dequeue { public: void push(int value); bool pop(int& value); // if you return 1 for success and 0 for error // bool is the more appropriate type... private: struct elem // it's an implementation detai...
72,232,083
72,232,154
Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a deletted funciton'
I need a "holder" class. It is supposed to store objects references. Like: holder.A = a; // Gets a reference! Sample code bellow including the compiler error: class A { }; class Holder { public: A& MyA; // I want to store a reference. }; int main() { A testA; Holder holder; // Compiler error: the default ...
The problem is that since your class Holder has a reference data member MyA, its default constructor Holder::Holder() will be implicitly deleted. This can be seen from Deleted implicitly-declared default constructor that says: The implicitly-declared or defaulted (since C++11) default constructor for class T is undefi...
72,232,317
72,233,089
C++ change parent class based on option
There is a Student class inherited from Person. And there is Student class inherited from University. I want to change the parent class Person, University based on the option without rewriting Student such as Student1 and Student2 (because student class is very complicated). Here is the example code. class Person { ...
Since we can't know what option.person is at compile-time, we need to find a way to work around that at runtime. One option for doing so is std::variant, which can store any number of different types; but does so at the cost of always having the same size as the largest templated type. As an example, if I did this: std...
72,232,384
72,232,486
Parameter pack iteration
Why this code doesn't compile ? #include <iostream> #include <typeinfo> template <typename ...Ts> void f(); template <typename T> void f() { std::cout << typeid(T).name() << std::endl; } template <typename T, typename U, typename ...Ts> void f() { std::cout << typeid(T).name() << ", "; f<U, Ts...>(); } ...
Compiling with g++ gives a pretty clear explanation of what's happening: prog.cc: In function 'int main(int, char**)': prog.cc:20:24: error: call of overloaded 'f<int, float, char>()' is ambiguous 20 | f<int, float, char>(); | ~~~~~~~~~~~~~~~~~~~^~ prog.cc:5:6: note: candidate: 'void f() [with Ts = {in...
72,232,396
72,232,569
Is it possible to determine if a pointer points to a valid object, and if so how?
I was reading C++ Is it possible to determine whether a pointer points to a valid object? and the correct answer in this thread is that no, you can't do that, but the thread is quite old now and I wanted to know if anything has changed. I read that with smart pointers that would be possible. So how could that be achiev...
Is it possible to determine if a pointer points to a valid object No, it isn't generally possible to determine whether a pointer points to a valid object. I wanted to know if anything has changed Nothing has changed in this regard. I read that with smart pointers that would be possible. So how could that be achiev...
72,232,484
72,233,716
C++ - Reading a line without getline
I am trying to read user entered data from the stream and then store it in a custom String class. To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class. My code looks like this: String street(); ...
To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class. Note that std::getline and std::istream::getline are two separate functions. The former will work with std::string while the latter will w...
72,232,792
72,238,950
Covariant return type on Eigen Matrix for base class method
Suppose that I have two different solvers that both will be called at run time. I want to call solvers' api and get resulted Eigen matrix through the base class pointer. The solved matrix size are selected from a few known values depending on some runtime variable. I need to use compiled time fixed size matrix in this...
The easiest solution would be to just store a VectorXd solution_; inside Solver itself. But if you insist on storing the actual solution vector only in the derived classes, you can have solution() return an Eigen::Ref<const Eigen::VectorXd> which can be created with just moving a pointer and a few integers: class Solve...
72,233,035
72,233,722
Get temp path with file name
I want to get path to file like this > %ENV%/%FILE_NAME%.docx But c++ doesn't make sense at all and nothing works.. I would use std::string but it's not compatible so I tried multiple ways of converting it to char[] or char* but none of them works and I'm also pretty sure this is unsafe.. My code so far (I know it's t...
Using appendCharToCharArray() is just horribly inefficient in general, and also you are leaking lots of memory with the way you are using it. Just use std::string instead. And yes, you can use std::string in this code, it is perfectly "compatible" if you use it correctly. getBaseName() is returning a char* pointer to...
72,233,118
72,233,251
C++ unpack variadic template arguments with the next function returns nothing
I'm trying to expand arguments to a variadic function. Code below works perfectly fine template<typename T> int printMy (const T& f) { cout << f << endl; } template<typename... Types> void print (Types... args) { auto i = {printMy(args)...}; } int main() { std::string s("world"); print(7.5, "hello", s)...
You can use fold expression with C++17 to compute the result of using a binary operator over all the arguments of the parameter pack, to solve the problem as shown below. The shown program uses unary right fold to achieve the desired effect. template<typename... Types> void print (Types... args) { (printMy(args)...
72,233,203
72,233,250
Should you always put join() after launching a thread?
I wonder if there is any advantage putting join() not immediately after launching a thread? std::thread t(func); // some code ... t.join(); does it give you any advantage or it's always preferable to use it after a thread launch? std::thread t(func); t.join(); // some code ...
If you use join() right after starting the new thread then it will block (wait) execution on the join() call until the new thread is finished running (defeating the whole purpose of the parallelization you get from starting the new thread). Therefore, if you want to execute "some code" on the main thread while thread t...
72,233,769
72,233,809
Is there a way to find exact location ( adress ) of file on disk?
I'm developing a software using C++ for Windows/Linux. I want to create a file (txt, json, license, you name it) at runtime, and save it somewhere. Is it possible in C++ to get the exact position of that file on disk, so that if I restart the app and read that address (or other), I'll be able to access its data? The pu...
An image of a disk copies it byte by byte, meaning that all addresses (locations) on disk stay exactly the same. So your copy protection won't actually work - you can still easily clone the disk while preserving your special copy protection file. Additionally, a file may not even have a defined location on disk: It may...
72,234,002
72,234,106
cannot convert 'LinkedList::filter(void (*)(Node*))::<lambda(Node*)>' to 'void (*)(Node*)'
Im trying to implement a simple LinkedList class, but this error shows up and I don't understand why. struct Node { public: int val; Node* next; Node(int v) : val(v), next(nullptr) {} }; struct LinkedList { public: Node* head; Node* tail; LinkedList() : head(nullptr), tail(nullptr) {} void...
As mentioned in the comments, a capturing lambda is not the same as a function pointer. Instead, behind the scenes, it is a fully-fledged object (because it has state). Fortunately, there's an easy fix - you can use the magical powers of std::function to abstract away all the messy details. To do this, all you have t...
72,234,300
72,234,423
What is differnece between CreateWindowEx, CreateWindowExA, CreateWindowExW?
I read the documentation about CreateWindowEx CreateWindowExA CreateWindowExW and they all are seem to be identical to each other. if there is not difference why they all even exist?
Firstly, CreateWindowEx is a macro, which expands to either CreateWindowExA or CreateWindowExW based on whether UNICODE has been defined. Many WinAPI functions work this way: they have a macro which switches between the appropriate functions based on UNICODE, then have the A and W versions. Now, the difference with the...
72,234,443
72,234,632
I need a function to delete certain characters from a char array in c++ without using any index
for example: if the user enters : ( 23+22+43) I want the function to do exactly the following : for(int i =0; i <strlen(x);i ++) { if (x[i]=='+') { deletfunc(x[i]); deletfunc(x[i+1]); cout<<x; } } so that the output will be (2323) without using index ----> without knowing the exact number of th...
Usually when working with a C style string and the instructor says, "No indexes!" they want you to use a pointer. Here is one way you could use a pointer char * p = x; // point p at start of array x while (*p) // loop until p points to the null terminator - the end of the string { if (*p=='+') // if value at p is +...
72,234,470
72,234,572
Is there a simpler way to write a concept that accepts a set of types?
Essentially, is there a shorter/cleaner way to define Alphabet than using a bunch of std::same_as/std::is_same? struct A {}; struct B {}; struct C {}; ... template <typename T> concept Alphabet = std::same_as<T, A> || std::same_as<T, B> || std::same_as<T, C> || ... You could accomplish this (sort of) ...
Using Boost.Mp11, this is a short one-liner as always: template <typename T> concept Alphabet = mp_contains<mp_list<A, B, C>, T>::value; Or could defer to a helper concept (or a helper variable template or a helper whatever): template <typename T, typename... Letters> concept AlphabetImpl = (std::same_as<T, Letters> o...
72,234,507
72,349,335
How can I remove the title bar / undecorate the window in FLTK on Linux?
I have been doing some things with FLTK on Linux lately, and now I've wondered how I can remove the title bar / undecorate the window. The target Operating System is Linux, but it would be preferrable if it runs on wayland as well as on xorg.
There are two functions that can be used: border(int b) and clear_border(). The border(int b) function tells to the window manager to show or not the border: see here the documentation. This can be used during the execution. The other useful function is clear_border(): calling it before the Fl_Window::show() function m...
72,235,131
72,235,238
Expand variadic template template parameters for use in e.g. std::variant<T...>
This will be a hard nut to crack. I don't even know if it's possible. My goal is to create a receive function that listens to multiple queues and pastes the object received via the particular queue (that responds first) to the stack in the return statement. This will be done via std::variant. The tricky bits are types:...
Since all your queues use the same template (queue<...>), you don't need a template template parameter (in which, by the way, the name of the nested parameter (T in your case) is ignored). You just need a type pack: typename ...T. I also got rid of the variant array, and instead opted to iterate over the arguments dire...
72,235,156
72,249,468
Provide run time environment variable path (e.g. LD_LIBRARY_PATH) to third party dependency in bazel
In the code base I am working with we use the oracle instant client library as a third party dependency in Bazel as follows: cc_library( name = "instant_client_basiclite", srcs = glob(["*.so*"]), visibility = ["//visibility:public"], ) The library looks as this: $ bazel query 'deps(@instant_client_basiclit...
One possibility is to add the following command line option: --test_env=ORACLE_HOME="$(bazel info output_base)/external/instant_client_basiclite" It is a pity that it cannot be put in .bazelrc.
72,235,463
72,235,700
Aliasing a SSBO by binding it multiple times in the same shader
Playing around with bindless rendering, I have one big static SSBO that holds my vertex data. The vertices are packed in memory as a contiguous array where each vertex has the following layout: | Position (floats) | Normal (snorm shorts) | Pad | +---+---+---+---+---+---+---+---+---+---+---...
Vulkan allows incompatible resources to alias in memory as long as no malformed values are read from it. (Actually, I think it's allowed even when you read from the invalid sections - you should just get garbage. But I can't find the section of the standard right now that spells this out. The Vulkan standard is way too...
72,235,485
72,240,702
Clarification about modern CMake structure
I am not an expert C or C++ programmer, but I have to write a C and a C++ application for two course projects. To start off on the right foot, I was reading a guide about how to structure the code of a CMake project. I would like to clarify the meaning and usage of the include directory: If the project is a library, i...
If you are writing an application, you can put stuff wherever you want. The user mostly expects you to have a bin subdirectory with your binary executables. Oh, and please support the CMAKE_INSTALL_PREFIX: in-source builds are evil, as far as I'm concerned. If you are writing a library, the user expects subdirectories ...
72,235,611
72,235,952
Initialize array based on C++ version and compiler
In C++11 or higher regardless of compiler int myArray[10] = { 0 }; would initialize to all elements to zero. The question is would this also work in C++98 and could the compiler not decide to initialize all elements to zero? In other words could C++98 with a given compiler ignore the assigning zero to all elements? I f...
All elements would be zero. Quotes from C++98: [dcl.init.aggr] If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized (8.5) [dcl.init] To default-initialize an object of type T means: if T is a non-POD class type (...
72,236,508
72,237,025
Returning MIME data from a function in Qt
I am trying to create a class with drag and drop. I want it to be used as a base class for future derived classes. I want derived classes to specify MIME data for Drag and Drop. I made a function that returns MIME data as a pointer, I am not sure if it is safe to do so. Is it possible that it will cause memory leak or ...
The man page for QDrag::setMimeData() says that “ownership of the QMimeData object is transferred to the QDrag object”, which is another way of saying that the QDrag object will delete the QMimeData object when it is done with it. Therefore you should not experience any memory leak of the QMimeData object (unless you ...
72,236,837
72,236,900
Problem: Assigning a group number to elements near eachother where groups are separated from spaces
We have a room divided of 6x5 possible seats, every place in the 6x5 matrix could be a seat or could be empty. We have the Matrix with all the seats already assigned on their location, and every seat has an unique code which is the actual Column(A,B,C,D,E)Row(1,2,3,4,5,6) position. Unique code Example could be: A1, C4,...
This is a classical neighbourhood-search scenario. See BFS / DFS algorithms. You can instantiate the graph as a simple array or a two-dimensional array and have implicit edges between each two neighbouring cells that both have a seat assigned. For example: std::array<std::array<std::optional<unsigned>,7>,8> matrix; As...
72,236,995
72,237,085
Object Oriented Programming - Inheritance C++, Code does not compile
Source Code #include <iostream> using namespace std; class A { private: long int a; public: long int b,x; void set_a(){ cout<<"Enter variable A's value (integer) \nAnswer: "; cin>>a; x=a; } void display_a(){ ...
There are 2 problems with your code described below. Problem 1 You have a method prod with the same name as the data member prod in class B. To solve this change, you can either change the name of the method or the data member so that they're not the same as shown below. Problem 2 The code has undefined behavior becaus...
72,237,424
72,237,467
Issue overloading the operator c++
I keep getting the following errors Error (active) E0349 no operator "<<" matches these operands Error C2678 binary '<<': no operator found which takes a left-hand operand of type 'std::ostream' (or there is no acceptable conversion) I know the issue is that there's something going wrong or missing when I try to...
The problem is that you've used: stream << Account.display(stream); inside the overloaded operator<<. This is a problem because account::display returns a std::ostream and there is no overload of operator<< that takes a std::ostream as a parameter. Method 1 To solve this you can add a friend declaration for the overlo...
72,237,709
72,237,791
how to initialize a class object reference in C++ to simulate NRVO?
I meet a course programming problem, which asks me to initialize the A a using passing by reference (initialize the A a in the func). How can I call A's constructor by A's reference? #include <iostream> using namespace std; class A { public: int x; A() { cout << "default constructor" << endl; ...
The syntax a.A::A(10); is incorrect. Constructor is used to create an object of a class, you cannot call it on an already existing object. Even a constructor cannot be explicitly called. It is implicitly called by the compiler. From general-1.sentence-2: Constructors do not have names. Thus, you cannot call a constru...
72,237,872
72,237,946
Modifying a member variable
I'm having an issue with modifying a member of a class. I overloaded the operators and I think that I am calling the member correctly to modify it but am getting the issue that the "expression must be a modifiable l-value. Any help would be appreciated .h file public: account& operator+= (float x); account& ope...
Your set_balance function doesn't set anything. You probably want this: float& account::get_balance() { return this->acct_balance; } Then you can do user1.get_balance() += withdraw;. This get_balance function gets the balance as a modifiable l-value, which is what you need. Since you have an operator+=, you could ...
72,238,228
72,240,852
BOOST request sending JSON data
I want to transfer json data into request of json boost in cpp. If i take json in boost int outer=2; value data = { {"dia",outer}, {"sleep_time_in_s",0.1} }; request.body()=data; like above i want to send data from boost client to server , but it's through error is any one understand below error...
C++ is strongly typed. You cannot assign a json::value to something else. In this case your body() is likely something like std::string. Assuming that value is boost::json::value you should write something like: request.body() = serialize(data); Where boost::json::serialize serializes the data value into string repres...
72,238,972
72,239,020
emplace and try_emplace with copy constructor
I have an issue with emplace and try_emplace as they always use the copy constructors when moving an object in. #include <iostream> #include <unordered_map> #include <map> using namespace std; class Too { public: Too(int x, int y):x_(x), y_(y) { cout << "init " << x_ << endl; } Too(const Too& to...
Since you've provided a copy constructor for your class, the move constructor Too::Too(Too&&) will not be implicitly generated by the compiler. Moreover, when there is no move constructor available for a class, the copy constructor can be used. For using the move constructor you have to explicitly provide an appropria...
72,239,021
72,239,154
Passing an array in struct initialization
I would like to create a struct which contains both an int and an array of int. So I define it like struct my_struct { int N ; int arr[30] ; int arr[30][30] ; } Then I would like to initialize it with an array which I have already defined and initialized, for example int my_arr[30] ; for (int i = 0; i < 30; ++i) { my_...
Arrays cannot be copy-initialised. This isn't particular to the array being member of a class; same can be reproduced like this: int a[30] = {}; int b[30] = a; // ill-formed You can initialise array elements like this: my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //... But that's not always very convenient. A...
72,239,263
72,239,359
Expression does not evaluate to a constant
I've just started to learn C++ and I don't understand this error: std::string AFunction(const std::string& str) { size_t s = str.length(); char inProgress[s]; return std::string(); } I get the error: error C2131: expression does not evaluate to a constant Here: char inProgress[s]; What do I have to do...
The problem is that in standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program: size_t s = str.length(); char inProgress[s]; //not standard C++ because s is not a constant expression Better would be to use std::vector as shown below: std::string AFu...
72,239,570
72,239,597
How to construct a class from a pack in C++?
I am trying to initialize a class with a pack passed as an argument to my function. Here is what I got so far: struct Vec3 { float x, y, z; }; template<typename _Ty, typename... Args> __forceinline _Ty construct_class(Args&&... arguments) { return _Ty(arguments...); } // here I am trying to construct a Vec3 b...
You could replace return _Ty(arguments...) with return _Ty{arguments...} as shown below: //---------------v--------------------- v----->removed the underscore template<typename Ty, typename... Args> Ty construct_class(Args&&... arguments) { //-----------v------------v------------------->used curly braces instead of pa...
72,240,126
72,242,127
MISRA 5-0-15 - Pointer Arithmetic - Rule Violation
The following code violates the MISRA C++ rule 5-0-15: Array indexing shall be the only form of pointer arithmetic. (1) void doSomething(const uint8_t *&ptr, size_t num) { ptr += num; } Incrementing any pointer also violates the above rule: (2) const uint8_t *ptr = ... ; *ptr++; I found a very similar question here...
Array indexing So use array indexing. void doSomething(const uint8_t ptr[], size_t num) { const uint8_t *ptr2 = &ptr[num]; } Incrementing any pointer Increment and decrement operators can be used by exception. Doing dereference with incrementing is invalid. There have to be two expressions. const uint8_t *ptr...
72,240,387
72,240,549
Why is std::reverse_iterator slower than a direct iterator?
I noticed that std::reverse_iterator always decrements a copy of internal iterator before dereference: _GLIBCXX17_CONSTEXPR reference operator*() const { _Iterator __tmp = current; return *--__tmp; } This is the implementation in GNU standard C++ library. cppreference.com implements it the same way. The questi...
The question: wouldn't it be more efficient to decrement it just one time in reverse iterator constructor instead of decrementing it at every dereference step? Efficiency is irrelevant when it's not possible to implement reverse iterator that way. Consider a reverse iterator representing rend. In order to get to it, ...
72,240,404
72,240,861
Big O notation calculation for nested loop
for ( int i = 1; i < n*n*n; i *= n ) { for ( int j = 0; j < n; j += 2 ) { for ( int k = 1; k < n; k *= 3 ) { cout<<k*n; } } } I am facing an issue with this exercise, where I need to find the big O notation of the following code, but I got O(n^5) where the first loop is n^3, 2nd l...
Your analysis is not correct. The outer loop multiplies i by n each ietration,starting from 1 till n^3. Therefore there will be 3 iterations which is O(1). The middle loop increments j by 2 each iteration, starting from 0 till n. Therefore there will be n/2 iterations which is O(n). The inner loop multiplies k by 3, fr...
72,240,611
72,274,597
D3D : hardware mip linear blending is different from shader linear blending
I have a d3d application that renders a mip mapped cubemap in a fullscreen quad pixel shader. I stumbled on a weird behavior, and wrote the following test to illustrate the issue. This shader outputs the absolute difference between hardware mip map filtering and HLSL equivalent. TextureCube Tex_EnvMap : register(ps, t0...
I was writing "but anisotropic filtering is not a candidate as I use explicit LOD sampling)". It turns out that this statement it wrong. To my understanding, anisotropic filtering should not affect sampling with textureLOD, however, it seems that in some implementations, it does, ex: https://forum.unity.com/threads/tex...
72,241,045
72,242,048
Ternary operator applied to class with conversion operator and delete constructor causes ambiguity
struct A { A(); A(int) = delete; operator int(); }; int main() { true ? A{} : 0; } Compile with C++20, Clang accepts it, but GCC and MSVC reject it with similar error messages <source>(8): error C2445: result type of conditional expression is ambiguous: types 'A' and 'int' can be converted to multiple common...
This seems to be a variant of CWG issue 1895. Before its resolution (in 2016 with C++17) the relevant wording asked whether either operand could be "converted" to the target type formed from the other operand's type. Going by the issue description, it seems this original wording, as well as the wording around it, were ...
72,241,156
72,241,320
Using the dynamic_cast operator
I'm trying to understand dynamic type casting. How to properly implement the DrawAnimals and Talk To Animals functions using dynamic_cast? DrawAnimals draws animals that can be drawn. Such animals implement the Drawable interface. TalkToAnimals conducts a conversation with animals that can talk, that is, they implement...
I am going to explain for DrawAnimals and you can extended to other functions by yourself. What you did here: void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) { /*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) { } else if (const Bug* c = dynamic_cast<const Bug*>(&animals)...
72,241,315
72,241,389
Convert std::vector to std::string without \0
I want to remove the vowels from a std::string with this code: # include <string> #include <vector> bool IsVowel(char c) { return ((c == 'a') || (c == 'A') || (c == 'e') || (c == 'E') || (c == 'i') || (c == 'I') || (c == 'o') || (c == 'O') || (c == 'u...
As you can see, inProgress always contains str.length() many elements. index tells you the actual number of vowels in there. std::string has constructors that let you use that information to determine how much of inProgress to use in the initialization of sy. So, you could do: std::string sy(inProgress.begin(), inProgr...
72,241,322
72,241,968
How to find the count of sub numbers of size k which divide the number
Given a number n Find the count of the sub numbers of size x in a number num which divides num. For example, if the number is 250 and x=2 the answer will be 2 as 250%25==0 and 250 % 50==0. Can anyone help me out with the cpp code ? class Solution { public: int divisorSubstrings(int num, int k) { string s=to...
You have a number of problems. First, using simple letters for your variables means we don't have a clue what those variables are for. Use meaningful names. Second, this: for(int k=i;k<=j;k++) You have an argument to your method called k. You've now shadowed it. Technically, you can do that, but it's a really real...
72,241,514
72,241,582
vector push_back memory access denied in Visual Studio
#include <stdio.h> #include <vector> using namespace std; int main() { vector<int> numbers; numbers.resize(10001); for (int i = 0; i < 10000; i++) { numbers.push_back(1); } return 0; } If I put more than 5000 1s in the vector, I get the following error, I don't understand. There is...
The error seems unrelated to the code that you've shown. Now, looking at your code there is no need to use resize and then using push_back as you can directly create a vector of size 10001 with elements initialized to 1 as shown below: std::vector<int> numbers(10001,1);// create vector of size 10001 with elements initi...
72,242,061
73,369,849
(esp 32) http.GET() is so slow
I want to get data from REST API by an esp32 and turning on and off LED lights(GPIO 26 and 27). Here is my code : #include <HTTPClient.h> #include <ArduinoJson.h> #include <WiFi.h> const char* ssid = "ssidName"; const char* password = "password"; void setup() { Serial.begin(115200); pinMode(26, OUTPUT); pinMode(27, O...
I have finally managed to do that by Websokcet . you have to make http persistent connection , HTTP client library in idf is good but your server has to support it , the better practice is websocket.
72,242,240
72,242,357
Why can’t my code find the second smallest elements array?
int smallindex = 0; int secsmallindex = 0; I put the lines above into gobalslope. The rest of the code: #include <iostream> using namespace std; int main() { int list[10] = { 33,6,3,4,55,22,5,6,7,6 }; for (int a = 1; a <= 10; a++) { if (smallindex > list[a]) { secsmallindex = smallind...
You had some problems. Mostly index ranges of an array, and comparing index with the actual value stored in the array. I commented out the old (problematic) lines and added the correct ones with some description. (Demo) #include <iostream> using namespace std; int main() { /// You don't need these variables to b...
72,242,246
72,245,095
Getting an HTTP response status code of 0 and empty message using C++ curl library libCPR
I'm using libcpr to send a GET request. cpr::Response r = cpr::Get( cpr::Url{target.str()}, cpr::Header{header}); For debugging, I print the response— std::cout << "Response Error: " << r.error.message << std::endl; std::cout << "Response Error Code: " << (int)r.error.code << std::e...
Of course, it's the simplest thing that I didn't try. This warning tipped me off: -- Could NOT find LibSSH2 (missing: LIBSSH2_LIBRARY LIBSSH2_INCLUDE_DIR) I simply did a brew install libssl2 and it now works.
72,242,566
72,242,620
Bounds of mesh are scaled by its world postion
I am trying to get the correct world postion and size of the bounds for a mesh, however the size of the bounds are scaled by the position of the mesh. The bounds of the mesh itself are correct, but trying to get them into world space does not work. Fotos: 1 and 2 The code for rendering the bounds: void MeshRenderer::dr...
size is a vector, but not a position. So it has to be bounds.size = transformation * glm::vec4(m_Mesh.bounds.size, 1.0); bounds.size = transformation * glm::vec4(m_Mesh.bounds.size, 0.0);
72,242,679
72,243,569
generic decorators for callable objects with conditional return
I want to write decorator functions for callable objects. This is what I have now: #include <utility> template <typename DecoratedT, typename CallableT> constexpr auto before_callable(DecoratedT &&decorated, CallableT &&callBefore) { return [decorated = std::forward<DecoratedT>(decorated), callBefore =...
I'm using the SCOPE_EXIT macro from Andrei Alexandrescus talk about Declarative Control Flow. The trick here is that SCOPE_EXIT creates an object with a lambda (the following block) and executes the lambda in the destructor. This delays the execution until the control flow exits the block. SCOPE_EXIT will always execut...
72,243,396
72,270,720
Cout Not Printing the Return Value from the function
I am trying the Infix to Prefix conversion and evaluation in C++. Someone here guided me and my converstion was resolved easily. But now I am having problems while evaluating it. The problem is that cout is not printing the return value from my function. Following is my code: int PrefixEvaluation(string s) { stack<...
The console simply displays a blank screen. That is a problem. Not so much because your program crashed, but because you do not know where it crashed. The traditional remedy for this is to use a debugger, but in this case diagnostic output could be illuminating. Furthermore, for a project like this (a fairly simple c...
72,243,827
72,251,462
How can I create a Qt project without a UI/Designer file?
I'd like my project to be written programmatically instead of using Qt Designer. EDIT: I'm just asking for a template :P
EDIT 2: I found out how, feel free to use the code down below: #include <QtWidgets/QDialog> #include <QtWidgets/QApplication> class MyWindow : public QDialog { public: MyWindow(QWidget* parent = nullptr); }; MyWindow::MyWindow(QWidget* parent) : QDialog(parent) { setWindowTitle("MyWindow"); // Make w...
72,243,858
72,244,312
Delete empty lines in file
I'm trying to delete empty lines from a file. Currently it deletes all except for the one I add at line 35:out_file << data_vector[i] << "\n"; How do I exclude the last "\n" so it doesn't add a new line? Here's the full function: std::vector<std::string> Data::Data::ReadData() { std::regex find_empty_line("^(\\s*)...
It's best practice (on most Operating Systems), and expected by a lot of file processing tools, to have a newline at the end of every line in a file, so you normally wouldn't want to remove the final newline... consider it a line termination character with no line after it, rather than a line separator with an implicit...
72,243,871
72,244,058
Group of structured binding errors, pertains to neural networking
so i downloaded a library that hasnt been in use in years, for Neural Evolutionary Augmenting Topologies. Basically, a neural network that evolves. It came with many, MANY errors out of the box (somewhere around 20-30) and i managed to fix them all, except for these: Error C3694 a structured binding declaration c...
As the error message says only the auto type specifier (and cv-qualifiers) is allowed in a structured binding, so replace float&& with auto&&. If you are uncomfortable with this syntax, you don't need to use it though. It is purely syntactical sugar. You can access the values of the individual elements of a std::tuple ...
72,244,215
72,251,062
OpenGL Compute Shader: Writing to texture seemingly does nothing
I've found a handful of similar problems posted around the web an it would appear that I'm already doing what the solutions suggest. To summarize the problem; despite the compute shader running and no errors being present, no change is being made to the texture it's supposedly writing to. The compute shader code. It wa...
I've found a solution! Apparently, in the case of a 3D texture, you need to pass GL_TRUE for layered in glBindImageTexture. https://www.khronos.org/opengl/wiki/Image_Load_Store Image bindings can be layered or non-layered, which is determined by layered​. If layered​ is GL_TRUE, then texture​ must be an Array Texture ...
72,244,407
72,244,420
There seems to be a problem with input of only 2 with a size of 6. Everything else seems to work exactly as expected. Why is this happening
I am starting to learn c++. So I want to try this using only recursion.Thank You for your help. #include <iostream> using namespace std; int lastIndex(int arr[], int size, int num){ size--; if(size < 0)return -1; if(arr[size] == num)return size; return(arr, size, num); } int main(){ int arr[11] =...
i think you mean return lastIndex(arr, size, num); your code return(arr, size, num); is equivalent to return num;
72,244,467
72,246,635
What is the necessary lifetime for SetWindowTextA string parameter
I have a program that creates a std::string s on the heap and passes it to the SetWindowTextA(hWnd, s.c_str()) My question is how long does that string need to live? Does SetWindowTitleA copy the string or do I need to keep the string alive?
Since my question was answered in the comments here is the the quick answer to anyone having the same question: Yes SetWindowTitleA will create a copy of the passed in const* char. So the necessary lifetime is until the function returns. Then the passed string can be deleted, dropped or whatever.
72,244,685
72,244,795
Why does a non-constexpr std::integral_constant work as a template argument?
My question is why the following code is valid C++: #include <iostream> #include <tuple> #include <type_traits> std::tuple<const char *, const char *> tuple("Hello", "world"); std::integral_constant<std::size_t, 0> zero; std::integral_constant<std::size_t, 1> one; template<typename T> const char * lookup(T n) { //...
Of course, we happen to know in this case that the body of the conversion operator doesn't look at the runtime value, but nothing in the type signature guarantees that. Correct. What you are missing is the fact that this doesn't matter. When a function is called during constant expression evaluation, the compiler che...
72,244,716
72,248,865
co_await is not supported in coroutines of type std::experimental::generator
What magic generator should I define to make the code below work? #include <experimental/generator> std::experimental::generator<int> generateInts() { for (int i = 0; i < 10; ++i) { co_await some_async_func(); co_yield i; } }; with MSVC I get compiler error: error C2338: co_await is not s...
My understanding is probably that generator_iterator can't handle co_await because it requires the task to be suspended with co_yeld, see the iterator source code: generator_iterator& operator++() { m_coroutine.resume(); if (m_coroutine.done()) { m_cor...
72,244,834
72,245,177
Does header file import modules a standard thing?
C++ 20 modules guaranteed backward compatible so modules can import headers. And Visual Studio introduced header file import modules,is this stardard or just a VS thing? // MyProgram.h import std.core; #ifdef DEBUG_LOGGING import std.filesystem; #endif
#include is a preprocessor directive that does a textual copy-and-paste of the text in the target file. Modules didn't change this. Textually copy-and-pasting import directives is still textual copy-and-pasting. So yes, this is standard. Assuming your compiler implements them correctly. That being said, it's probably n...
72,245,002
72,245,551
Calling a purely template lambda callback in C++20
With C++20, we've gained templated lambdas, great! []<class T>(){}; Is it possible to call a lambda callback with a template parameter, but no argument to deduce it from? For ex, template <class Func> void do_it(Func&& func) { // Call lambda with template here, but don't provide extra arguments. // func<int>()...
Is it possible to call a lambda callback with a template parameter, but no argument to deduce it from? This is probably what you want template <class Func> void do_it(Func&& func) { func.template operator()<int>(); }
72,245,577
72,245,660
strlen defaulting to '40'?
new programmer here starting with the basics. I need to write a code that checks for the length of a string (line) and does things with it. I'm working on getting the length correct before I start with the next part of the task. What's happening when I run the below code is strlen(string1) seems to be defaulting to '40...
There are 2 problems with your code as described below: Problem 1 In standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program: char string1[line]; //not standard C++ because line is not a constant expression Problem 2 Note that there is another probl...
72,245,664
72,245,800
using declval with reference types
I would like to understand how the assignment of int & to double below in conjunction with declval works? Is T deduced to something other than int & ? #include <iostream> #include <type_traits> #include <utility> template <typename T, typename U, typename = void> struct assignment : std::false_type{}; template <typen...
Is T deduced to something other than int & ? T will still be deduced as int&, so std::declval<T>() = std::declval<U>() will be roughly equivalent to int& f(); double&& g(); f() = g(); // assignment Note that f() = g() is still well-formed because f() returns a reference to an already created int that can be assigne...
72,245,738
72,245,903
concepts template argument deduction
The concept below has two template parameters but only one is specified during usage. Is T always deduced and InnerType always the parameter that needs explicit specification? #include <iostream> #include <string> #include <span> template < class T, class InnerType > concept RangeOf = requires(T&& t) { requires s...
When you use concepts with templates as you did there, the type you are trying to constraint matches the very first type-argument. Everything else you specify comes after that in the order you specified. Here's a simplified example: #include <concepts> template <class T1, class T2, class T3> concept ThreeTypes = std::...