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
64,698,690
64,699,078
Get object instance class name with Qt's meta-object system
I have 3 classes: class Being : public QObject { Q_OBJECT public: explicit Being(QObject *parent = nullptr); }; class Animal : public Being { Q_OBJECT public: explicit Animal(QObject *parent = nullptr); }; class Dog : public Animal { Q_OBJECT public: explicit Dog(QObject *parent = nullptr); };...
It is not possible in the constructor of Being because the enclosing object is not constructed yet, therefore metadata about it is not available. However, you can write the initialize method that should be called after the object construction, e.g. with print function: class Being : public QObject { Q_OBJECT public...
64,699,116
64,707,827
C++ API Wrapper in C for Java/JNA Object references
I'm writing a C API wrapper for my own C++ library. I want to use the C-API with JNA in Java. For each class in the C++ library I wrapped the constructors in C function calls, returning a handle. With this handle I can call C functions, which are wrapping the object's member functions (casting the handle to it's class ...
The code as you've written it will not cause any problems, assuming that you have a native method for releasing the Foo object in C. What your description seems to be missing is the difference between Java side memory and Native memory. They are separately allocated and handled. Some key points: calling new Foo() in...
64,699,381
64,700,590
Procedural grid on a plane in 3d space in opengl
I have a simple graphics program written in c++ that uses opengl for rendering. I have a plane that I draw at the origin and I want to add a procedural grid texture to it. In my current fragment shader I only do some lighting calculations: #version 330 core out vec4 FragColor; in vec3 Normal; in vec2 TexCoord; in ve...
The easiest way to do this will be to play around with trig functions. Since you are passing the texture coordinates already. Let the color intensity be max(cos(u), cos(v)). That will give you a start. Then you should play around with the cos formula to get it exactly how you want it (i.e. multiply it by some coefficie...
64,699,393
64,699,456
Check for equality against multiple values in C++
I am looking for an easy, fast and descriptive way in C++ to check if a value is contained in a fixed set of other values. Like in Python, where one can write if some_function() in (2, 3, 5, 7, 11): do_something() Some obvious options are: switch/case: If the values in question are integers, then one can write s...
Yes, you can indeed write a variadic template function, combined with a fold-expression, like this: namespace my { template<typename T, typename ... Vals> bool any_of(T t, Vals ...vals) { return (... || (t == vals)); } } and then use it like this: if (my::any_of(some_function(), 2, 3, 5, 7, 11)) { ...
64,699,525
64,700,207
Set an element of an array of pointers to a pointer in C++
I have the following code: #include <iostream> #include <string> using namespace std; class Vector { public: double *array; int width; Vector (int width) { array = new double[width]; this->width = width; } double& operator[] (int x) { return this->array[x]; } };...
From what I understand, you simply want to access the elements of matrix as martrix[a][b] and not matrix.array[a]. First thing first, your operator[]() is inefficient. It won't be able to handle the cases of matrix with width other than 2. To correct that, you need to change Vector v = new Vector(2); to Vector v = new...
64,700,134
64,700,217
How to initialize a template class with a non constant value
I have a template class that needs I need to set the size of using the size of a vector. what is the best way to achieve this? below is a simplified version, I will link to the full class if you need to see it. template<int maxParams> class ParameterChangeHandler { public: inline ParameterChangeHandler() { ...
What you want isn't possible. Here's what you can do. Pass myVectorOfParameters.size() as an argument to the constructor and use std::vector/std::basic_string instead of unsigned char array so you don't need a constant expression for the size. #include <vector> #include <cstddef> class ParameterChangeHandler { public:...
64,700,138
64,704,233
Load C# (COM) in a Credential Provider : working with winlogon, but problem when explorer loads it
I created a custom Credential Provider for Windows. The base DLL is in C++ and it loads a C# DLL trought a COM interface. if (CoInitialize(NULL) != S_OK) { hr = _authenticationManager.CreateInstance("{BAF984BD-0D41-42D1-AA49-4BC98EE6C4A1}"); std::stringstream stream; stream << std::hex <<...
Anymore, COM is a bad idea! Alternativelly, you can use Visual C++ CLI. CLI support is a bridge between native C++ and managed C#.NET libraries.
64,700,886
64,700,907
I keep getting this error each time i compile and run : main.cpp:15:29: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
I keep getting this error each time i compile and run : main.cpp:15:29: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] #include <iostream> using namespace std; int main() { string paragraph; cin>>paragraph; int wordsCount; int pSize = paragraph.length(); for (int i ...
" " is a string literal. This is an immutable character array and is converted to a pointer to the first element of the array in this case. You should ' ' (character surrounded by single quote, not double quote) to represent one character. Also the variable wordsCount is incremented without being initialized. You shoul...
64,701,244
64,701,812
Explain GPU NVIDIA execution time
I have written simple code to sum an array using GPU. I use 1D grid and blocks. Each block computes '2 times block size' elements of the array and reduce these elements to 1 value. Then host code will sum the reduced values of these blocks. Here is the code: __global__ void reduceBlksKernel1(int * in, int n, int * out)...
Let's consider this portion of your kernel where "most" of the work is being done: for (int stride = 1; stride < 2 * blockDim.x; stride *= 2) { if (threadIdx.x % stride == 0) { if (i + stride < n) { in[i] += in[i + stride]; } } __syncthreads(); } At each pass through the for-loo...
64,701,559
64,701,962
How to best solve "void foo( const T& t = T() )" when T==void
I have a function which has an option parameter of type T. template<typename T> void foo( const T& t = T() ) { t.stuff; } This was all fine but I now have a scenario where T becomes void. In this case I expected a no-operation empty function. The only workable solution I have requires three separate declarations a...
A simpler solution (in that there are only 2 overloads) would be something like this: template<typename T> void foo( const T& t = T() ) { t.stuff; } template<typename T> std::enable_if_t<std::is_void_v<T>> foo() {} // void foo(const T&); is the only viable overload for non-void T, // since std::enable_if_t SFINAE...
64,701,725
64,701,885
Can someone explain this bit wise operation
I am trying to understand what is happening in this bitwise operation that is used to set the size of a char array but I do not fully understand it. unsigned long maxParams = 2;// or some other value, I just chose 2 arbitrarily unsigned char m_uParamBitArray[(((maxParams) + ((8)-1)) & ~((8)-1))/8]; What size is this...
This counts the number of 8-bit chars needed to fit maxParams bits. +7 is to round up to the next multiple of 8. 0 -> 7 will round to 0 char 1 -> 8 will round to 1 char After division by 8. Which is done by /8 The bitwise and is to discard the last three bits before dividing by 8.
64,701,892
64,702,708
Are pragmas in a cpp of a static library consumed by that library's users?
After some testing, I feel that they are consumed by the library user even when placed in a cpp, but am not sure if I am doing something wrong. In Visual Studio, I have a static library StaticLib.lib with StaticLib.cpp. In that file I have the following code: #pragma comment(lib, "random.lib") When compiling StaticLib...
Strictly speaking, that #pragma is processed by compiler, while compiling your StaticLib.cpp file. The result of it, according to https://learn.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160, is: lib Places a library-search record in the object file. THAT is consumed by linker while building MyProgr...
64,701,918
64,702,109
I get the error C2440 but i don't know how to fix it, please can someone help me?
I keep getting the error C2440! It says 'return:' cannot convert from 'bool' to 'HCURSOR'. if (!addrSetCursor) return false; Thats where I get the error from and I think its giving me the error because of the code HCURSOR Discord::SetCursor(HCURSOR hCursor) { static uintptr_t addrSetCursor = NULL; ...
The function is expected to return HCURSOR, and false can't be converted to HCURSOR. Try return NULL instead of return false (assuming the caller of Discord::SetCursor can handle a NULL result). BTW the code on "GitHub" has return 0 at that location, so maybe you have an old version.
64,701,924
64,702,003
How to read data from a file then convert the data to an int and store them in a vector
I am trying to read in data from a text file, convert its contents into an integer, and finally store the integer values into a vector. However, I'm having an issue where the conversion skips the last number in the .txt file and seems to add a random value at the beginning of the vector when it goes to print it out. Fo...
The 3rd part of for loop (number = stoi(line) in this case) is executed after executing the loop body. Therefore, the 28156 is an indeterminate value of uninitialized non-static local variable and the last 4 is converted and discarded. You have to do conversion before using number like this: for(int number; getline...
64,702,087
64,709,595
Running function with ifstream and stringstream multiple times
Im fairly new to c++ and i would like to ask for suggestions / advice if there is a better / more optimal way to use a function calling ifstream and string stream. I have a document with the structure with 150 lines and 8 columns (a small subset with values simplified): 5.43e-08 0.0013 0.0105 0.013 0.026 0.068...
My suggestion: std::string Qual(double *a) { std::string line; char Qualities[] = {'1', '2', '3', '4' ,'5', '6', '7','8','\0'}; std::string Read_qual; std::srand(std::time(nullptr)); std::random_device rd; std::default_random_engine gen(rd()); std::discrete_distribution<> d({a[0],a[1],a[2],a[3],a[4],a...
64,702,626
64,702,874
How can I deallocate the last element of an array in C++?
I have a dynamically allocated array like this: a[1,2,3,*unallocated value*] which has 4 elements. I also have a length variable from which I know how long it is. I want to remove the last element in this array and set it to unallocated or uninitialize it somehow. I think something like this might work a[lenght-1]=*som...
To answer your question: How can I deallocate the last element of an array in C++? Allocate a new array that is one less in capacity. Copy all items, except for last, to the newly created array. Delete the original array. Example: int *p_original_array = new int[5]; int *p_shorter_array = new int[4]; //... std::co...
64,702,750
64,702,900
How will the Memory behave in this C++ program?
So I am not used to hardware-close programming, pointers and ram always were done for me but because I want to learn C++, I wanted to try a 2d array, that didn't work because of unknown size, so i decided to go with a 2d list. The problem I have now though is I have no idea how the program will behave, and before I can...
I recommend you pick up a good book on the basics of modern C++. C++ is a challenging language with a steep learning curve and long legacy. There is a lot to learn regarding object lifetimes, different types of construction and initialization, etc -- and it will be easier to start with a good book covering these topics...
64,702,760
64,702,862
Not able to set conditional Variable
in the below code I am waiting inside function waitingForWork() on a condition variable, butdoTheCleanUp() is never called. #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::un...
main() is locking the std::mutex and then calling waitingForWork() in the same thread, which tries to lock the std::mutex again. This is undefined behavior: If lock is called by a thread that already owns the mutex, the behavior is undefined: for example, the program may deadlock. An implementation that can detect th...
64,702,850
64,710,562
How to change the background color of the QTableWidget's vertical header?
I would like to change the colors of a QTableWidget. I am almost getting the result I like, but two areas in the vertical header remain white: Before writing this post I actually managed to color also the upper left corner, but not the other area. Here is the stylesheet I am using: QTableCornerButton::section { ba...
Finally found the answer myself: /*The top-left area is actually a button:*/ QTableCornerButton::section { background-color: #8b8d8e; } /*The lower part of the vertical header:*/ QHeaderView { background-color: #8b8d8e; } The original css I posted (QHeaderView::section) referred only to the header entries, no...
64,703,028
64,717,400
Can I use a bit of code as a parameter into a C++ template? (Without adding a function call)
I have several time sensitive variations on a function, so I hoped to write a single template and just alter the few lines of code that differ. As there is speed pressure I'm trying to avoid an extra function call. Previously with the preprocessor I would write: // code.inl void FUNC_NAME { a = 1; BIT_OF_CODE ...
why not: #include <stdio.h> int a, b, c; template <int N> void func(){ a = 1; if(N==1){ c = 3; #include "code1.inl" }else if(N==2){ c = 999; #include "code2.inl" } b = 2; } int main(){ printf("a=%d;b=%d;c=%d\n", a, b, c); func<1>(); printf("a=%d;b=%d;c=%d\n", a,...
64,703,124
64,703,209
Overloaded Double Equal operator is not working as expected
its a long doubly linked list code. but the problem is when i overload the operator, i think the function is not getting called. I have tried to put a debugging line printing here, but that does never show up. so i wanted if two of my Doubly Linked List are equal , it should print true. class Node { friend class Dl...
For starters the operator should be declared with the qualifier const bool operator==(const Dlist &Q) const; In this statement cout<<(x==y)<<endl; the used expression is a comparison of two pointers x and y declared like Dlist *x = new Dlist; Dlist *y = new Dlist; You need to compare the pointed objects like cout<<(...
64,703,505
64,703,560
Class type non-type template parameter initialization does not compile
I was under the impression that the following should become valid code under the new C++20 standard: struct Foo { int a, b; }; template<Foo> struct Bar {}; Bar<{.a=1, .b=2}> bar; Yet, gcc 10.2.0, with -std=c++20 set complains: could not convert ‘{1, 2}’ from ‘<brace-enclosed initializer list>’ to ‘Foo’ and Clang c...
This template-argument {.a=1, .b=2} is not allowed according to the grammar for a template-argument which only allows the following constructs: template-argument: constant-expression type-id id-expression A brace-init list is not any of the above constructs, it's actually an initializer and so it cannot be used as...
64,703,658
64,703,876
Convert a boring list of switch statements to something shorter and pleasing to look at?
I have a switch statement that runs like this switch (abc) { case FILE_0: lf = m_a->olf[0]; kf = m_a->pkf[0]; break; case FILE_1: lf = m_a->olf[1]; kf = m_a->pkf[1]; break; . . default: LOG_ERR << "Wrong type to check"; return 0; } This happens about 30...
Your code ain't that big to be sure about the intent, though, from what I can see in the snippet, you actually want to convert the symbolic value into an index. (Can I assume this is an enum?) What I would do is to move that code into a separate function: auto fileEnumToIndex(FileEnum file) { switch (file) { ...
64,703,696
64,703,775
Call a member function automatically in the end of a scope
Is there a way to call a class member function automatically in the end of a scope? Apparently if the class is instantiated within the same scope, clean() can be used in the destructor of it. The question is, can we achieve that if it is instantiated before the scope? In detail: class foo { public: void do_somethin...
Something like this. May not be exactly what you are looking for as it requires you do declare another variable at the start of the scope where you want the clean function to be called. class CleanFoo { public: CleanFoo(Foo& r) : ref(r) {} ~CleanFoo() { ref.clean(); } CleanFoo(const CleanFoo&) = delete; ...
64,703,761
64,739,008
Can you link static library directly in android application?
I am sorry maybe this is stupid what I am asking, but I have a question about linking static/shared libraries in android. I am creating a new C++ Native android studio project. After build, I open the apk file, and inside lib the folder there are placed libraries libnative-lib.so for every ABI. Size of APK is 3.580 KB...
You can't use native static libraries directly in Android apps. Android user space is basically a Java (or more precisely Dalvik VM). So all user-facing applications must be written in Java or Kotlin (which both compile to Dalvik bytecode). Static C/C++ libraries must be link in to a C/C++ executable or dynamic library...
64,703,905
64,776,483
QTooltip unwanted behaviour. Icon from button is partly visible as background in the tooltip
So, I think this picture speaks for itself. The tooltip should have black text color and lightgrey background. Ok, if you look closely, the background is lightgrey. But text is white and the most important, the icon for enabled button is shown. This should not be! Other default-buttons, without an icon, the tooltip is...
Now we are coming closer to the problem and the solution. By setting the button style after setting the application's style, the tooltip inherits the button's style - especially, it inherits the buttons border image, which is why you see the buttons's border image reflected in the tooltip. You can avoid this by setting...
64,704,154
64,704,193
Could use some clarity on my first time using std::distance
I have a vector variable called 'cache' (which stores strings, but I don't think that's needed info). I want to find the last occurrence of the variable 'latest', a string of course, in this vector 'cache'. I use std::find. Since I want to find the last occurrence instead of the first, I use reverse iterators, as shown...
You're trying to compute the distance between a reverse iterator and a regular iterator. The types of the two arguments to std::distance must be the same. Try this instead: size_t dist_from_begin = std::distance(find(cache.rbegin(), cache.rend(), latest), cache.rend());
64,704,227
64,706,344
Why is data validation only checking the first entry?
The following code should check all the entries if founds "badIndex" which is a non integer number, it must print it and also if it founds correct input which is for sure only digits entry, it should print all the digits. EX bad input: 123Y123 here Y is a bad input and it should print it along "badIndex". EX good input...
Here's a way you could do it: First, count the characters that are digit with std::isdigit, if it's not a digit, then print it. And if the count is equals to the length of the input, print the input is good and return true, else return false: bool isThisHuman(const std::string& userInput) { // Check the numbers of ...
64,704,564
64,709,551
WRL/C++ Detect multiple mouse buttons pressed simultaneously
I am coding in C++ targeting Windows WRL for UWP, and I need to process mouse input, at times consisting of left/right buttons being pressed simultaneously. My code only receives an event for the first mouse button pressed and the last mouse button released. So, if I press the right button followed by the left button,...
The CoreWindow.PointerPressed event is fired for the first mouse button pressing detected in the interaction session, and the event is not fired for the second mouse button pressing before the interaction session ends up. Similarly, the CoreWindow.PointerReleased event is fired for only when the last mouse button is re...
64,704,615
64,710,873
testthat (& Catch) complains in R CMD check that xml2 library is missing
I am using testthat to test my R package (https://github.com/beerda/hexmatrix). Recently, I started C++ testing: I have executed testthat::use_catch(), which should setup the package for unit testing with C++ Catch, and then I wrote some tests. The tests run correctly if executed by devtools::test(). However, if I try ...
The problem seems solved by adding xml2 into Suggests section of the DESCRIPTION file of the package.
64,704,642
64,706,459
Install tcmalloc from source to link without bazel?
I'd like to install tcmalloc from source. I'm on centos8. I'd install from yum but don't see any google-perf or gperf or anything of the sort available. (I did do yum check-update.) The instructions on the tcmalloc github sure are simple. Install bazel (check). Then run bazel test //tcmalloc/... in the <projectroot>/tc...
Yes @dewaffled had the answer in the comments. Here is what I used. yum install -y epel-release && yum install -y gperftools.x86_64 Or you can use the gperftools-devel that @dewaffled mentioned.
64,704,878
65,525,809
Crash when initializing vector with one element using brace initialization in VS2019
The following code crashes deep inside the standard library: #include <set> #include <vector> struct Parent { std::set<int> v; }; struct Child : public Parent { Child() = default; }; int main() { std::vector<Child> v{ {} }; } but if the constructor is explicitly declared (without = default), it doesn't ...
I looked up into the code and it really caused to happen in Visual Studio 16.7.7. Now it seems to be working fine in both in VS 16.8.3 and g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 (tried with -std=c++14), it was a bug which seems to be fixed by Microsoft team in the recent update.
64,705,366
64,705,415
Why c++ allows default template argument that can never be used?
If I have a function template that has default argument for its template parameter and that function takes a non-default parameter of the type parameter then what's the point in the language to allow that default argument that'll never be used? : template <class T = int> void foo(T x){cout << x << endl;} int main() { ...
But it can be used. Here's an example. auto* foo_ptr = &foo<>; // The default template argument is used. A function call expression is not the only context where a function template's arguments need to be figured out.
64,705,493
64,705,607
Perfect forwarding vs const reference
I have a simple question I do not understand int solution(int&& a, int&& b); int main() { int a, b; std::cin >> a >> b; std::cout << solution(std::forward<int>(a), std::forward<int>(b)) << std::endl; } int solution(int&& a, int&& b) { return a + b; } I am a Java developer and started to re-learn C++ ...
Does it really give the rvalue reference so no copy of argument is created? Yes. If that is right why is it better than writing just const int&?(I do not copy anything here either. It isn't. In fact, for a simple int, you shouldn't even be passing by reference. They're small enough that a nice simple pass-by-copy i...
64,705,831
64,705,914
Win32 C++17 - Pointer returned by system_category().message().c_str() dies immediately...why?
Consider the following code: #include <windows.h> #include <strsafe.h> int main() { // ...many lines of code not related to the problem auto errMsg = system_category().message(GetLastError()).c_str(); char buf[MAX_PATH]; // Throws an access violation exception StringCchPrintfA(buf, MAX_PATH, "Fun...
Yes, you have the same issue as the other question. In this case, message() is returning a temporary std::string object by value, which goes out of scope and is destroyed on the ; at the end of the statement that creates it. You are taking a pointer to the temporary's internal data, then the temporary is destroyed bef...
64,705,932
64,744,752
Wording of GCC's error message when calling lvalue-ref qualified member function on temporary object
The following code does not compile, expectedly: struct A { void doWork() & {} }; int main() { A{}.doWork(); } My understanding is that the temporary A{} cannot bind to the &-qualified member function doWork, and this seems in line with this excerpt from cppreference (my italic): […] member function of class ...
This is just a case of a suboptimally worded error message in GCC. My guess would be that in GCC's implementation, diagnosing a mismatch between differing ref-qualifiers shares some code with diagnosing a mismatch between const and non-const, and they reused the same error message. I would encourage you to file a GCC b...
64,706,266
64,920,113
Unable to set up SDL2 to run with audio (alsa) on linux ubuntu 20.04 using conan
Depending on what I do I either get "No such audio device" if I leave determining my audio device up to SDL2 or I get Failed loading libasound.a: /home/aypahyo/.conan/data/libalsa/1.2.4///package/d48130e0dd76369b1338deb3b2372c5a649f9f2d/lib/libasound.a: invalid ELF header when I set SDL_AUDIODRIVER=alsa. (The error...
The Issue is solved and the traces in the question show how. Ultimately were several layered problems. libalsa/1.2.4 needed a fix for shared libraries and I had to add that option to the conan file. I had to plug my boxes in because the default device was a channel I do not normally use Ultimately I will need to set u...
64,706,638
64,706,788
Arduino Uno is making errors when doing calculations
So I have been working with my Arduino to make a calculator, and thats what I did. Although, it did not work as I expected it to. When I input simple calculations, it spits it out fine, but when I put in complicated calculations, it goes berserk! It tells me that 9999 * 9 is about -14554 or something like that. Here is...
This does look like an overflow on a 16-bit signed integer which is what the Arduino Uno uses internally. Numbers > 32767 cannot be represented with this. It's not an error, it's a limitation of that hardware, it's just 16-bit. You need to use multiple int values in order to hold anything larger.
64,706,869
64,706,938
C++ Passing an Object to Another Object From Another Class
I am trying to write this program using base classes and derived classes where there is a truck with a maximum capacity of 8 tons. Then this truck is loaded with 1.5 tons of apple and then loaded with 0.5 tons of kiwi. This would then diminish the amount of tons remaining to 6.5 when the apples are loaded and then to ...
First, you need to make your getAmount() function virtual: class Cargo{ public: double c = 0; virtual double getAmount(){ return c; } }; Then, your derived classes will override the getAmount() function with their version. Without the virtual keyword, if your function accepts a parameter of type Ca...
64,707,309
64,724,545
Modifying a C++ array in main() from Lua without extra allocation
I am sketching a small C++ program that will pass arrays to Lua and have them modified there, where I intend to have a lua script read in the program so I can modify it without needing to recompile the program My first obstacle is to ensure Lua is able to modify arrays already allocated instead of having them allocated...
I recommend you create a userdata that exposes the arrays via __index and __newindex, something like this (written as a C and C++ polyglot like Lua itself): #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif #include <lua5.3/lua.h> #include <lua5.3/lauxlib.h> #ifdef __cplusplus } #endif str...
64,707,382
64,869,759
How can I get SPI SCK line to idle low without wasting current with a pulldown resistor?
I am using the STM32L475 MCU and am using SPI to communicate with an SD card. When I configure the SPI SCK GPIO pin, I configure it as Alternate Function SPI in PushPull mode. I set the ClockPolarity to be idle low, which would make me think that the SCK line would remain low when inactive, but this is not the case. In...
CPOL is the 1st bit of SPIx_CR1, controlling the idle state of CLK pin of a specific SPI. So if you want to remain SCK pin in low state when idle, try: SPI1->CR1 &= 0xFFFE; You can also configure the clock polarity in STM32CubeMX: screenshot. I haven't try these by myself, but according to the official document, these...
64,707,401
64,707,439
Define norm as member function of vector class in C++
I'm trying to write my own vector class in C++.In particular, I want to implement the norm as a member function. The following classic snippet of code is what I did: #include <iostream> #include <cmath> template <typename T> class vector{ private: T* elem; std::size_t _size; public: vector(const std::size_...
You are declaring norm() as a friend function, so it is not actually a member of the vector class itself. You are telling the compiler that some external non-member function T norm() is a friend of vector so that it can access vector's private members. But then you don't actually define such a T norm() function! The ...
64,707,410
64,707,441
Function that returns a pointer in C++
I've started learning about pointers and I ended up with a question over functions and pointers. I created a simple function that should return the address/pointer of an Integer type. However, after printing the address using "&" it differs from what the function returns me. What am I missing here? int* address_ofInt(i...
int* address_ofInt(int a) { This is called "passing by value" in C++. This means that whatever the caller passes, as a parameter to the function, effectively a copy is made, and that's what this a is. This function can modify this a, and it will have no effect on the original parameter, since it's just a copy. This a ...
64,707,759
64,707,805
linker error 2005 seemingly caused by a constructor
I keep getting this linker error below and it seems to be caused by the constructor below /*Card.h*/ #ifndef Card_H #define Card_H #pragma once #include <iostream> using namespace std; #include <cassert> //for assert() #include <string> #include <time.h> using namespace std; /*Card.h*/ enum color { club, diamond, h...
In your header file: Card::Card(color c, int v) { This is a definion of Card's constructor. This means that every translation unit (a C++ source file), that #includes this header ends up defining this constructor. Remember that an #include of a header file is exactly equivalent to logically inserting the contents of t...
64,707,811
64,708,086
The variable redeclared in the outermost block of a substatement
#include <iostream> int main(){ int b = 2; if(int a = 0){ // #condition }else if(b == 2){ int a; //#1 } } The above code can be compiled in both gcc and clang. However, according to what the relevant rules say, this code should be ill-formed. The rules are: stmt.stmt#3 A name introduced by a declaratio...
The statement in stmt.stmt#stmt.pre-5 explicitly says: [Note 2: A name introduced in a selection-statement or iteration-statement outside of any substatement is in scope from its point of declaration until the end of the statement's substatements. Such a name cannot be redeclared in the outermost block of any of the s...
64,708,463
64,708,544
What is the difference between functions in Python and functions in C++?
What i basically mean to ask is, in python, a function is defined and when the program is run, it does not return anything as long as we don't call it. I recently started learning C++, and here i saw that a function is defined using int main() and doesnt have to be called in order to execute the block of code within th...
In C/C++, the main() function is the program entry point. In python their is no such main() functions which are the program entry point and don't automatically run unless they are called. But the behaviour cam be implemented. def main(): # Your code if __name__ == '__main__': main() Then main() will run if script...
64,708,587
64,711,437
Is explicitly calling destructors from constructors bad practice in C++?
I usually don't call destructors explicitly. But I'm designing TCP server class, which looks something like this: class Server { public: Server() { try { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) throw std::runtime_error("WSAStartup function failed.")...
What's recommended way of designing this? I would say: even more RAII. Something like: class WSARaii { public: WSARaii() { if (WSAStartup(MAKEWORD(2, 2), &wsaData)) throw std::runtime_error("WSAStartup function failed."); } ~WSARaii() { WSACleanup(); } WSARaii(c...
64,708,867
64,708,999
what are the constraints for std::ranges::make_heap?
The following code works well with gcc: struct S { int i, j; auto operator<(const S& s) const { return i < s.i; }; }; std::vector<S> v; std::make_heap(v.begin(), v.end()); But when I switch to C++20's range algorithm: std::ranges::make_heap(v); I got this compiler error: source>:14:27: error: no match for c...
std::ranges::make_heap uses std::ranges::less, which has a constraint: Unlike std::less, std::ranges::less requires all six comparison operators <, <=, >, >=, == and != to be valid (via the totally_ordered_with constraint). Your type S does not have an equality operator; the spaceship operator only provides the other...
64,708,992
64,709,258
Question regarding race conditions while multithreading
So I'm reading through a book an in this chapter that goes over multithreading and concurrency they gave me a question that does not really make sense to me. I'm suppose to create 3 functions with param x that simply calculates x * x; one using mutex, one using atomic types, and one using neither. And create 3 global v...
One problem with race conditions (and with undefined behavior in general) is that their presence doesn't guarantee that your program will behave incorrectly. Rather, undefined behavior only voids the guarantee that your program will behave according to rules of the C++ language spec. That can make undefined behavior ...
64,709,028
64,710,517
how android studio gradle compile external cpp sources?
It's easy to compile c++ sources to xxx.so following Android Template. But it's weird when I move the cpp folder and edit externalNativeBuild. step1: When I move cpp folder in another place, and modify externalNativeBuild.cmake.path, it works fine.(sync -> clean project -> rebuild project) step2: When I move cpp folder...
I deleted the build folder and rebuild, but error occured also. Try to delete app/.cxx folder, it might help. Also sometimes Build->Rebuild Project helps.
64,709,107
64,721,363
How to calculate the betweenness centrality with weights
I'm trying to calculate the betweenness centrality of a city street network, using the Edge length property as weight, but it doesn't seem to work. When I run without weights it gives the following results: min: 0 mean: -nan(ind) max: inf stddev: -nan(ind) and with weights: min: 0 mean: 0 max: 0 stddev: 0 Any help wo...
Well, that's awkward, turns out the code is right, my graph was somehow wrong, I regenerated it and it has worked. Edit 1 After seeing the time and amount of memory it takes to load the graph, I was able to find the problem, after I made some operations on the nodes, I was inserting them in the same graph, instead of a...
64,709,153
64,716,664
The redeclaration in a statement after case label inside a switch statement
Consider this example #include <iostream> int main(){ switch(int a = 1){ //#condition case 1: switch(int a = 2){} case 2: switch(int a = 2){} } } why the redeclarations of a are well-formed in this example? According to the following rule: basic.scope.block#3 Names declared in the init-state...
The real question is the meaning of in here. Anything between the { and } that delimit the switch is of course in that “outermost block”, but the use of “outermost” clearly implies that we’re not supposed to consider portions of the program that are (also) inside a nested block. The simplest way to reach that interpr...
64,709,195
65,221,222
C++ fixed-capacity associate container
I am looking for a container like std::unordered_map that does not use any dynamic allocation. I believe this would be the case for any associate container with a fixed number of keys, or even keys that have to be chosen at compile time. I am not looking for a constexpr or compile time hash map because I would like to ...
I was able to find a library with this functionality: https://github.com/serge-sans-paille/frozen It allows for constexpr and constinit ordered and unordered maps with (newly added by me) the ability to update values in runtime.
64,709,245
64,709,290
Compilation error in auto keyword in C++11
I know that the use of auto keyword can automatically deduce the type of the variable from the Rvalue. Then why does the following function snippet in my code have a compilation error? auto getName(auto str = "John Doe") { return str; } The compilation error is 'auto' not allowed in function prototype. I googled a...
You can use auto in a lambda expression, but not a normal function. To get the same effect, you can define a function template instead: template <class T> T getname(T input = "John Doe") { return input; } But be aware that this default value for the argument will only work for types that can actually be initialize...
64,709,438
64,709,496
Unable to find height of BST
Using recursion I am trying to find height of tree but the output seems wrong. Any errors? #include <iostream> struct node{ int data; node* left, *right; }; node* getNode(int item){ node* new_node = new node; new_node->data = item; new_node->left = new_node->right = nullptr; return new_node; }...
Right away, this code: int main() { node* root; // <-- uninitialized root = insert(root, 40); // <-- Using an uninitialized pointer //... } is faulty. The root is an uninitialized pointer, and passing that uninitialized pointer to insert will invoke undefined behavior. The probable fix is to simply do: no...
64,709,783
64,709,822
convert base class unique_ptr to derived class unique_ptr
I need to convert my base class unique_ptr to a derived class unique_ptr so that I can access some of the functions of the derived class. The code I have throws error. What is going on wrong here? #include <iostream> #include <memory> class Base {}; class Derived : public Base { public: Derived(int x):_x(x){} ...
The problem is that dynamic_cast can't be used on non-polymorphic types. Depending on your intent, you could make Base polymorphic, e.g. class Base { public: virtual ~Base() {} }; LIVE Or you can use static_cast instead, if you're sure about the conversion result. LIVE
64,710,288
64,713,796
How to access the raw widget pixels rendered on the screen?
I am trying to extract the pixel data from every frame, but when I try to get the pixmap it returns null. I thought that the pixmap would return the actual pixel data of what was on the screen, similar to glReadPixels but I think I am mistaken. I think it's meant to access the pixel map of the result of setPixmap. Is t...
Cause QPixmap: The QPixmap class is an off-screen image representation that can be used as a paint device In other words, it is a drawing canvas and, as any other canvas, if you have not drawn on it, it would be empty. On the other hand QLabel serves as a view for the pixmap, not as its content, and when you try to a...
64,710,582
64,710,694
Error using include sys/resource.h with Windows 10 C++
I have been using VS code on macOS for a while and switched to windows 10, I tried running a code from my mac but it's giving me this error that I don't get using mac. I installed LLVM not sure if it would help. #Include <sys/resource.h> My compiler path currently is set to: "compilerPath": "C:/Program Files (x86)/Mic...
sys/resource.h is a POSIX header file, that's why your system is not able to find it anywhere on windows. If you still want to use it then you can either either use a virtual machine or install cygwin on your system.
64,711,044
64,712,105
Benefit of printing values from an array in ascending order by selecting?
I read the tutorial regarding arrange a number of array in ascending order and understood the idea https://www.includehelp.com/cpp-programs/sort-an-array-in-ascending-order.aspx . However, now I'm thinking of other way to perform the operation. Wonder will the idea below works? The method will be using while loop and c...
What you've described is a variant of what's normally called a "selection sort". It's pretty well known. It does work, but there are many sorting algorithms that work--and while there are a few sorting algorithms that are generally less efficient, it's still one of the least efficient around. Selection sort is typicall...
64,711,069
64,711,139
why it does not return anything?
I'm doing a programming exercise about converting Fahrenheit to Celsius [C = 5/9 * (F-32)] with some conditions: create a function toCelsiusByReference which takes a temperature by reference, and returns a bool so : bool toCelsiusByReference(float &temperature); change the parameter from Fahrenheit to the equivalent ...
Basic knowledge: you need to use the returned value somehow. ... if (toCelsiusByReference(temperature)) { cout << "above 32°F\n"; } else { cout << "below 32°F\n"; } cout << "Converted temperature: " << temperature << " °C\n"; ...
64,711,819
64,711,901
c++ duplicate class definition in different source file
This is the minimum reproducible code, the code no namespace and header file,The test can compile and run normally, but the results obtained do not match expectations. test-a.cc class TestStamp { public: TestStamp(){} inline static std::string Name = "foo-stamp-1"; std::string GetStampName() const { retur...
I don’t know if this is correct. One Definition Rule states that all definitions of a class and inline variable must be identical across all translation units. Your definitions differ, which violates the language rule. Therefore the program is ill-formed. why doesn’t it cause a compilation error? Language implement...
64,711,991
64,712,278
C++: get int from any place of vector<byte>
I have big enough std::vector<byte> source and I need to get four bytes from any offset in vector (for example, 10-13 bytes) and convert it to integer. int ByteVector2Int(std::vector &source, int offset) { return (source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24); } This ...
Use memcpy. You might be tempted to use reinterpret_cast, but then you can easily end up with undefined behavior (for instance due to alignment issues). Also, pass a vector by a const reference: int f(const std::vector<std::byte>& v, size_t n) { int temp; memcpy(&temp, v.data() + n, sizeof(int)); return tem...
64,712,273
64,712,625
Is it possible to use a depth renderbuffer with cubemap color attachment?
I am trying to create a Framebuffer, with a GL_TEXTURE_CUBE_MAP as the Color Attachment, and GL_DEPTH24_STENCIL8 as the Depth Attachment for the Framebuffer's Renderbuffer. I was confident that this would work, as it did for a Framebuffer with a GL_TEXTURE_2D Color Attachment and a Renderbuffer with GL_DEPTH24_STENCIL8...
No. You have to create a GL_TEXTURE_CUBE_MAPtexture with the format GL_DEPTH24_STENCIL8 for the depth buffer attachment. For instance: glGenFramebuffers(5, &FBO[0]); glGenTextures(5, &FBO_texture[0]); glGenTextures(5, &FBO_depth_texture[0]); for (unsigned int i = 0; i < 5; i++) { glBindTexture(GL_TEXTURE_CUBE_MAP,...
64,712,281
64,712,469
No output from glDrawElements when I try to take color from vbo
I am new to OpenGL and trying to extend my current code which displays a square using colour provided as a uniform variable to the code that will display square on the basis of colour given in vbo. int main(int argc, char **argv) { //! The pointer to the GLFW window GLFWwindow *window; //! Initialize GLFW ...
You cannot set a fragment shader input directly. in_color needs to be a vertex shader input (attribute). Pass the vertex shader input to the fragment shader. For instance: Vertex shader #version 330 core layout(location = 0) in vec4 position; layout(location = 1) in vec4 in_color; out vec4 vert_color; void main() { ...
64,712,892
64,714,179
Mimic std::bind_front in c++17 for calling member functions
Is it somehow possible to easily mimic std::bind_front in C++17 ? (just for member function wrapping is fine) I took a look at implementation in c++20 aiming to copy but it seems its very much implementation specific indeed. I'm thinking a lambda wrapper or template function/object might work? (Performance is not an is...
This can be a starting point template<typename F, typename ...FrontArgs> struct bindfronthelper { bindfronthelper(F f, FrontArgs&&...args) : mF{std::move(f)} , mFrontArg{std::forward<FrontArgs>(args)...} {} template<typename ...BackArgs> auto operator()(BackArgs&&...args) const { ...
64,712,927
64,713,113
How does the subtraction of two iterators denote the index of a vector item in C++?
In a blogpost of GeeksForGeeks, subtraction of two iterators has been used to denote the index of a vector. Link of that post: std::find in C++ I have also seen a related answer in stackoverflow: How to convert vector iterator to int in C++ But it didn't describe the mechanism with a good example, so I am confused abou...
Subtracting one RandomAccessIterator from another gives the distance between them, because that's what operator- is defined to do for random access iterators. If you subtract begin() from another iterator, you get the distance from the beginning of the container to the second iterator, which is naturally the same value...
64,713,512
64,714,854
C++ usage of constexpr with lambda expression
I was reading book C++17 - The Complete Guide and in the section 6.1 on constexpr lambda the author gives two examples: auto squared1 = [](auto val) constexpr { // example 1. compile-time lambda calls return val * val; }; and constexpr auto squared2 = [](auto val) { // example 2. compile-time initialization return...
The thing is, that an auto-declared object does not adopt the constexpr'ness of its initializing expression, only its type; and constexpr is not part of that type. See: Why does `auto` not adopt the constexpr'ness of its initializing expression? So, suppose I had: auto five_squared = 25; the value 25 is very much cons...
64,714,211
64,714,363
Incomplete type error when compiled with g++
I am trying to execute following code using g++ and getting incomplete type error #include <stdio.h> struct try_main{ union{ struct try_inner_one{ int fl; float g; }one; struct try_inner_two{ char a; }two; }un; int chk; }; void func(struct try_inner_one o){ printf("%d\n",o.fl)...
C and C++ have different scoping rules. The full name of the type in C++ isn’t struct try_inner_one, since the type definition is nested inside the unnamed union inside try_main.1 If you want to write code that works equally in both C and C++, pull the type definition to the top level: struct try_inner_one { int fl; ...
64,715,045
64,721,729
Sending string through queue in Freertos
I want to create a task with push button and the task sends a string to a queue and creates another task (this can also be separate task with lower priority) which reads the queue and blink led if its variable is same with the string in the queue. Otherwise system should stay in the idle mode. Im quite new with freerto...
Nothing is happening because the program is likely executing too quickly for things to work. When your program starts it initializes everything in a fraction of a second, and if the button is not pressed then nothing happens. Then your main loop does nothing. At a minimum, you should put the button watching in a task, ...
64,715,254
64,715,286
Using push_back vs at in a vector in C++
Have a doubt in using vectors in C++. it is to do with the push_back method in the vector. For the first program, i have used push_back to insert elements into the vector. For the second program, i have used at( ) to insert elements into the vector. #include <iostream> #include <vector> #include <string> using namespac...
The issue in this loop: for (unsigned i=0; i<myvector.size(); i++) { myvector.push_back("hi"); //Note: using push_back here. } is that if you ever enter the loop, i.e. myvector is not initially empty, then each push_back will increase the size of the vector. Since i is incremented once each time in the loop, it w...
64,715,888
64,717,414
getting error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"
This is my first post on Stackoverflow and I hope I will find a solution to my problem. This is main of the class song, where it gets an metadata ( length, year, genre). I think the problem is coming from the function enumToString but I'm not sure :/ Song::Song(Artist artist, string title) { an_artist = &artist; ...
Note: I am posting the answer here so that one does not have to go through the comments in order to find it. In the function "addSong" from artist.cpp: void Artist::addSong(Song *song) { the_songs.push_back(song); song->artist(*this); // line I will be referencing } You are passing the object's "this" pointer....
64,716,180
64,716,524
C++ dll Pinvoke function with function pointer struct in parameter
I'm working on a C# code which uses a C++ dll One function of the C++ dll takes a struct of 3 function pointers in parameter, I dont know how to manage it any tips or topics ? I tried this but this doesnt work : [StructLayout(LayoutKind.Sequential)] public class DisplayCallBacks { [MarshalAs(UnmanagedType.FunctionP...
Use IntPtr as the type for the function pointers. Then you can declare a delegate. Here is an example from code I wrote: [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void PrintLogDelegate(string msg); PrintLogDelegate pld; System.Runtime.InteropServices.GCHandle callbackPrintLog; IntPtr ipCBPrintLog = ...
64,716,316
64,717,335
What is it useful for to have class type attributes in a C++ class?
I have inherited a software in C++. The software contains below given code which is hard for understanding to me. DeviceAlarms.h class DeviceAlarms { public: class DetectedAlarms { AlarmOVERCURRENT_PHASE_A alarm001; AlarmOVERCURRENT_PHASE_B alarm002; AlarmOVERCURRENT_PHASE_C alarm003;...
This: class DeviceAlarms { public: class DetectedAlarms { AlarmOVERCURRENT_PHASE_A alarm001; AlarmOVERCURRENT_PHASE_B alarm002; AlarmOVERCURRENT_PHASE_C alarm003; AlarmOVERVOLTAGE alarm004; AlarmOVERTEMPERATURE alarm005; } detectedAlarms; }; Is mostl...
64,717,768
64,717,818
C++ callback v.s. vector return in a data structure traversal method?
In the following example, I've implemented two ways of traversing a data structure. One uses a result vector which implies copies while the other uses a callback. Which of the two approaches is usually better to use in typical C++ applications? Said differently, does one solution have flaws/drawbacks? #include <iostrea...
In this case I would use the callback approach, but I would remove the std::function and replace it with a template type. std::function uses type erasure and that requires dynamic allocation and a little bit of overhead. A function template like template<typename Callback> void query(T query, const Callback& cb) { ...
64,718,600
64,727,524
Cleanest way to avoid branching with templates
I have a cuda kernel which takes some bool template arguments which help to explicitly optimize out unused sections of the kernel. I'm wondering if there is a cleaner/more compact way of instantiating the kernel call than my solution below. Device Template template <bool pred1, bool pred2> __global__ void foo(args) { ...
Well there are ways but they require more lines than your current implementation. And I'm not sure if the following implementation improves readability more than just putting your 'unclean' section in a separate function. The following code is probably longer than it will be for you because I implemented two ways (call...
64,719,130
64,719,544
Boost Spirit : can't manage to have the alternative operator working as I expect
I can not manage to have the spirit alternative parser working (or let'say do what I expect). Here is my MCVE #include <string> #include <iostream> #include <boost/variant.hpp> #include <boost/spirit/include/qi_parse.hpp> #include <boost/spirit/include/qi.hpp> using namespace boost::spirit; namespace charset = boost:...
operator > is higher in C++ Operator Precedence table than operator | hence parenthesis are needed: orParse = qi::omit[qi::lit('{')] > (parseString | parseInt) > '}'; // here ^ and here ^ Result: <alternative parser> <try>{string: "foo"}</try> <string parser> <try>s...
64,719,671
64,719,772
If `v` is a class, can `v + 1 - 1` be optimized by compiler to `v`?
Consider the following code: struct S{ int a, b; S() : a(0), b(10) {} }; S operator + (const S& v, int n){ S r = v; r.a += n; return r; } S operator - (const S& v, int n){ S r = v; r.b -= n; return r; } S v = S() + 1 - 1; Is it possible that S() + 1 - 1 will be optimized to S() ? How ...
No, a compiler is not allowed to optimize S() + 1 - 1 into S() because those two expressions are not equivalent for your class S. Even though it might be non-idiomatic, it's completely valid for S to be written as you have done, in a way that operator+ and operator- don't cancel each other out (in your case, by modif...
64,719,818
64,720,715
Formalizing a concept with conditional requirements
A benefit of concepts in C++20 is that this feature allows, and encourages, programmers to specify (using the C++ language itself) information about their interfaces that formerly had to be in human-only documentation, in a natural language like English. For example, I have a generic algorithm, let's call it template<i...
Well, that was strangely easy. #include <concepts> #include <cstddef> #include <type_traits> template<int N, template<int> class X> concept Fooable = requires(X<N> a, int i) { a[i]; } && ( N == 1 || requires(X<N> a) { a.reduce(); } ); template<int N, template<int> class X> requires Fooable<N, X> void foo(X<N>...
64,719,900
64,720,826
How to send a file by a zmq multipart message?
I'm trying to send a video using a ZeroMQ infrastructure and I split the video into chunks to send it. When I do it and put the video into a vector to send it through zmq::send_multipart I get a very high usage of RAM memory and so times later I get a segmentation fault error. My headache is that when I comment on the ...
An attempt to move all data via multipart-message does collect all data into one immense BLOB, plus add duplicate O/S-level transport-class specific buffers and the most probable result is a crash. Send individual blocks of the video-BLOB as individual simple-message payloads and reconstruct the BLOB ( best via indexed...
64,719,981
64,720,121
using cin.clear() to remove the fail state in an exception
So I'm trying to understand why cin.clear is getting rid of the first word instead of the second if a first and last name are entered, and a number for age. for instance, if the input is: Lee 18 Lua 21 Mary Beth 19 Stu 33 -1 then shouldn't the "Beth" in "Mary Beth 19" be skipped? Why is it clearing...
For the input line Mary Beth 19 the first cin >> inputName; will read Mary into inputName. Then cin >> age; attempts to parse Beth as an integer, but it will fail and thrown an exception. However, and here's the important part: The input isn't discarded! Instead the input read pointer is unmodified, it will still be...
64,720,293
64,720,480
Do I need to free the memory in this case somehow?
I have a pointer State *state; which is a class that other states inherit from. And I do state = new GameState; Do I need to free the memory here somehow, if I change what the object state points to from GameState to something else?
If what you mean is that State* state does NOT own the object you will need to do something like this: // create states State* game_state = new GameState(); State* menu_state = new MenuState(); // set current state State* state = game_state; // ... do somethings ... // delete states del...
64,720,310
64,720,311
What normative text governs that a friend defined in-class can be found by non-ADL lookup only once (re-)declared in the enclosing namespace?
All standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS. A function declared as a friend can also be defined at the friend declaration as follows: #include <iostream> namespace a { struct A { // Definition of 'a::foo()' friend void foo() { std::cout << __PRETTY_FUNCTION__; ...
All standard references below, unless explicitly noted otherwise, refer to N4659: March 2017 post-Kona working draft/C++17 DIS. Friend declarations (definition or not) does not introduce new names into the enclosing namespace [class.friend]/6 governs the scope of a "hidden friend" (only declared and defined at its fri...
64,720,668
64,721,007
Queue not holding the updated data
I have a simple multi threaded program where one thread is filling the queue, while the other is consuming the queue, I know this example program is buggy, which is closely trying to replicate my application. I don't have an explanation as to why it's behaving this way, I expect the output to be popping 1 , 2 , etc #in...
You have two variables named svc_resp in main. The second one (at the bottom of the while loop) will create and briefly own a shared_ptr<A> before it is immediately destroyed. This accounts for the constructed and destructed outputs with the increasing numbers. The first svc_resp variable, declared before the while loo...
64,720,994
64,721,088
class array default setting c++
I can't find any information on whether or not you can set default values for arrays created via a class and/or any syntax for arrays made via classes beyond mere creation. Please help. // strings #include <string> //normal setup #include <iostream> #include <string> using namespace std; // multi array setup cla...
You can value-initialize all of the elements of the array using this syntax, eg: recordtype listof[11](); Which, in your example, will default-construct all of the string fields, and set all of the char fields to 0. Though, in this case, it would be better to give recordtype a default constructor to initialize its mem...
64,721,460
64,721,776
How to delete a dynamic array with my function class?
Again with templates. Now I'm trying to write a Deleter function class so that it works similar to the language one delete. Here is my attempt: class Deleter { public: template <typename T> void operator()(T*) const; }; template <typename T> void Deleter::operator()(T* ptr) const { std::cout << "freeing me...
You cannot use delete with memory allocated with new[], and vice versa using delete[] with memory allocated with new. This is exactly why std::unique_ptr and std::shared_ptr have specializations to decide when to use delete[] vs delete for array and non-array memory, respectively (via the std::default_delete template)....
64,721,525
64,721,613
Overloading subscript operator not working as expected
I have a String struct that I overloaded the subscript operator on. But it doesn't seem to work. //my_string.h struct String { char* Text; uint64 Length; char& operator[](int32 index); } //my_string.cpp char& String::operator[](int32 index) { ASSERT(index >= 0); return Text[index]; } //main.cp...
The compiler issued an error because in this statement char c = test[0]; the expression test[0] has the type String. In this declaration String* test = string_create("Hello world"); you declared a pointer instead of an object of the type String. If it is not a typo then in this case you have to write char c = ( *test...
64,721,903
64,777,263
Qmake cannot find my Android libraries because they have the QT_ARCH variable appended to the name
I have a Qt application that builds correctly for desktop. All of my libraries are dynamically linked. I'm currently building on Ubuntu, so they end up looking like "libMyLibName1.so", but building for Android outputs a library that looks like "libMyLibName1_armeabi-v7a.so", which is the original name suffixed with the...
Append the QT_ARCH variable to the library name in the .pri file when building on Android. #MyLibName1.pri INCLUDEPATH += $$PWD DEPENDPATH += $$PWD android: LIBS += -L$$OUT_PWD/../../libs -lMyLibName1_$${QT_ARCH} else: LIBS += -L$$OUT_PWD/../../libs -lMyLibName1
64,722,146
64,722,183
string.compare() function not comparing the correct string
Unsure why, but when I am using string::compare() in my code, it is printing the opposing switch statement, rather than the one it is supposed to. cout<<lexeme << " "; if(lexeme.compare("begin")){ item = LexItem(BEGIN, "begin", linenum); return item; } if(lexeme.compare("print")){ item = LexItem(PRINT, "print"...
std::string::compare() returns an int, where the value is: negative if *this appears before the character sequence specified by the arguments, in lexicographical order zero if both character sequences compare equivalent positive value if *this appears after the character sequence specified by the arguments, in lexi...
64,722,407
64,722,436
C++ bool template parameter and compile time if
I have the following function template <bool c> void func() { ... if (c) { // do something } else { // do something else } } This function is to be used several time inside a loop: for (...) { func<true>(); } I would like to know it the if inside func is done compile-time, run-time...
The compiler may or may not optimize your code since it knows what c is at compile time. The only way to actually know would be to look at the generated assembly code to see if the branch was removed or not. That said, C++17 introduced constexpr if which is guaranteed to evaluate the condition at compile time and disc...
64,722,464
64,722,961
C++ - Unable to call inline std::cerr inside of a ternary operator
I'm trying to make a very simple setter method that checks if the start value isn't higher than the end value before setting it. This is the basic code: if (start <= this->end) { this->start = start; } else { cerr << "Start cannot be higher than end." << endl; } I tried simplifying the method by using an inlin...
A ternary conditional expression a ? b : c is an expression and is therefore not equivalent to if (a) { b } else { c }. Because it's an expression, it must have a type (and, if that type is not void, it has a value too). This is why you can put a ternary conditional on the right-hand side of an assignment (or even the ...
64,722,525
64,742,920
Arduino print string via serial
I was coding a while when I noticed that arduino when it print data to "console", it print it perfectly, but, when I try to copy it, only copyes part of string. Is like there are invisible characters. I can't paste the output because when I try to copy it, it don't copy full. What I was trying to do is to get data from...
Mifare cards have a limitation of 16 bytes x block and you can't write on protected blocks like 0, 3, 6 etc.. The error was that I was writing 17 bytes instead of 16 bytes and that returns invisible / error charaters that can't be displayed
64,722,976
64,723,049
Putting spaces before two cout statement iterations that is displayed via a recursive function
Essentially I am making some recursive calls where it increments and decrements a number that is displayed via cout statements. There are two cout statement iterations(so four of one cout statement, and four of the other) that display this. The first one increments the number from 1 to 4, and the second one decrements ...
Call this method from Waswritten void writeSpaces(int spaceCount){ for(int i=0;i<spaceCount;i++){ cout<<" "; } } before each cout writeSpaces(count);
64,723,055
64,723,080
Passing a pointer to a function with reference parameter
Usually, this is caught by the compiler. But using a cast to a function pointer we can manage to do this. I may not have worded it properly, here is an example to better illustrate my question: void printintp(int *ip) { printf("pointer = %p\n", ip); printf("*pointer = %d\n", *ip); } void printint(int &i) { ...
Is this undefined behavior that just happens to work on my implementation? Yes. Most compilers implement a reference using a pointer under the hood, but that is not dictated by the standard. Standard syntax does not allow a pointer to be assigned as-is to a reference, and vice versa, hence the compiler errors on tho...
64,723,110
64,733,291
C++ Find the sum of elements between minimum and maximum element of matrix
So, My program works as it should, but only if minimum and maximum element are in opposite corners. So my question is how to iterate two-dimensional array from one certain element to another(and perhaps get rid of some nested loops). Shall I convert this array to one-dimensional? Here's the correct work of the code: A...
As my comment stated, one solution is to realize that the two-dimensional array has a layout of its data in contiguous memory. Thus getting the minimum, maximum, and sum become simple, since you would traverse the two-dimensional array in the same way as a one-dimensional array. Here is a solution using C++ algorithm ...
64,723,265
64,723,524
How to use ADL in Constraints?
As an example, I want to use a constraint to ensure that the function isinf is implemented for a template parameter T. If T is one of float, double, long double or an integral type, this can be done in the following way: #include <cmath> template <typename T> concept Test = requires (T a) { std::isinf(a); }; Howe...
The way this sort of thing works in Ranges is by creating a Customization Point Object. This closely mirrors your second option (we stick a using-declaration in a custom namespace) except we also provide an mechanism for users to call the correct isinf without having to write a bunch of the same kind of boilerplate the...
64,723,326
64,726,780
Weird output for RGB
I am trying to manage some LED strips with my mobile device using bluetooth + Adafruit NeoPixel. I almost had the sketch finished but I have found the numbers for RGB are not appearing as I expected and I cannot find what I am doing wrong. Imagine that from my mobile I have sent the following RGB code "0,19,255", when ...
You describe that for the shown output you sent via mobile "0,19,255". Yet in the shown output that obviously is only the second part of a longer sequence of numbers sent, which starts with "0,21". Assuming that what you send is always of the format you have described, i.e. three numbers, separated by two ",", the show...
64,723,343
64,724,206
Exiting entire bash script from subshell
I'm a bit new to bash scripting, I have a C++ program communicating back and forth with this bash script through some named pipes. I used inotifywait to watch a folder for new files and when a new file is added (ending in .job) sending it to through the pipe. I'm having the C++ program pipe back the result, and if the ...
In general, you can use kill "$$" from a subshell in order to terminate the main script ($$ will expand to the pid of the main shell even in subshells, and you can set a TERM trap in order to catch that signal). But it looks that you actually want to terminate the left side of a pipeline from its right side -- i.e. cau...
64,723,813
64,723,879
How to build a C++ program that takes a graph, color it and print out that graph to a .dot file?
Problem statement: Given an undirected graph E. Build a C++ program to color it using greedy algorithm. You will read input from the file "graph.txt", the first line contains the total number of nodes n and the total number of edges m, each of the (m+1) line contains two positive integers representing an edge. The resu...
You can print the file with: std::cout << "graph E\n{\n"; for (std::size_t i = 0; i < nodes; ++i) { std::cout << (i+1) << "[fillcolor=" << color[i] << ", style=filled];\n"; } for (std::size_t i = 0; i < edges.size(); ++i) { std::cout << edges[i][0] << " -- " << edges[i][1] << ";\n"; } std::cout << "}\n";
64,723,904
68,944,927
why does this simple Gecode example not compile?
I am trying to learn gecode and am trying to get the example found here to work. // To use integer variables and constraints #include <gecode/int.hh> // To make modeling more comfortable #include <gecode/minimodel.hh> // To use search engines #include <gecode/search.hh> // To avoid typing Gecode:: all the time using n...
e.next() returns a pointer of the cloned space (SendMoreMoney). You must use while (SendMoreMoney* s = e.next())
64,724,943
64,726,213
Executing CMD commands using C++
I am trying to sleep my PC using this command system("C:\\Windows\\System32\\psshutdown -d -t 0"); it works fine if I use cmd, but when I run this in cpp, I got this 'C:\Windows\System32\psshutdown' is not recognized as an internal or external command, operable program or batch file.
32-bit applications running on WOW64 will be put under file system redirection. Therefore if your app is a 32-bit one, the call system("C:\\Windows\\System32\\psshutdown -d -t 0"); will look for psshutdown.exe in C:\Windows\SysWOW64 and failed. You have some solutions: Use Sysnative instead to access the real System32...