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
67,419,931
67,421,118
Making an application bundle with Xcode, C++ and wxWidgets
I'm new to macos, I'm trying to figure out how to make an application bundle so my code won't be just an executable file. I'm working with xcode version 12.5 and writing a test gui application using c++ language and the wxWidgets library. Now I tried to make a simple gui with just a button and a menu bar (The bar on to...
In order to make an Application Bundle: You should have been creating an OSX Application project inside Xcode. Check wxWiki (I know it is for older version of Xcode, but it still applies and you can try to match it in the newer version). If you want to do that later - you can try to build minimal sample from thr wxWidg...
67,420,227
67,422,669
How to make the Code for this question optimized?
The city of Darkishland has a strange hotel with infinite rooms. The groups that come to this hotel follow the following rules: At the same time only members of one group can rent the hotel. Each group comes in the morning of the check-in day and leaves the hotel in the evening of the check-out day. Another group comes...
If the for loop goes for n steps, it means that: D > S + (S+1) + ... + (S+n-1) You can solve this issue analytically and apply correction to the potential numerical error. long long groupSize(long long S, long long D) { long long twoSMinus1 = 2 * S - 1; // solution of quadratic equation long long result1 = ...
67,421,656
67,422,293
Filter the tuple types with templates in C++
I need to check the types of the tuple with type traits. And if the type is appropriate it should stay, if it is not its continues. For example: using TUPLE = tuple<int, float,char, short, string, double, float>; using TUPLE_INTEGRAL = filter_types_t<is_integral<void>, TUPLE>; TUPLE_INTEGRAL --> tuple<int, char, short>...
Your code was almost correct. With these 2 things changed it works: t_Predicate needs to be a template template type since it is used as a template in the implementation. The using declaration needs to be split into 2 parts. Or at least that's how it is usually done and how you use it in the example. Here is my worki...
67,421,937
67,422,001
How to pass traits as arguments for a templated struct?
Say I have something like this template<typename T1, typename T2> struct my_struct { using type = typename T1<T2>::type; }; In the main function I want to be able to write using test = typename my_struct<remove_const_t<>, const float>::type; where test will be equal to float since remove_const_t<const float> retur...
You want a template template parameter so you can pass the template to my_struct. That would look like template<template<typename> typename T1, typename T2> struct my_struct { using type = typename T1<T2>::type; }; and then you would use it like using test = typename my_struct<is_integral, float>::type;
67,422,111
67,422,210
Is it possible to implement coroutine with threads?
All in title. Since coroutine just need a sort of EIP memory, and thread provides that, is it possible to do it? That's way to have a highly portable coroutine library.
You can implement coroutines / generators based on threads or even fibers. But they would be less performant compared to implementations like msvc or gcc provide. I implemented coroutines that way (no threads, but fibers) in delphi. You need to estimate how much stack-memory do you need, you need to create those thread...
67,422,116
67,426,342
Elegant way to push all declarations with a particular pattern-match into vector?
I'm refactoring some code and curious if there is a modern C++ feature that allows me to dynamically push all matching declarations into a vector without having to manually type out every parameter name. For example; I have the following declarations in my header (instantiated elsewhere); Fl_Button * button_file_browse...
Is there a beautiful C++ feature that allows me to type something as elegant as below? std::vector<Fl_Button *> vector_fl_button; vector_fl_button.push_back(button_*); No, not built-in. However, FLTK makes it possible to build the vector dynamically. The name of the objects in the C++ code is however lost in compil...
67,422,140
67,422,362
Why is my code Time Limit Exceeded while a really similar code is not (Leetcode 1249)?
I am solving https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ Description: Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any val...
Unless you have a clever compiler, += will probably be faster as it's simply concatenating a char to an existing std::string (there may well be a couple of allocations as string memory limits are reached but that won't occur on each call to +=). The overloaded + operator for a std::string followed by an assignment back...
67,422,396
67,422,510
Why cppreference says that copy_n can throw bad_alloc? When is it possible?
I've read through copy_n documentation https://en.cppreference.com/w/cpp/algorithm/copy_n and there's an interesting line in Exceptions section: If the algorithm fails to allocate memory, std::bad_alloc is thrown. What allocation is it talking about? When we want to copy N bytes we firstly allocate a buffer ourselves...
This section is talking about the overload with a template parameter named ExecutionPolicy. That overload allows the algorithm to use multiple threads to do the copying. To facilitate that, the implementation might need to allocate some resources and that could throw. These exceptions do not apply to the serial versi...
67,422,588
67,422,934
Overloading a template based on size of type
I'm trying to write a templated function that will allow me to pass in an explicitly sized enum and it will call the correct serialize function based on the enum's size in C++ 11. This is what I currently have, which works fine: template<typename EnumName> uint32_t WriteBuffer::Write_enum(EnumName aValue) { conste...
For this very specialized case, you can use std::underlying_type to extract the type name, and then rely on plain old overloading: struct WriteBuffer { template<typename EnumName> uint32_t Write_enum(EnumName aValue) { Write_overloaded(static_cast<typename std::make_unsigned<typename std::underlying_typ...
67,422,712
67,468,530
Error while setting up Movesense platform with Cmake commands
I've been trying to set up movesense platform in my windows 10 machine and facing issues with cmake commands. I pulled the movesense container using docker docker pull movesense/sensor-build-env:latest I cloned the movesense repo using the below code git clone git@bitbucket.org:suunto/movesense-device-lib.git Then...
The "<sample_directory>" should be a path to the folder where the firmware source code is (i.e. the sample app folder). If you create the build folder as /movesense/myBuild and cd into it, the path would be ../samples/blinky_app if you are building the blinky_app -sample. Full disclosure: I work for the movesense team
67,423,052
67,423,337
cpp - why you can't use boolean, float, & string in switch Statements
i am new to C++ and currently learning switch statements, but i don't know why does my compiler throws an error or warning (in case of booleans) when i use boolean, float, & string ? How can i solve the problem ? or why does it occur
In days of old and sometimes today, switch statements were translated into arrays of branch or jump statements, preferably contiguous. As with arrays, indices of 8.9, "frog", and "false" don't make sense. The C and C++ languages are designed for efficiency when compiled. An array of jump instructions is much more effi...
67,423,193
67,424,485
How to declare global variables in seperate config.h file
I am running into a problem with compiling in VScode and not when in Visual Studio. I have a header file config.h in the include folder in my project. Please note I have added build_flags = -I include to platformio.ini. In config.h I need to make some declarations for a select number of global variables that I need. Ev...
If you just want global constants, refer to Defining global constant in C++. Assuming that you need a mutable global variable, there are two options. In either case, there will be only one instance of our global variable. Classic Solution: extern // header file extern MyQueue queue; Here, we simply say that queue is d...
67,423,250
67,423,425
Transform the std::tuple types to another ones
Let's say ı have a type traits to transform one type to another one template<typename ...> struct Transforming; template<typename T> struct Transforming<T> { using type = T; }; template<> struct Transforming<char> { using type = int; }; template<> struct Transforming<long> { using type = int; }; template<> struct Trans...
C++ templates have a kind of parameter called template template parameter which is a template parameter which is itself a template. These types of parameters can be used to provide templates like Transforming<T>. Example : #include <tuple> // Original trait template<typename ...> struct Transforming; template<typename...
67,423,616
67,454,121
How Android Runtime compiles Java more efficiently than the CLang C/С++ compiler (Android NDK)?
I was absolutely sure that C\C++ native code will run faster than Java code. And it is. My simple C/C++ benchmark (random arithmetic operations on int array) runs 5-7 times faster than the same Java code on an old tablet (Samsung Galaxy Tab E - Android 4.4.4 - Dalvik VM), but slower on recent devices with ART Prestigio...
How Android Runtime compile more efficient native code than CLang (Android NDK) C/C++ compiler? The JIT compiler complements ART's current ahead-of-time (AOT) compiler and improves runtime performance. Although JIT and AOT use the same compiler with a similar set of optimizations, the generated code might not be ident...
67,423,722
67,423,802
C++ linked list implementation, goes to infinite loop while traversing. Guessing something is wrong with the contructors
I'm new to C++. I'm trying to implement a linked list. The output goes to an infinite loop when the traverse function is called(output shown at the bottom). Had no errors when I used 'new' in the insertNodeAtEnd function instead of contructors, but I read up that it's generally not a good practice in C++ and it's bette...
Here: static void insertNodeAtEnd(int data) { Node newNode(data); if (head == NULL) { head = tail = &newNode; return; } tail->next = &newNode; tail = &newNode; numberOfNodes++; return; } newNode is a function local variable. Its lifetimes ends when the function returns....
67,423,725
67,423,794
Building .SLN files on Windows without Visual Studio?
I have recently been trying to set up my CMake environment and some 'hello world' code in C++. I added a CMakeLists.txt and added my configurations, but when I ran cmake . in the command line, something was different from all of the tutorials. The people on the tutorials were using a Unix based system, so the command c...
First of all, you should never do an in-tree build with cmake .. It invites problems in the form of name clashes and makes it nearly impossible to get a clean rebuild. If you're using a recent version of CMake (which you should be), the standard way to build a project varies on whether the backend generator is single-c...
67,424,096
67,428,377
AnyFunction class with type erasure
I want to implement a type-erasure class AnyFunction that would be able of storing any entity with templated call operator(that returns void). For example: struct Printer { template<typename... Args> void operator()(Args&&... args) { std::cout << ... << std::forward<Args>(args); } }; Printer typed_printer A...
You can't quite do what you are asking for. You can write a type AnyPrinter, but you cannot write an AnyFunction without literally shipping a C++ compiler and taking as input the C++ code you want to store in it and compiling a DLL on the fly. The existence of DLLs should make the problem clear. Suppose your AnyFuncti...
67,425,414
67,425,510
Is the optimizing compiler allowed to omit a function call indirectly used in a short-circuit?
The C and C++ languages evaluate || and && in left-to-right order, and must "short-circuit" the right-hand side if the left-hand side establishes the truth value of the entire expression. Does either language allow for the generated code to not call foo(), if the result of foo() is stored in a local variable only used ...
Compiler optimizations are not permitted to change the observable behavior of the program. int foo(int f); int bar(int x) { int const foo_value = foo(x); if (x || foo_value) { return 123; } return 456; } int baz(/* assume "void" here for C */) { return bar(1); // Can this collapse down to "return 123"?...
67,425,829
67,426,056
Why do I get a segmentation fault for my operator +?
I have this simple code : vector<double> operator+(const vector<double>& v1, const vector<double>& v2) { int n = v1.size(); vector<double> a(n); for(int i = 0; i < n; ++i){ a[i] = v1[i] + v2[i]; } return a; } But my debugger shows me that there is a segmentation ...
Your operator+ assumes both vectors are the same size. If v1 is larger than v2, the loop will go out of bounds of v2, causing undefined behavior. So, either validate the sizes are equal, eg: vector<double> operator+(const vector<double>& v1, const vector<double>& v2) { size_t n = v1.size(); if (n != v2.size())...
67,425,836
67,426,052
What is the accepted C++ template definition for pointer-only types?
I want a type that simply wraps a pointer stored as a member. struct Foo { }; template <typename T> struct MyHandle final { MyHandle(T* data) : m_Ptr(data) { }; T* m_Ptr; }; void main() { MyHandle<Foo> fooHandle(new Foo()); } This is sufficient since I restrict the constructor to only take a pointer of ...
You can use std::remove_pointer: #include <iostream> #include <type_traits> struct Foo { void Test() { std::cout << __func__ << std::endl; } }; template <typename PTR> struct MyHandle final { static_assert(std::is_pointer<PTR>::value); using T = typename std::remove_pointer<PTR>::type; MyHandle(T* ptr) : m_Pt...
67,426,010
67,426,267
asio boost socket connection refused
I'm attempting to connect a client and server through asio boost but my connection keeps getting refused. My expected output is a clean connection with no errors. client.cpp #include <boost/asio.hpp> #include <fstream> #include <iostream> using namespace std; using namespace boost; using namespace boost::asio; using n...
First off, with all the unhygienic namespace ... abuse and then even naming your variables conflicting names (like io_context) it's hard to tell wether the code is correct, or should even compile. Here's my counter-offer File server.cpp #include <boost/asio.hpp> using boost::asio::ip::tcp; int main() { boost:...
67,426,161
67,427,573
Arithmetic on all but the last components of tuples in C++
Getting inspiration from this question, I managed to implement a function which takes two tuples as input and return a tuple which components are the min of each components of the tuples given in input. template<typename T, T...> struct integer_sequence { }; template<std::size_t N, std::size_t... I> struct gen_indices...
Now, I would like it to work on all components but the last one. for the last one, always keep the component of t1 So, to solve this, pass a reduced list of integers (not sizeof...(T) but sizeof...(T)-1u): template <typename ... T> std::tuple<T...> min_tuple( const std::tuple<T...>& t1, const std::t...
67,426,215
67,436,939
JWT Verification on WIN32
I'm attempting to verify a RS512 JWT using the WIN32 cryptography functions. I've got the public key, data to be verified, and signature data as in-memory arrays. I'm able to create the certificate context and import the public key, but so far I haven't been able to verify the signature. Regardless of what I attempt...
I missed the part in the documentation that says the data needs to be hashed. After applying the same hash to the data (SHA512) I am able to verify the signature. Here is the working code minus error checking: //Hash data here. auto hashedData = data.hash( HashType::SHA512 ); auto signingKeyBuffer = signingKey.publi...
67,426,510
67,426,730
Is there an efficient way to slice a C++ vector given a vector containing the indexes to be sliced
I am working to implement a code which was written in MATLAB into C++. In MATLAB you can slice an Array with another array, like A(B), which results in a new array of the elements of A at the indexes specified by the values of the element in B. I would like to do a similar thing in C++ using vectors. These vectors are ...
emplace_back has some overhead as it involves some internal accounting inside std::vector. Try this instead: template<typename T> std::vector<T> slice(const std::vector<T>& v, const std::vector<int>& id) { std::vector<T> tmp; tmp.resize (id.size ()); size_t n = 0; for (auto i : id) { tmp [n++...
67,426,662
67,426,949
C++ Lookup table for derived classes
I have a wrapper class holding a bunch of derived class objects by means of a vector of references to a common base class. During runtime, the Child objects are created based on user input. #include <iostream> #include <vector> #include <memory> #include <type_traits> class Base { public: virtual void run() = 0; }...
This looks like a typical case of double dynamic dispatching, however there is a possible simplification in that the output and input types must match. Hence, here is sort of a half-Visitor pattern. First, we extract the concepts of input and output types into classes so that they can be targeted by dynamic_cast: templ...
67,427,261
67,427,442
Cannot find any header files c++ project in Visual Studio
For the past hour I have been looking at multiple stack overflow questions trying including this one and this one trying to figure out why visual studio cannot open typical source files like stdio.h I am starting out by building a new project and then selecting the "console app" option, but when I try to compile and ru...
The issue was that I thought I had the Widows 10 SDK installed, but apparently I did not. I found the answer using this stack overflow thread. I had to download the Windows 10 SDK from here and restart the visual studio IDE and it worked straight away.
67,427,345
67,427,459
std::vector.data(), &std::vector[0] and &std::vector.front() returning wrong values
I'm having a little issue that i don't know how to fix. I'm trying to send a std::vector<float*> to the GPU, and in order to do that, I have to return the elements from the array as values instead of pointers. This float-pointer vector just for testing is storing 2 squares with 4 vertices each, having a total of 8 elem...
The basic problem is that you have a vector of pointers, which don't necessarily all point to contiguous memory. So you can't treat them as such. In order to get your values into a contiguous array of floats, you'll need to copy them into a contiguous array of floats. Something like std::vector<float *> allVerts; std...
67,427,776
67,428,113
Is passing by reference the right solution?
I have some type like this: #pragma once #include <stdio.h> #include <string> struct Color { std::string value; }; struct Shirt { std::string brand; Color color; }; class Outfit { public: Outfit(Shirt shirt): shirt(shirt) {} private: Shirt shirt; }; I previously reviewed this Stackover...
The copy and the original Outfit will point to the same Shirt instance No this is wrong. A copy has no relationship to the original except if it also contains pointers. In that case, the pointers will still point to whatever they referred to before the copy was made. However, even the pointers themselves are not the ...
67,428,188
67,428,355
How can I use push_back() on a vector of pointers?
I have a Manager class. I made an addEmployee() method to add Employee objects to it by address: #include <iostream> #include <string> #include <vector> using namespace std; enum EmployeeLevel { A, B, C, D, E }; class Employee { string name; const EmployeeLevel level; public: Employee(const string& _name, ...
Your addEmployee() was expecting a const Employee*. But your vector is storing an Employee* resulting in pushback failure. So change your addEmployee() as follows: void addEmployee(Employee* e) { group.push_back(e); }
67,428,388
67,429,052
Using reinterpret_cast to pass a value by reference
#include <iostream> void inc(long& in){ in++; } int main(){ int a = 5; inc(*reinterpret_cast<long*>(&a)); printf("%d\n", a); return 0; } Above code compiles successfully and prints 6. Is it undefined behaviour? as I'm not really making a reference to anything on the stack. I'm doing an inline cast. Note that t...
As for the editted question: My question is, how is it ok to pass *reinterpret_cast<int*>(&a) as a reference but static_cast<int>(a) isn't?" As it was already said, this is because the *reinterpret_cast<int*>(&a) expression has a value category lvalue as described in [expr.unary.op]: The unary * operator performs in...
67,428,492
67,431,066
Get SID of current user as std::string. c++
Get SID of current user as string. c++ I've been thinking how to get sid in c# it's easy like this: System.Security.Principal.WindowsIdentity.GetCurrent().User.Value; If someone can give me short solution to get SID as std::string i will be happy.
See these WINAPI functions: ConvertStringSidToSid(), to convert the account SID strings to a SID that is required as an argument to, LookupAccountSid()
67,428,511
67,428,576
Why doesn't parameter pack expand to correct type?
I have a somewhat contrived piece of code: #include <functional> template <typename... ARGs> auto construct1(std::function<void(ARGs...)> p, const ARGs &...args) {} template < typename... ARGs> auto construct2(std::function<void(int)> p, const ARGs &...args) {} int main() { auto p = [](int) {}; construct...
The problem is, construct1 is taking std::function but you're passing lambda. When you make parameter as type std::function<void(ARGs...)>, template argument deduction is performed to deduce ARGs on the function parameter p (even template parameter pack is explicitly specified with template arguments it may be extended...
67,428,659
67,428,815
Why do I keep getting a read access violation? C++
I keep running through the program and changing around pointers and I don't see what I am missing. I keep getting a read access violation on line 42 of the .cpp file and I am genuinely confused on how. Here is the .cpp file #include "Graph.h"; void Graph::insertEdge(int from, int to, int weight) { if (from <= size...
Probably instead of if (from == current->adjVertex || current == nullptr) you should first ensure the pointer is not null before dereferencing it. if (current == nullptr || from == current->adjVertex) then if current is null, the right-hand side of || operator won't be run. HOWEVER, you will still have a problem be...
67,428,922
67,428,950
Is there any macro defined when compiling with --coverage option?
As mentioned by the title, I would like to achieve something like this: void my_exit(int status) { #ifdef _GCOV __gcov_flush(); #endif _exit(status); } But I do not know if there is a _GCOV(or something similar) defined when compiling with --coverage. Any idea will be appreciated!
Doesn't seem to be: $ true | gcc -E - -dM > no-coverage.h $ true | gcc -E - -dM --coverage > coverage.h $ diff no-coverage.h coverage.h
67,429,553
67,440,197
Error compiling C++ source utilizing the Boost.Math library
I'm trying to use a couple of functions from the Boost Math library in some C++ code using the G++ compiler but I've been unsuccessful. This is on macOS. I downloaded and extracted the Boost tar.gz from here and placed it into my source folder. Within my C++ I've tried #include "boost_1_63_0/boost/math/distributions/ch...
Resolved using #include "/Users/[me]/[project_dir]/boost_1_63_0/boost/math/distributions/chi_squared.hpp" and g++ -I/Users/[me]/[project_dir]/boost_1_63_0/ main.cpp
67,429,774
67,431,694
Fstream getline() only reading from the very first line of text file, ignoring every other line
I am working on a coding project where I sort and organize data from a text file, and I cannot get the getline() function to read past the first line. The idea is to capture the entire line, split it into 3 sections, assign it to an object, then move on. I can do everything except get getline() to work properly, here i...
what you can do is rather than using !fin.eof(). i prefer to use something similar to this: ifstream file ( fileName.c_str() ); while (file >> first >> last >> pace ) // assuming the file is delimited with spaces { // Do whatever you want with first, last, and pace } The "While loop" will keep...
67,429,795
67,429,866
Why the program execution ends at the first iteration of for loop?
C++ Program To Generate Random Password As stated in the code(as comment), the program execution doesn't end or works fine without those lines of code but with them, the program ends without executing the next iteration and lines of code that follow. #include<iostream> #include<cstring> #include<cmath> #include <ctime...
In the line of code in question p is used uninitialised and gets write-dereferenced inside the called function. That should give you at least two causes for undefined behaviour, which means absolutely anything can happen. With that, all bets are off, end of explanation for the line in question. If you get no problems f...
67,429,895
67,446,777
How to create CMakeList.txt for Onboard-SDK project on Debian 10
I would like to compile my own project. I have error with **make**. cmake .. works properly. I tried to compile the example in /Onboard-SDK/sample/platform/telemetry. I did mkdir build and cd build in telemetry directory. This is my CMakeList.txt cmake_minimum_required(VERSION 2.8) project(djiosdk-telemetry-sample) # ...
The proper CMakeList.txt for creating your own project (example based on telemetry sample): cmake_minimum_required(VERSION 2.8) project(djiosdk-telemetry-sample) set(ARCH armv7) # Compiler flags: link with pthread and enable C++11 support set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread -g -O0") # Tell t...
67,430,002
67,452,604
How to iterate through all typenames in a class template?
I want to design a component-based weapon template for my game. However, it seems no way to add/remove a class member or create a code? Sorry for my expression and lack of terminology, for I am not graduated from dept. of computer science or software engineer, I know little of what those stuff called by professionals. ...
One way of doing so from C++11 on-wards would be to store the template types used for this particular weapon inside an std::tuple template <typename Weapon, typename... Attachments> class WeaponWithAttachments { protected: WeaponWithAttachments() { return; } std::tuple<Attachments...> attachment_types...
67,430,095
67,430,213
Why do const variables don't need to be initialized in a template class until the class is actually used?
Why doesn't the compiler throw an error if I don't initialize const variables in an unused template class? If I remove the template keyword the compiler complains as expected. This code works (unexpected): #include <iostream> template<class T> class Matrix { private: const uint8_t numRows, numColumns; T conten...
Class template isn't implicitly instantiated until required. You don't use Matrix<int>, then it's not instantiated, and definition is not required (to exist or to be well-formed). When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, a...
67,430,461
67,430,935
Container Iterator Template for one value type
you helped me before so here I am again with another question in hope for an answer. I have a function that processes a range of std::complex<float> values. My initial attempt of a function definition was // Example 1 using namespace std; // not in original code Errc const& process(vector<complex<float>>::iterator begi...
Your example 2 is nearly correct template< template<typename T> class C, typename T, typename C<T>::iterator iterator // That is wrong > Errc const& process(typename C<T>::iterator begin, typename C<T>::iterator end); it should be: template<template <typename> class C, typename T> Errc const& process(t...
67,430,885
67,430,939
OpenGL Won't Render With Shaders Mac
I'm trying to get OpenGL to render a basic triangle with shaders on my newer Macbook Pro with the M1 chip. I'm stuck using Qt Creator as well. I was able to set it up and get a basic Fixed-Pipeline scene rendering, but when I changed the version to use modern OpenGL I get that the version is 4.1, even though I set it t...
This is not a problem with the shaders. However in a core profile OpenGL Context you have to create Vertex Array Object, since the default VAO (0) is not valid. This is not optional: GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glEnableVertexAttribArray(0); // Enables the buffer layout glBindBuffer(...
67,431,083
67,431,338
Can inline substitution cause an infinite loop in multithreaded code?
Please note: This is just a question out of curiosity, but not about writing better-multithreaded code. I don't and won't write code like this in real projects, of course. Inline substitution may occur when the inline keyword is added. So I'm curious. Let's say we have code like this: static bool done = false; inline ...
The access to done must be protected in parallel and synchronized between threads. Otherwise, the processor or the compiler can produce/execute an incorrect sequence of instructions. Your current program is ill-formed. The problem you are facing is that done can be cached in the L1 CPU cache (processor dependent) or th...
67,431,325
67,431,493
argument of type "void" is incompatible error
hello and thanks in advance for supporting, I'm trying to send a pointer to function which is type void and receive nothing. it didn't work well so far. here is my minimal code that have this problem: void func::foo() { return; } and the function which use it is: void func::create_func(void(*wanted_func)()) { ...
From what I understand, you'd like to pass a member method pointer to another member method. So you'll have to bind an object instance to the method that you want to pass. Have a look at std::bind (Reference) Here is a minimal example which I believe does what you want: #include <iostream> #include <functional> class ...
67,431,365
67,431,506
C++ error: 'variable' was not declared in this scope
I have this simple C++ program and when I try to compile it I get two errors: 'klasa' was not declared in this scope 'oznaka' was not declared in this scope Does anybody know how can I fix it? Note: I am still beginner in C++. :] #include <iostream> #include <string> using namespace std; int main(){ int T; cin...
The reason for the error is that you're declaring each of klasa and oznaka inside the "if statement", as such you can only reach these variables within their scope (i.e inside each of their respective "if statements") #include <iostream> #include <string> using namespace std; int main(){ int T; cin >> T; s...
67,431,515
67,432,336
Auto expand qcombobox that is delegate in qtreeview
I have my own QTreeModel implemented, where at first column I'm using custom delegate which is QComboBox with auto-completion of some strings in it. The delegate is created by using QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index); method. Also, the delegate is being ...
To enter edit mode, you can use: void QAbstractItemView::edit(const QModelIndex &index) The combobox will be shown, but not opened. To do that, you can override QStyledItemDelegate::setEditorData() and call combobox->showPopup(); at the end of the function. void setEditorData(QWidget *editor, const QModelIndex &index)...
67,431,972
67,452,597
How can I get metadata from boost::mysql::row?
How can I get metadata from an element into boost::mysql::row ? void print_employee(const boost::mysql::row& employee) { std::cout << "Employee '" << employee.values()[0] << std::endl; how can i get metadata from here? I want to extract the column name for this specific value const bo...
The field meta data describes a rowset, not a an individual row (because in the SQL model, each row in the resultset has the exact same metadatra). So, assuming you had a database called Test with a table Message, you can use the metadata for each row as follows: #include <boost/mysql.hpp> #include <iostream> using boo...
67,432,798
67,433,355
Initialize class with array
I found many questions in this area but none seem to match what I'm looking for. The goal is to initialize a constant class instance so that it is put completely in flash memory of an microcontroller and not take up any ram. This is an not working example: class Message { public: co...
As explained here (kudos to taiBsu for posting the linke in the question's comments) Your constructor argument [data] is, actually, not an array! Yes, I know it looks like one, because you wrote [char data[4]]. But, actually, it's [char* data]. ... So, the error message is telling you that you cannot assign a pointer ...
67,433,342
67,433,482
Why system_clock time_point can not be constructed from duration?
Browsing cppreference shows that in theory any time_point should be constructible from duration. constexpr explicit time_point( const duration& d ); Constructs a time_point at Clock's epoch plus d. But when I try it on some compilers it does not work, on some it works. Second lambda does not work, but surprisingly...
The durations of system_clock and steady_clock are implementation defined. On platforms where it does not have (at least) nanosecond resolution, there isn't a constructor that takes nanoseconds. If you add a duration_cast to an appropriate duration, then both work. #include <chrono> using namespace std::chrono; int mai...
67,433,481
67,434,114
C++: Use sideeffects of a conditional_variable test
I wonder whether I can use the side effects of a conditional_variable test? Is it guaranteed that the conditional_variable test is returning to execution if it returns true, or can there be the situation that the test returns true, but it is called again or times out in between? In the below example maybeCmd_locked() d...
The predicate is always checked under the lock, and another wait isn't done if the predicate returns true. In a simplifed version of your code (which doesn't have time outs) is: if (cv.wait(lk, [&cmd,this]{ return ((cmd = maybeCmd_locked()) != -1); })) { return cmd; } cv.wait(lock, pred) is defined to be equivalen...
67,433,514
67,435,578
Does the pointer arithmetic in this usage cause undefined behavior
This is a follow up to the following question. I was under the assumption, that the pointer arithmetic I originally used would cause undefined behavior. However I was told by a colleague, that the usage is actually well defined. The following is a simplified example: typedef struct StructA { int a; } StructA ; typ...
It is undefined behavior because there are severe restrictions on what can be done with pointer arithmetic. The edits that you have made and that were suggested do nothing to fix this. Undefined Behavior in Addition StructA* a = (StructA*)((char*)copy + offset); First of all, this is undefined behavior due to the addi...
67,434,912
67,434,992
Why does calling a method from within another method use the version that is within the same class and not an overriden version?
I have made an example that shows exactly my point without any additional code from my actual project. I have two classes that are parent and child and each have a getClass() method that return a string with the name of their class. Obviously the getClass() method inside the child overrides the one in Parent. Then I ha...
In C++, methods have to be explicitely marked as virtual for polymorphism to be effective. If a method is virtual, the most derived override will be used whatever class the calling method is in. If it is not, the version of the calling class will be used, whatever the actual class of the object.
67,435,394
67,435,625
C++ only one constructor is called
I'm trying to understand rvalue reference. This is the code I've written so far: class A { public: A(const char* str) { std::cout << str; } A(A&& other) { std::cout << "other"; } }; int main() { A m(A(A(A("hello")))); } The output is only "hello", which makes me confused. Since A(...
Yes this is a compiler/language(see latter) optimization. As can be seen here, this will output: hello Changing the standard from -std=c++2a to -std=c++14 in the compiler options will still give you hello only, but in addition to the standard change if you also add: -fno-elide-constructors to the options you should se...
67,435,492
69,799,148
C++ move constructor with IBM Rhapsody
I am running IBM Rhapsody 8.1.5 here and moving a code base to modern C++. I now face the issue that I can't define a move constructor, if a copy constructor is already defined, because Rhapsody simply ignores lvalue and rvalue references and thinks both constructors are the same. Since I can't even choose the move con...
This is IMHO a bug in the product. These workarounds exist in version 8.4: First create a constructor of your class A with argument type int (or any other type different from A), then go to Features... → Arguments and change the argument type to A and the code pattern to $type&& Use C++ Declaration A&& instead of exis...
67,435,837
67,435,975
implementation of bucket in unordered_map
I read somewhere that once a bucket holds more than 8 elements it will become a red&black tree instead of a linked list. I know that java uses this policy but i'm sure about c++
The standard doesn't mandate any particular implementation. Only linked lists are used in the libstdc++ and Microsoft implementations (I didn't study other implementations, so here I'm considering only these two). Both of them use one long linked list (libstdc++ - singly-linked list, Microsoft - doubly-linked list) tha...
67,435,899
67,441,182
Using decltype in a nested-name-specifier
Consider the following demonstrative program. #include <iostream> namespace N { struct A { static int n; }; A A; } int N::A::n = 10; int main() { std::cout << N::A::n << '\n'; std::cout << N::decltype( N::A )::n << '\n'; return 0; } The program compiles successfully us...
A decltype-specifier can never appear except at the beginning of a nested-name-specifier. After all, it designates a specific type, and no name lookup is necessary afterwards to interpret it. GCC is wrong to accept the code: by experimentation, it seems to just ignore any preceding components after checking that they...
67,436,247
67,436,291
runtime error: reference binding to null pointer of type 'int' (stl_vector.h) : LeetoCode 907
I am trying 907. Sum of Subarray Minimums on Leetcode. I keep getting this error: Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:10...
On the first iteration, ans has no elements i = 0 j = i (j = 0) Then no elements will be pushed to ans because i < j is false. Therefore, mn = ans[0]; is invalid out-of-range access because ans still has no elements.
67,436,373
67,437,098
Why ranges::single_view use curly brace initialization for underlying value?
According to [range.single.view#3], one of std::ranges::single_view constructors define as: template<class... Args> requires constructible_­from<T, Args...> constexpr explicit single_view(in_place_t, Args&&... args); Effects: Initializes value_­ as if by ­value_­{in_­place, std​::​forward<Args>(args)...}­. Why th...
value_ is a semiregular-box, so its constructors are well-known and don't include an initializer-list constructor. The inconsistency doesn't arise because in this case braces and parens are equivalent - the underlying type will always be constructed with parens, because that's what the semiregular-box's constructor is ...
67,436,771
67,437,125
How to correctly write an array of chars to a text file
At first, I would like to point out that despite using C ++ I cannot use strings or vectors. It is like C with objects. Ok I have class A with char* test() method: char* A::test() { char to_return[3*this->some_value+3]; for (int i = 0; i < this->some_value; i++) { to_return[3*i] = '♥'; to_re...
The problems are: to_return is a local array that ends its lifetime on returning from the function, so returning its pointer is a bad idea. '♥' may differ from what you want, especially when ♥ cannot be represented by one byte in your character code. To overcome this problems: Allocate a dynamic array that persists ...
67,436,868
67,437,063
linked lists insertion function send argument by references misunderstanding
I was reading through a book about C/C++ and I study linked lists from it. I implement a LL as: struct Node { int information; // the information of one node. assumed is that this is an integer only struct Node * next; // pointer which stores the address of next node in the list. points to next node in the list...
What does cause some confusion is this typedef (at least for me it was a source of confusion at first): typedef struct Node * List; So the arguments here: void Insert(List & First, List p, int x) { are actually void Insert(Node*& First, Node* p, int x) { Parameters are passed by value in C++, unless you pass them by...
67,437,131
67,437,566
Why does the next line of a function still execute despite calling another function before such line?
Here's a sample code where it is evident: int foo(); void bar(); bool flag = false; int foo() { if(!flag) bar(); cout<<"Reached Here!"<<endl; return 0; } void bar() { flag = true; foo(); } In this code, cout<<"Reached Here!"<<endl; is executed twice. However, simulating it step-by-step does not ...
When you return from functions, the execution continues from the line after the function call. This is what return means. Therefore, the actual trace is: (1st call of) foo() calls bar(), seeing flag = false bar() sets flag = true bar() calls (2nd) foo() (2nd call of) foo() skips bar(), seeing flag = true (2nd call of)...
67,437,232
67,437,471
Using std::tie with bit fields seems to fail
I have the following code in C++17 in which I am defining a struct which is a bit mask and has member variables which are bit fields of type bool. I am defining a tie function so that I can convert it to a comparable std::tuple object, which can be handy. Problem is: std::tie seems to be doing something wrong, and the ...
It is not possible to have a reference or a pointer to a bit field. From cppreference : Because bit fields do not necessarily begin at the beginning of a byte, address of a bit field cannot be taken. Pointers and non-const references to bit fields are not possible. When initializing a const reference from a bit field,...
67,437,611
67,438,865
Compute reduction sum of a device array with thrust
I know we can compute sum of a CPU(host) array with thrust like this. int data[6] = {1, 0, 2, 2, 1, 3}; int result = thrust::reduce(data, data + 6, 0); Can we find sum of GPU array with thrust without cudaMemcpy to CPU array? Suppose I have a device array created using cudaMalloc like this, cudaMalloc(&gpuspeed, n* si...
Yes, you can do that with thrust. You can pass device pointers to thrust, and thrust will do the right thing if you specify explicitly the device execution path, using thrust execution policies. Alternatively, you can use thrust::device_ptr to refer to your data, and thrust will also do the right thing, even without ex...
67,437,798
67,437,894
Pass Iterator to template but only accept certain data types
I am struggling a bit with passing iterators to functions. I want to accomplish something like this. void func(MyClass* foo, numberOfFoo); But I want to use iterators and it should support any stl-container. I know I can write a function like this: void foo(std::vector<MyClass>::const_iterator start, std::vector<MyClas...
If you don't need overloads, you don't need SFINAE, and could go for a simple static_assert using std::is_same_v and std::iterator_traits. A static_assert makes it possible to generate a really clear compilation error. #include <iterator> // std::iterator_traits #include <type_traits> // std::is_same_v template<c...
67,437,924
67,440,720
C++ getpid() vs syscall(39)?
I read that syscall(39) returns the current process id (pid) Then why these 2 programs output 2 different numbers? int main() { long r = syscall(39); printf("returned %ld\n", r); return 0; } and: int main() { long r = getpid(); printf("returned %ld\n", r); return 0; } I am running my program i...
Making system calls by their number is not going to be portable. Indeed, we see that 39 is getpid on Linux, but getppid ("get parent pid") on macOS. getpid on macOS is 20. So that's why you see a different result between getpid() and syscall(39) on macOS. Note that macOS, being a BSD kernel derivative, is not related t...
67,437,932
67,438,321
OpenGL object not scaling properly
I want to scale a triangle with a model matrix. I have this code: void Triangle::UpdateTransform() { mView = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f)); mModel = glm::scale(glm::mat4(1.0f), glm::vec3(2.f)); mModel = glm::translate(glm::mat4(1.0f), mLocation); mMVP = mProj*mView*mModel; } Wit...
The 1st argument of glm::scale and glm::translate is the input matrix. These functions define a matrix and multiply the input matrix by the newly specified matrix. In both cases, you specify the Identity matrix (glm::mat4(1.0f)) for the inout matrix. You have to pass mModel as the input matrix. e.g.: mModel = glm::tran...
67,438,891
67,439,374
Preferred way to understand object type at runtime
Consider I have a Plant class that has derived Fruit and Vegetable classes, and Fruit class has some more derived classes, like Orange and Apple, while Vegetable has derived Potato and Tomato. Assume, Plant has Plant::onConsume()=0; method: class Plant { public: virtual void onConsume(void)=0; }; class Fruit:publi...
One option would be the visitor pattern, but this requires one function per type in some class. Basically you create a base class PlantVisitor with one Visit function per object type and pass add a virtual method to Plant that receives a PlantVisitor object and calls the corresponding function of the visitor passing it...
67,439,483
67,439,699
What are the priorities when calling template and non template functions?
Why does this: #include <iostream> using namespace std; template <class T> void f(T t) {cout << "A";} template <> void f(float x) {cout << "B";} void f(float x) {cout << "C";} int main() { float x; f(x); f<>(x); f<float>(x); return 0; } display this: CBB ? It's very unclear for me especially ...
As Walter E Brown teaches in his 2018 CppCon talk there are levels of priority for templates based on specialization: non-template overloads are always picked first; non-templates are more specialized than templates themselves. specialized templates (your template <> void f(float)); the way I remember it is these type...
67,439,885
67,440,084
Why is the C++20 concept not compatible with "const auto&"?
template<typename T> concept Octet = 1 == sizeof(T); // ok Octet decltype(auto) c = 'a'; // ok void f1(const auto&) {} // ok void f2(Octet auto) {} // ok void f3(Octet auto&&) {} // error: expected ‘auto’ or ‘decltype(auto)’ after ‘Octet’ void f4(Octet const auto&) {} // error: cannot declare a parameter with ‘de...
As seen in [dcl.spec.auto], when you use a placeholder here, the constraint needs to immediately precede the auto: placeholder-type-specifier: type-constraint_opt auto type-constraint_opt decltype ( auto ) This is simply a matter of syntax. The constraint isn't a general specifier like const is; it doesn't have a fle...
67,440,153
67,440,651
CMake configuration CMakeLists.txt
I would like to set up cmake for a project but I don't know how to do with this architecture : src/ control/ file.cpp file.h factory/ file.cpp file.h model/ file1.cpp file1.h ... file9.cpp file9.h ui/ file.cpp file.h main.cpp I guess it seems easy to people with ex...
I would use something along these lines: cmake_minimum_required(VERSION 3.12) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) project(test1) find_package(OpenSSL REQUIRED) find_package(Qt5 COMPONENTS Core REQUIRED) add_executable(${PROJECT_NAME} main.cpp src/control/file.h ...
67,440,689
67,440,770
circular doubly linked list insertion at the end
I was going through dsa doubly circular list, and was practicing insertion of elements to it, after entering the first element my program ends abruptly.....is there a mistake in my insertafterfunction.i get a segmentation fault error .just help me through I cant find what has gone wrong.. #include<iostream> struct Node...
For example this while loop within the function insertafter while(existingnode->next!=headnode){ existingnode=existingnode->next; } invokes undefined behavior because after calling the function insert data members prev and next of the head node are equal to nullptr. See the function insert void insert(int data){ ...
67,440,694
67,440,850
Get all pixel data of an image in a string as quickly as possible
I need to get all the pixels data of an image in a string, with each pixel taking 6 characters, 2 for each RGB channel, i'm storing them in HEX, so the 0-255 can be written as 00-FF, so, for example, an all white pixel would be "ffffff", and an all black one "000000". This is the code i currently have, using OpenCV, it...
If speed is an issue, then get rid of the stringstream altogether and just fill the string manually using some bit-shifting to calculate the hex digits, eg: Mat image = imread("image.jpg"); resize(image, image, Size(288, 160)); const char *hexDigits = "0123456789abcdef"; auto start = high_resolution_clock::now(); st...
67,440,802
67,440,903
Point CMake to proper Python header inside conda env?
I am trying to embed Python code in C++ and use the packages in a Conda environment. I have: // main.cpp #include <Python.h> int main(int argc, char *argv[]) { Py_Initialize(); return 0; } And in CMakeLists.txt I added: find_package(Python3 COMPONENTS Interpreter Development) I run cmake with my Conda env (c...
When using find_package, you also have to link it to your targets: find_package(Python3 REQUIRED COMPONENTS Interpreter Development) add_executable(main main.cpp) # Adds the proper include directories and link to libraries target_link_libraries(main PUBLIC Python3::Python) As for the documentation on how CMake works...
67,441,086
67,442,403
Change whole rvalue array
I want to pass several ints in the constructor and change field of the structure like this: struct testStruct { testStruct(int argIntArray[]) { intArray = argIntArray; } int intArray[5]; }; void main() { testStruct test1(new int[5]{1,2,3,4,3}); } But I can't do it like that. intArray = argIntArray; = "...
Considering my limitations (I can use only C functions), memmove() will do the trick: #include <cstring> const unsigned int markArraySize = 5; struct TestStruct { TestStruct(int argIntArray[]) { memmove(intArray, argIntArray, sizeof(int)*markArraySize); } int intArray[markArraySize]; }; int main() { i...
67,441,161
67,442,113
How do create a word ladder?
I'm trying to create a word ladder, by using a linked list as a dictionary of words, and a queue to hold the word to be changed. In the while loop of the queue, it reaches the first word in the dictionary (the word "toon" and changed to "poon") and stops. How can I make it continue until it reaches the targeted word? H...
Algorithm It seems you were on the right track, trying to implement something like BFS, so I'm not going to explain the algorithm for a "Word Ladder" in detail. But a high-level overview is: Push the start word in the queue Run a loop until the queue is empty Traverse all words that differ by only one character to the...
67,441,634
67,441,986
How to disable a CMAKE option
On ${CMAKE_CURRENT_SOURCE_DIR}/JUCE, there is: option(JUCE_BUILD_EXTRAS "Add build targets for the Projucer and other tools" OFF) if(JUCE_BUILD_EXTRAS) add_subdirectory(extras) endif() link: https://github.com/juce-framework/JUCE/blob/master/CMakeLists.txt#L57 So this is what I did: set(JUCE_BUILD_EXTRAS OFF) add...
The easiest way to guarantee that this will be overridden correctly from a parent CMakeLists.txt is to set it as a CACHE variable with a FORCEd value: set(JUCE_BUILD_EXTRAS OFF CACHE BOOL "" FORCE) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/JUCE) This will ensure that any state that may already exist from a previous...
67,442,043
67,559,513
Passing data buffers from C++ to LabVIEW
I am trying to create a LabVIEW DLL and call it from a C++ program but I am facing a problem of data passing. A scientific camera I recently bought comes with a LabVIEW SDK, and nothing else. The example program provided with the SDK is mainly a while loop around two functions, ReadData and DecodeData. ReadData collec...
It is a little tricky to answer in this specific case but assuming that the problem is that NULL values in the buffer data are causing issues then it might be worth looking at the option to use String Handle Pointers for the String-Type controls and indicators of the VIs you are exporting. This option can be selected d...
67,442,145
67,442,215
How can I stop adding to a std::vector once an element has been added
I am trying to make boids simulation. What I am currently doing is checking if boids are in each others range and adding their memoery address to a std::vector called withinSensoryRange if they are. Here is the code. struct Boid { float sensoryRadius = 50.0f; std::vector<Boid*> withinSensoryRange; }; std::vect...
You can use std::find to check if an item already exists in a container. Or you could use a container that contains unique keys e.g. std::unordered_set. Caution!! You need to be very careful when storing addresses. If the object moves or goes out of scope the address becomes invalid. This is in fact what can happen in ...
67,442,609
67,446,973
How to remove certain file from a list in .pro file?
When compiling Project 1 a bunch of object files including the main.o are put into buildfolder. Now I like to use these object files in Project 2 like a library, so what you can do is add all files manually to the the LIBS assignment by //project2.pro LIBS += $$buildfolderProject1/compressedair.o \ $$buildfolde...
There is a way to remove a certain file from list. For explanation: NOT WORKING: //project2.pro LIBS += $$buildfolderProject1/*.o LIBS -= LIBS -= $$buildfolderProject1/main.o WORKING: //project2.pro myObjectFileList = $$files($$buildfolderProject1/*.o) myObjectFileList-= $$buildfolderProject1/main.o LIBS += myObje...
67,442,615
67,451,907
Linked list template implementation and operators overloading
I am pretty new to templates in C++ and I'm having some trouble understanding them for the moment. So, someone gave me the next linked list implementation using templates, and the operators overloading is very unclear for me. Here is the code: #include <iostream> using namespace std; template<typename T> class List; ...
I guess the answer to your question can be found in the second edition of C++ Templates: The Complete Guide on 2.4 Friends on page 30: Generally operator >> and << is overloaded for standard input std::istream and output streams std::ostream so you can read from input and write to abstract output streams. This can be d...
67,442,712
67,445,721
fast rounding fixed point number
Let's say I treat my integer as if it has 4 fraction bits. And now 0 is zero, 16 is one, 32 is two, and it goes on. When rounding, numbers in range [-7, 7] becomes 0, [8, 23] becomes 16. My code is this: std::int64_t my_round(std::int64_t n) { auto q = n / 16; auto r = n % 16; if (r >= 0) { if (r >=...
With return (n + 8 + (n>>63)) & (~15ll); one can shave off the branch from my_round2(), and ensure the original symmetry at zero. The idea is that signed type >> (sizeof(signed type) * 8 - 1) is -1 for negative values and 0 for positive values. Clang is able to produce branchless code for the original my_round2() but ...
67,442,752
67,442,788
Class private member wont change in function
using namespace std; class map { private: float result= 0; public: void func_1(); void setres(float counter); float getres(); }; void map::setres(float counter) { result= counter; } float map::getres() { return result; } void map::func_1() { float num_0=0, num_1=0, ...
Within the function you are creating a local variable of the type map map run; the data member result of which is changed. That is the function does not change the data member result of the object for which the function is called. Moreover for example in this code snippet cout << run.getres() << " Result." << endl; if...
67,442,964
69,364,621
Does the number of iterations of the 'for' loop change if the second argument changes in one of the iterations?
i've this code here: for(i = openGates[0]; i < closeGates[0]; i++) { if(str[i] == '(') { closeGates.removeFirst(); openGates.removeAt(1); } } If brace found, closeGates[0]'s value will change. Will it change the number of iterations?
Yes, the iteration-expression is executed after every iteration of the loop. Reference for this answer : https://en.cppreference.com/w/cpp/language/for
67,443,291
67,445,015
mips-g++-5.4 listing bnez skips div instruction
I'm trying to understand why mips-g++ compiles a simple division subroutine where it skips the actual div instruction with a bnez v0, <jmp> (pseudo inst for bne). My understanding is that if the divisor is zero it makes sense to skip div and trap or break in this case. Why should it branch if the divisor is not zero? I...
As @EOF mentioned in a comment, MIPS has the concept of branch delay slots. This is from the description of BNE (emphasis mine): If the contents of GPR rs and GPR rt are not equal, branch to the effective target address after the instruction in the delay slot is executed. So the DIV always gets executed. You might th...
67,443,310
67,453,037
Non-type parametric template function, error: reference to non-static member function must be called
I am trying to use a not-type parametric template function as a member of a class and am running into errors. Below is a minimum working example #include <iostream> enum Mode {ka, kb, kab}; class Foo { public: Foo(const double& x = 1.0, const Mode& y = ka) : x_(x), y_(y) {;} Mode get() const{ return ...
The problem with your code is that a template argument has to be compile-time constant. For a function call this means it has to be constexpr while for a class method this means it has to be static. You have only two options: Either you leave the configuration of the Mode to run-time and allow the user to potentially ...
67,443,332
67,443,406
Constructor inheritance behaving weirdly
In the following situation: class A { protected: int m_int; A() : m_int{-2} {}; public: A(const A& a) { m_int = a.get(); } A& operator=(const A& a) { m_int = a.get(); return *this; } int get() const { return m_int; } }; class B : public A { protected: using A::m_int; public: // s...
The problem is the constructor in D: D(const B& b) { D(b.get()); } This will be the constructor that is called. And it doesn't copy the value from b, instead it creates a new and temporary D object which is promptly destructed as the constructor function exit. You have the same problem in the corresponding C construct...
67,443,342
67,443,354
Tring to create a unique pointer gives me an error
I have a Boid class with the following constructor Boid(olc::vf2d _position, float _angle, olc::Pixel _color) : position(_position), rotationAngle(_angle), color(_color) { }; I need to create a vector of unique pointers of Boid objects. Following online examples, I tried to do the following std::vector<std::un...
std::unique_ptr can't be copied, it doesn't have copy-constructor but has move constructor. You can use std::move to convert boid to rvalue then the move constructor could be used. std::unique_ptr<Boid> boid = std::make_unique<Boid> ( olc::vf2d(rand() % 600 * 1.0f, rand() % 300 * 1.0f), rand() % 7 * 1.0f, ...
67,443,372
67,443,465
I don't understand what is wrong with my code (pointers and template)
#include <iostream> #include <stdio.h> #include <float.h> using namespace std; template<class T> void getMinMax(T tab[], int nbPers, float *min, float *max){ *min = FLT_MAX; *max = 0; for (int i = 0; i < nbPers; i++){ if (tab[i] < *min){ *min = tab[i]; } if (tab[i...
A useful tip when debugging template stuff: get rid of the template! In this case, rewrite getMinMax as a plain old function. If it works, then you know the problem was something specific to templates. If it doesn't, then you made a mistake unrelated to templates. In fact, unless the template you're writing is very...
67,443,418
67,444,253
How do I pass a template function to a thread within the same .cpp file?
I have an assignment to implement a parallel version of the longest common subsequence algorithm (just calculating the LCS length). The program must use threads in order to complete the task as quickly as possible (at least, faster than a sequential implementation). Ideally, it should also utilize TLS in the threads. W...
You are right, you cannot pass a function template as if it was a function. They are different things, just like a cookie cutter is not a cookie. You have two main problems in your code. First, since ParFor::parfor is a template, you can only take a member function pointer to it if you provide template parameters that...
67,443,592
67,443,905
Recieve Data from ESP32 Socket Server with Android
I'm trying to recieve data from my ESP32 with an Android App. Sending data from my phone isn't a problem. I just don't get anything. It doesn't show an exception and also not a msg. My code so far: //In the onCreate method: Connection connection = new Connection(); connection.execute(); //The Connection: class Connect...
Your Android code is calling input.readLine() but your ESP32 code is only sending a single character, not a line, so of course the client never shows any input. Try sending a line. client.writeln('A'); or client.write("A\n"); The string in the second version might need to be "A\r\n"; I'm not 100% clear wh...
67,443,822
67,443,864
Add instance of class in vector
I am trying to make a static vector of a class (called "radsurf") so when a instance is constructed it will be appended to the vector. But I have had some issues when compiling the code using g++. It tells me there is "no matching function for call" for the static vector of the class. Can someone help me? Tree View: ├─...
In C++, the this keyword is a pointer to the current object instance. Your std::vector<radsurf> is a vector of radsurf objects, not pointers to radsurf objects (not radsurf*s). The static vector should instead by a std::vector<radsurf*>, meaning it contains a list of radsurf pointers. If you instead want a vector of va...
67,444,083
67,452,778
PlatformIO collect2.exe linker error with: undefined reference to
I am trying to modularize my code by crating git submodules for libraries/dependencies, but I am running into a linker problem collect2.exe. I am compiling and building using PlatformIO in VScode. The linking error occurs with the following structure. Please note I have simplified the names and structure for illustrati...
In order for the build to be successful the following two lines had to be added to the platformio.ini file: lib_extra_dirs = lib/MyLibFolder/ExternalLibFolder lib_ldf_mode = chain+ I found one really strange thing while debugging to which I dont have an answer to. I am running FreeRTOS and the truly strange thing is t...
67,444,204
67,444,468
How to use glVertexPointer() and glDrawArrays with a array of GLint's correctly to draw quads?
I have been trying to optimize my drawing code for a model visualizer i am working on, here is the old solution I used before: glBegin(GL_QUADS); glColor4ub(255, 255, 255, 255); for (int i = 0; i < C.vertices_prepared.size(); i+=12) { glVertex3i(C.vertices_prepared[i], C.vertices_prepared[i+1], C.vertic...
You'll get an invalid GL_INVALID_OPERATION operation error. Only a few operations are allowed within a glBegin/glEnd sequence. It is used to specify a vertices with glVertex. You don't need glBegin/glEnd at all when you use fixed function attributes and drawing with glDrawArrays. However enable and disable the GL_VERTE...
67,444,434
67,444,697
How can I make a header file appear on every new project
I'm very new to programming so hopefully I don't sound too dumb. I'm using visual studios to learn on and reading Bjarne Stroustrup's book "Programming Principles and Practice Using C++" and the book uses a header file called "std_lib_facilities.h" for every example. I've been copying the file into every single program...
Yes, There is a way to add automatically the additional libraries and header files into every project you create. Navigate the window into MSBulid\v4.0 by using the below command in run window %localappdata%\Microsoft\MSBuild\v4.0 Then you can find the Microsoft.Cpp.Win32.User.props Right click the Microsoft.Cpp.Win32....
67,444,702
67,444,739
Increasing value after changing a references does not increase both values
When changing the target of a reference in c++, and increasing the initial value, why are a and b not the same in the following example: Output: a = 11 / b = 10 using namespace std; void SampleMethod(int& val) { val++; } int main() { int a = 5; int b = 10; int& ref = a; ref = b; SampleMethod...
void SampleMethod(int& val) { val++; } int main() { int a = 5; int b = 10; int& ref = a; //ref bound to a and has a's value i.e. 5 ref = b; // ref doesn't point to b now but just sets the value of a to 10 SampleMethod(a); // a gets incremented inside the function and becomes 11 cout << ...
67,444,955
67,445,876
Relationship between alignment of class fields and alignment of object instances in C++?
Given the following C++ class: class X { public: uint8_t a; uint32_t b[256] __attribute__((aligned(32))); }; How can the compiler ensure that the storage for b is 32-byte aligned, when an instance of X is presumably word-aligned? Does the aligned attribute only specify alignment relative to the object instance...
The standard says following: [basic.align/2] A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to alignof(std​::​max_­align_­t) ([support.types]). The alignment required for a type may be different when it...
67,445,694
67,445,832
How to free memory allocated in a function without returning its pointer?
I have a function like this: int fun(){ int* arr = new int[10]; for(int i = 0; i < 10; i++){ arr[i] = 5; } delete[] arr; // return arr[6]; } int main(){ std::cout << fun(); return 0; } What am i going to do is to free the memory whick is pointed to by the pointer arr. But the fu...
Unless it's for academic purposes, you rarely see a C++ program using manual memory allocation, you don't need to do it since you have a set of containers in the STL containers library that do this memory management reliably for you. In your particular example, a std::vector is recommended. That said, to answer your qu...
67,445,704
67,445,757
Why does this code snippet give a segmentation fault?
I am not able to understand why this simple code gives a segmentation fault. #include <iostream> using namespace std; int main () { vector <vector <int>> graph; graph [0] = vector <int> (); graph [0].push_back(0); cout << graph[0][0]; }
You declared an empty vector vector <vector <int>> graph; So you may not use the subscript operator to change non-existent elements of the vector. You could declare the vector at least with one element like vector <vector <int>> graph( 1 ); In this case this statement graph [0] = vector <int> (); shall be removed an...
67,445,736
67,533,900
Qcombobox remove and add item in C++ Qt
Creating a combobox in Qtableview2 column 1 and passing values from Qtableview1 column1 so i am storing column1 table1 values in Qstringlist and passing to combobox void cymodel::rowvalues() { QAbstractItemModel* table1 = ui.tableView->model(); QAbstractItemModel* table2 = ui.tableView_2->model(); QStringLi...
thnks,,,i solved this.. to remove the items in combobox which are not in colvallist1..without change in selection here is the code-- void cymodel::rowvalues() { QAbstractItemModel* table1 = ui.tableView->model(); QAbstractItemModel* table2 = ui.tableView_2->model(); QStringList colvallist1; for (int r ...
67,445,740
67,446,727
Error in code after reading data from file with the help of fstream
While creating a simple stock management system, I encountered some problem after adding a new item in the list. My code will explain better. #include <iostream> #include <fstream> #include <iomanip> using namespace std; // For sake of speed class INVENTORY { char name[10]; int code; float cost; public: ...
I found a solution. After reaching eof if you try to do inoutfile.tellg() it will return -1. Instead use inoutfile.clear() to clear the eof tag and then use inoutfile.tellg().