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
61,585,226
61,585,308
How can I create simple C++ code that runs fine with no Data Execution Prevention (DEP) but will crash with DEP on?
While I understand code that is not marked "executable" will trigger a DEP crash, I am trying to understand what type of common coding practices (in legacy Windows apps) would result in this type of crash.
Something like this: int main() { char* s = (char*)malloc(1); s[0] = '\xC3'; void (*p)() = (void (*)())(s); p(); } ATL did this to allocate thunk for WndProc. The purpose of such WndProc thunks is to embed context parameter and use a method for WndProc instead of a function not taking extra context pa...
61,585,404
61,612,820
cross platform MultiByteToWideChar
Is boost::locale::conv::to_utf(here) same as the windows api MultiByteToWideChar (here) ?
At least they differ in possible target encodings: MultiByteToWideChar converts various code pages to UTF-16 Boost Character Set Conversions can convert to UTF-8, UTF-16, UTF-32 Also set of supported source encoding may differ. If the question is whether boost function uses MultiByteToWideChar / WideCharToMultiByte w...
61,585,749
61,585,810
How to pass a derived class to function with base class as an arguement
I am still a beginner in programming and I am trying to pass an object from a derived class to a function with a base class as an arguement. But when I print the output, it would only print the attributs from the base class. Any atrributes which is in derived class won't come out. How to print it? Given this code: #in...
When you assign a derived object to a base class object, only members of the base class are copied to the new object; it couldn't be any other way, if you think of it. This is called slicing. If you, instead, store a pointer or reference to the derived object in a base class pointer, it still points or refers to the or...
61,585,961
61,650,124
PCL, SACSegmentation detecting spheres
I'm trying to find spheres from a point cloud with pcl::sacSegmentation using RANSAC. The cloud is scanned with an accurate terrestial scanner from one station. The cloud density is about 1cm. The best results so far are shown in the image below. As you can see the cloud contains 2 spheres (r=7,25cm) and a steel beam w...
After some investigation I have come in to conclusion that I can't find spheres with SACSegmentation from a cloud that contains lot of other points that don't belong in any sphere shape. Like in my case the beam is too much for the algorithm. Thus, I have to choose the points that show some potential being a part of a ...
61,586,272
61,587,825
Using sigaction without SA_RESTART and preventing an infinte loop
I have the following code: struct sigaction act = {{0}}; act.sa_handler = handler; sigaction(SIGINT, &act, nullptr); while (true) { std::cout << "input:"; std::getline(std::cin, line); // Handle line } When I receive SIGINT, the program gets stuck in an infinite loop. I can't simply set SA_RESTART (like h...
When getline is interrupted an error flag will be set on cin. That needs to be cleared to prevent getline from continuously failing. if (flag) { std::cout << "got SIGINT" << std::endl; flag = false; std::cin.clear(); }
61,586,430
61,587,376
Why does my regex work JavaScript but not in C++?
My regex is supposed to capture the names of all function declarations: ([\w{1}][\w_]+)(?=\(.+{) In JavaScript it works as expected: 'int main() {\r\nfunctionCall();\r\nfunctionDeclaration() {}\r\n}'.match(/([\w{1}][\w_]+)(?=\(.+{)/g); // [ 'main', 'functionDeclaration' ] In C++ Builder I get this error: regex_error...
The correct regex string literal for C++ is this: "([\\w{1}][\\w_]+)(?=\\(.+\\{)" The { must be escaped, unlike in JavaScript.
61,586,586
61,586,635
Non-static class function pointer
I am trying to create a pointer to a class non-static function to call it by several objects. Example class: class A { public: int getNumber() { return 5; } }; I have created a pointer to the class function with the same signature: int (A::*funcPtr)(); After this, I have initialized it like this: funcPtr ...
Following would work: funcPtr = &A::getNumber;
61,587,040
61,590,151
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’}
the code on monte_carlo.hpp is : class Histogramme{ protected: std::vector<double> echantillon; unsigned int nb_boxes; double lbound; double ubound; double box_width; public: Histogramme(double min_intervalle, double max_intervalle, unsigned int n) : nb_boxes(n), ...
I delete "const" from the Histogram parameter in the friend function and in the function declaration, the error message is no longer there Great But I get the error message " error: 'std::vector Histogram::sample' is protected within this context" I'm not getting any errors with or without the const. here is what I...
61,587,048
61,587,219
C++ prime loop test executes in false manner
I'm currently taking on some challenges and looking for stuff to do to test my very new abilities in C++, and I decided to do mostly math, in this case the euler problems. Below is some code to find the greatest prime factor of a given number, however for some reason it does not go into the for loop, I have even run co...
600851475143 is too large for int type in typical environment, which is 32-bit long and can store upto 2147483647. 600851475143 in binary is 1000 1011 1110 0101 1000 1001 1110 1010 1100 0111. In typical environment, it is truncated to 32-bit long: 1110 0101 1000 1001 1110 1010 1100 0111 The top bit of this is 1, so it...
61,587,582
61,588,054
Potential deadlock in thread-safe stack C++
In the book "Concurrency in Action", there's an implementation of thread-safe stack where mutex is acquired/locked upon entering pop() and empty() functions like shown below: class threadsafe_stack { private: std::stack<T> data; mutable std::mutex m; public: //... void pop(T& value) { ...
how does this code not run into a deadlock, when a thread, that has acquired the lock upon entering pop() is calling empty() which is protected by mutex as well? Because you are not calling empty member function of threadsafe_stack but you are calling empty() of class std::stack<T>. If the code would be: void pop(T& ...
61,587,849
61,587,903
find by key in std::set
I struggle with a std::set that should support custom compare operations. My goal would be to be able to call find with just the key argument, without first creating an object of the set type. Something like this: #include <set> #include <cstdint> #include <vector> class TestItem { public: std::uint64_t id; ...
It is possible. But your comparator must be a transparent one. And the member functions in functor need to be const struct TestItemCompare { using is_transparent = int; // actually any alias will do, void, custom type bool operator()(const std::uint64_t& lhs, const std::uint64_t& rhs) const { return lhs...
61,588,854
61,589,075
How can I define a templated function which takes a map and a lambda to search map-pair by value?
What I currently have is this: std::find_if(mmap.begin(), mmap.end(), [streamShm](const std::pair<int, StreamMapContainer> pair) { return pair.second.pcktRefShm->id() == streamShm->id(); }); and I want to re...
Most of the body of the function is right. You just incorrectly used typename inside parameter list: template<template <typename...> class Map, typename K, typename T, typename Lambda> typename Map<K, T>::const_iterator findMapPairByValue(const Map<K, T> &map, const Lambda &lambda) { return std::find_if(map.begin()...
61,589,016
61,589,035
stof returning 0 for object, works fine for normal variables
I have a vector that stores some values, and a class Weather with some methods. One of the methods is to convert a string to a float using stof, and do a calculation on that new value and return it. I see that stof works for one of my independent variables that doesn't belong to a class, but when I call this method tha...
(1/6) is 0 because it's an integer division. Thus everything becomes zero. newValue = ((newValue) * (1.f / 6.f)) / 1000.f; should work.
61,589,249
61,589,368
C++ error: fields must have a constant size
can someone please give me a hint how to solve the following problem: clang++-7 -pthread -std=c++17 -o main createLibrary/configuration.cpp createLibrary/growbox.cpp createLibrary/helper.cpp createLibrary/httprequests.cpp main.cpp In file included from createLibrary/configuration.cpp:2: In file included from createLibr...
Declare maxNameSize like this // configuration.h class configuration { public: static const int maxNameSize = 30; ... }; And no need to define it in configuration.cpp. Your way doesn't make maxNamesize a compile time constant. EDIT, I am assuming that configuration is a class. If it's a namespace then do the f...
61,589,487
61,590,441
How to define a class type conversion to a pointer to function?
I am trying to understand more Class-type conversion. I am reading C++ primer 5ed. So I've tried this code: int add(int x, int y) { return x + y;} struct Foo { //operator(int(*)(int, int))(){return add;} // error using pfn = int(*)(int, int); operator pfn(){return add;} // OK double value = 5.45; }; i...
So why I cannot directly define conversion for my class using the type int(*)(int, int) but I can with a type alias? The grammar for the "operator TYPE" name of a conversion function is much more restricted than a more general declarator or type-id. It doesn't allow parentheses at all, only a type specifier (like a...
61,589,764
61,589,984
How can I create a regression of x versus y?
I read three vectors from a csv file: x, y_low, y_high. x is the independent time series variable. y_low and y_high are the low and high observations of the dependent variable. I want to write a function that will take these three inputs as arguments and use an algorithm to find linear regression x versus y. I basica...
Is it possible to estimate y from the given dataset and get a series of estimates? Yes. The difficulty is there are multiple ways of estimating your ys. The simplest would to take the midpoint of y_low, y_high.
61,589,853
61,599,821
Why it calculating Wrong Pisano period
long long fibonacci_fast(long long n) { long long a[n]{0}; a[0]=0; a[1]=1; for(int i=2;i<=n;i++) a[i]=a[i-1]+a[i-2]; return a[n]; } and the fuction to calculate pisano period is long long get_pisano_period(long long n,long long m){ vector<long long> vec{0,1}; for(int i=2;i<=n...
The code tries to evaluate the Pisano period (the period with which the sequence of Fibonacci numbers taken modulo n repeats) given the modulo and what looks like a limit, but there are multiple issues. In fibonacci_fast, a is declared as a variable length array, a non-standard compiler extension in C++. It is also in...
61,590,100
61,590,440
C++ friend function with a template argument enable_if
I'm struggling with a friend function for a struct that has a template argument with enable_if: // foo.h #ifndef FOO_H #define FOO_H #include <type_traits> template< typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type > struct foo { foo(T bar) : bar(bar) {} T get() { ret...
The friend declaration refers to a non-template operator, while the definition out of the class definition refers to a template one, they don't match. You might want // forward declaration of the class template template< typename T, typename X = typename std::enable_if<std::is_arithmetic<T>::value>::type > stru...
61,590,133
61,590,925
Qt Creator does not autocomplete and colorize the code
I am having a problem with Qt. I am writing C++ code in Qt Creator but it doesn't autocomplete and colorize some of my functions. Here is the sample of my code: void Form::hide_button(){ this->ui->pushButton_10->hide(); } void Form::on_pushButton_clicked() { if(push_button_error() == 0){ if(this->ui->c...
Various old Qt Creator versions have this problem. You can fix it with following steps. go to Help select About_Plugins change ClangCodeModel (set or reset) check Some times the code update in the editor will be stuck, for that you can do following steps to fix it. go to Tools select About_Plugins click Reset_Code_M...
61,590,627
61,605,297
CMake Cross Platform Compile: file cannot create directory: /data. Maybe need administrative privileges
I am trying to compile, depending on the detected system, a tar.gz file, or a .deb file. Using the below code, I am able to successfully create a .deb file when the detected system is Linux, however when compiling for QNX which recquires a `.tar.gz' file, I receive the error: file cannot create directory: /data. Maybe...
As Stephen Newell mentions in a comment: My guess is the leader slash in your install command is making cmake treat it as an absolute directory. What happens if you just use data instead of /data/? Using data instead of /data/ solved the problem.
61,590,721
61,590,855
Does C++20 remove the requirement for class members to be in ascending order?
In C++17 there is normative text [class.mem]/17: Non-static data members of a (non-union) class with the same access control (Clause 14) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified. A...
This is still guaranteed by [expr.rel]/(4.2), describing the behavior of built-in <, <=, >, and >= expressions on pointer values. If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare...
61,590,804
61,591,878
How to install gcc-9 on debian:latest docker
In order to use the C++17 include <filesystem> I need gcc-9 package in my debian docker. By default debian:latest (aka 10 or buster) will install gcc 8.3.0 from the regular distro repo. Is there any PPA, testing repo, whatever, where I can easily install a gcc-9 (or later) package (i.e. not build it from source) Thanks...
In my Dockerfile I did: FROM debian:latest AS env ... RUN echo 'deb http://deb.debian.org/debian testing main' >> /etc/apt/sources.list RUN apt update -y RUN apt install -y gcc note: I added these line after the install of build-essential so technically the container install the "default" gcc then it is updated by the...
61,590,817
61,591,989
Using enum class write the factory method
I need to use enum class and factory method with static function create to be able to create the appropriate type of Object enum class Object { First, Second, Third }; Each object has function1, function2 and function3. I searched about enum class and factory method but don't know how to combine them.
It is quite common to parameterize a factory method, say an Object factory named Object::create(), over a tag, e.g. over a non-type template parameter such as an enum, say ObjectTag. The Object::create() function template parameterized over ObjectTag exposes a public factory method that is specialized for each specific...
61,591,211
61,596,179
GLSL log returning an undefined result
I'm trying to draw the mandelbrot set. I've created the algorithm on the CPU, but now I want to reproduce it on the GPU, but the code behaves differently. In the CPU program, at one point, I take the std::abs(z), where z is a complex number, and write the value in the green channel on the screen. On the GPU, I take the...
It turns out that GPU doesn't really like when you ask it to calculate a log of a very large number. From what I gather, log (actually ln) is implemented as the taylor series. This is unfortunate because it contains polynomials to the n-th power for n members. However, if you have a number represented as x = mantissa *...
61,592,200
61,592,281
std::array::iterator that ignores the size template
I am implementing a function that wants to loop over a number of elements in an std::array, but I don't really care how long the std::array is. So I was thinking of the following function: #include <stdio.h> #include <array> #include <iterator> void foo(std::array<bool,0>::const_iterator begin, std::array<bool,0>::con...
You can just make it a function template as template <typename I> void foo(I begin, I end) { std::cout << "iterator"; } You don't need to care about container type (and the size), you can pass iterators of std::array, std::vector and std::string and so on, even raw pointers (which also satisfies iterator's require...
61,592,209
61,604,661
How can I generate all permutations of length n from a set of k elements?
For example I have this set k=5 of elements [1,2,3,4,5] and I want all permutations of length n=2. 1,2 1,3 1,4 1,5 2,1 etc etc. Thing is I can't use STL, external math libraries etc. What I tried is generating all permutations of all the elements using Heap's algorithm, and then all the permutations of n elements whe...
I think you can do it in two steps, first, generate combination of k elements out of a set of n, then print permutation of each combination. I tested this code and works fine: #include <iostream> using namespace std; void printArr(int a[], int n, bool newline = true) { for (int i=0; i<n; i++) { if (i > 0) ...
61,592,220
61,592,365
Hide class implementation using static lib c++
I am working on a project and I need to make a class which I will share using a static library. So far I wrote the implementation inside a .cpp file and shared only de .h and .lib files. If I use those inside another project and I try to debug something that uses my class I am able to see the full implementation writte...
If I use those inside another project and I try to debug something that uses my class I am able to see the full implementation written in the .cpp file. Is there any way I could hide the implementation? You can only see the implementation in .cpp because: .lib has debug information not stripped. .cpp file happens to...
61,592,774
61,593,081
How to use double point to handle matrix?
I want to implement the matrix multiplication in c++.And here is my code: #include"math.h"; #include <iostream> using namespace std; int** create_matrix(int rows, int cols); int** calculate_matrix(int** matrix1, int** matrix2, int row_1, int col_1, int row_2, int col_2); void printMatrix(int** matrix, int rows, int c...
In this line: int** matrix_A_point_final = &matrix_A_point; This doesn't do what you think. Your stack matricies (matrix_A and matrix_B) are contiguous numbers representing all the rows and columns. Your dynamic matricies are rows of pointers to columns. These are different things, and you are conflating those with ba...
61,592,849
61,608,136
No narrowing warnings when using `emplace_back` instead of `push_back`
My colleague ran into an unexpected issue with emplace_back and I am trying to wrap my head around it. The following test.cpp is a minimal example that reproduces the issue: #include <vector> ...
In order to get the warning you need to compile with: $ g++ -Wsystem-headers -Wconversion test.cpp -o test In file included from /usr/include/c++/8/vector:60, from test.cpp:1: /usr/include/c++/8/bits/stl_algobase.h: In function ‘constexpr int std::__lg(int)’: /usr/include/c++/8/bits/stl_algobase.h:1001...
61,593,034
61,593,212
Space Invaders: All enemies in column die when shot
I am trying to program space invaders in C++ I am not an expert and decided to store the enemies in a multidimensional array. Here each enemy is a column. The rows are from top to bottom: x, y1,y2,y3,y4,y5 and enemy health. y1 is the lowest row (or the row of enemies closest to the player). When I currently shoot my b...
You are using common enemy health per each row, so all enemies in a row will die as you says. To avoid this, you have to allocate enemy healthes for each enemies. possible fix: for(int i=0;i<12;i++) { for(int j=1; j<6; j++) { if(distanceBetween(enemies[0][i], enemies[j][i], bullet.x, bullet.y)<20) ...
61,593,166
61,593,286
noexcept operator compile-time check
In bellow code I'm trying to use conditional exception specification for functions but compile fails, although if used outside function it works just fine. void may_throw(); // ERROR: expression must have bool type or be convertible to bool void check () noexcept(may_throw()); int main() { // works just fine! ...
Given void check () noexcept(may_throw());, noexcept specifier expects an expression convertible to bool, while may_throw() returns void and can't convert to bool. You should apply noexcept operator on may_throw() and specify it to noexcept specifier. i.e. // whether check is declared noexcept depends on if the express...
61,593,224
61,593,421
Returning custom string from exception::what()
How to build a custom string inside what() function of exception class and return it? The following code does not work but presents what I want to achieve: class divide_by_zero : public exception { public: divide_by_zero(int a) : a(a) {} const char * what() noexcept { stringstream ss; ss << "Divisio...
How to build a custom string inside what() function of exception class and return it? Don't do that. It won't work. Instead, build the custom string inside the constructor, store the string in a member, and return a pointer to the data owned by the member in what. Technically, you can delay building the string until ...
61,593,309
61,593,736
Serializing/deserializing a bitfield structure in c++
I have a typedef struct { uint32_t Thread: HTHREAD_BUS_WIDTH; uint32_t Member: 3; uint32_t Proxy:3; // Other members, fill out 32 bits } MyStruct; that I must transfer from one system to another as an item of a buffer comprising 32-bit words. What is the best way to...
If you need to read from other system which might have different endianess you cannot rely on a portable bitfield. A solution is to "expanse" your structure so that each field is serialyzed as a 32 bit value in the "transport" buffer. A safe implementation could be something like: typedef struct { uint32_t Thread:...
61,593,396
61,888,029
How to prevent orthogonal region transition for error handling
I want to create the following state machine, with Boost MSM: I would like to be able to prevent the Error event to trigger the AllOk + Error == InError transition if the orthogonal state is on "B". For example, specifying transition for all orthogonal states would be nice. Something like: {AllOk, B} + Error == {AllOk...
Ok, I find a solution: The Error event can be "catched" in the MainStateMachine. If it is not, an internal transition is triggered on the MainStateMachine, which will send the EnterError event to make the other orthogonal state switch to InError.
61,593,419
61,610,417
How to only process the macros in a C/C++ project without compiling it?
I'm trying to review a C/C++ project which is heavily dealing with macros and function-like macros. What I would like to do is to replace the define and function-like macros with their replacement. For example I have this file: #include <iostream> #define SUM(a,b,c,d) a+b+c+d using namespace std; int main(){ cou...
I've used gcc -nostdinc -E ... (or something similar) before. Can't test this at the moment; don't really remember exactly why I used it either
61,593,950
61,594,278
How does CMAKE tell the makefile to link a library?
I have a simple executable that uses functions from a library mylib at ~/mylib/lib/libmylib.so. On CMakeLists.txt, I tell CMAKE where to find the library and link it: find_library(MYLIB_PATH mylib HINT $ENV{HOME}/mylib/lib) target_link_libraries (output "${MYLIB_PATH}") after doing cd build; cmake .., the Makefile is...
For every executable and library CMake creates link.txt script which performs the linking step. This file is used in per-target build.make script via $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/<target-name>.dir/link.txt
61,594,155
61,594,315
reference initialization from a temporary object's member data issue
A non-const reference can be bound only to an lvalue so I have tried this: struct Foo { double value = 5.45; operator double&(){return value;} }; int main() { double& d = Foo{}; cout << d << endl; // seems ok 5.45 } d is a reference initialized from an unnamed temporary object Foo{}'s member data v...
So why I get the correct value 5.45? Because the behaviour of the program is undefined. Does my code yield a UB? Yes. You access an object outside of its lifetime. Is d a dangling referencing now? Yes. As you said: The temporary object along with its member have been destroyed. All previously valid references to...
61,594,259
61,712,021
Byzantine Consensus Randomized - Monte Carlo Implementation with matrix for value sending
In order to achieve the Bizantine Consensus, these 3 rules must apply: during every round each process must send a bit (with value either 0 or 1) to the others n-1 processes; before the start of a new round each process must have received a bit from every other process; in each round every process has sent his bit to a...
I solved this problem by creating a class Process with a Type and vote attribute and a getVote() method, Type: reliable, unreliable Vote: the vote (v0 at the beginning, it will converge to v following the protocol) setVote(): sets the vote. getVote(): if type is reliable then return the bit else return random number ...
61,594,521
61,594,628
Difference in default initialization of struct members
struct Date1 { int day{1}; int month{1}; int year{2000}; }; struct Date2 { int day =1; int month =1; int year =2000; }; struct Date3 { Date() : day(1), month(1), year(2000) {} int day; int month; int year; }; Is there any difference in terms of efficiency between those three options of default ini...
Is there any difference in terms of efficiency between those three options of default initialization of the struct member? No. In class member initializers are just syntactic sugar for a member initialization list so they all generate the same code. The real benefit comes from when you have multiple constructors lik...
61,594,577
61,595,745
Why should you include more than one value in a return statement?
I've seen instances where someone would use return statements with multiple values. For example: return 8, 10, 6; As far as I know, only one of these values will actually be returned. What is the benefit of using return this way? Specifically, this question appears on my homework. The statement: return 2 * 3 + 1, 1...
The statement return 2 * 3 + 1, 1 + 5; returns the value 6. This the trick of comma operator in C++. You can read more about it here: https://en.cppreference.com/w/cpp/language/operator_other A comma operator is basically a list of expressions separated by commas, they will be evaluated from left to right, and the resu...
61,594,647
61,601,178
Reading a specific line of a csv file and adding into array
I would like to select a specific line of a csv file and add its values into an array. For exemple if I select "two", the xyz array will be {0,1,2,3,4,5,6,7} Could someone help me ? test.txt : one,1,2,3,4,5,6,7,8 two,0,1,2,3,4,5,6,7 three,8,7,6,5,4,3,2,1 A simplified version of my program : #include <windows.h> #inclu...
Solved : #include <windows.h> #include <stdio.h> #include <fstream> #include <sstream> using namespace std; int main() { int xyz [8]; char name[50]; int i = 0; //int n; printf("Name ?"); scanf("%s", &name); // Input : two ifstream fichier("test.txt", ios::in); if(fichier) { ...
61,594,917
61,595,356
lambda capture of std function
The following code causes segmentation fault, but I can't understand why: #include <iostream> #include <vector> #include <functional> class State {public:int x; int y; State(int _x,int _y):x(_x),y(_y){}}; typedef std::function<bool (const State &s)> FuncT; std::vector<FuncT> funcs_outside; class Manager { private: ...
What am I doing wrong? getAnd returns a function object from a member function, which captures and accesses members. You call that member function on a local variable, and return the resulting function object to the outside of the scope. The members pointed by the function object no longer exist and calling the funct...
61,594,940
61,610,921
Avoid prompting users to redial when PPTP connection has been disconnected
I am establishing PPTP connection to the remote server programmatically using RAS api in Windows. The problem is that when server disconnects (for example server stopped) windows automatically prompts user to redial (see screenshot), I don't want this prompt to be shown since my app handles everything by itself but cou...
The problem was the RASEO2_ReconnectIfDropped option that I used for creating a connection. After removing it - prompt does not appear.
61,595,179
61,595,869
Can I call a C++ constructor function in dart ffi?
I'm new to ffi. But I successfully used dart-ffi with functions call. Now, I'd like to use a C++ object in dart ffi. I don't know if it is possible, but I tried like this. The prototypes of constructor call are : function_dart = lib .lookup<NativeFunction<function_native>>("constructor_function") .asFunction()...
C++ compilers use "name mangling" to ensure symbol names are unique. The fact that you had to add the -C option (or --demangle) to make it show up is a hint. For example, here is the mangled symbol for some_class::some_class(int, std::string): _ZN10some_classC2EiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE You...
61,595,618
61,595,821
Some errors have occurred with Thread
void* bubbleSort(int *data,int len){ int i = 0, j = 0, temp = 0; for ( int i = 0 ; i < len ; i++ ){ for ( j = i + 1; j < len ; j++ ){ if(data[i]>data[j]){ temp = data[i]; data[i] = data[j]; data[j] = temp; } } } } int ma...
First of all, the function you want your threads to run can only take one argument. If you want to pass different values to it, you'll have to use a struct (with data and len, in your case). Second, you don't have to do this: &bubbleSort. You should pass the function without referencing it: bubbleSort. Third, you have ...
61,595,800
61,596,188
Qt. Non-blocking progress dialog during huge amount of non-controllable calculations
I implemented a widget/dialog, which is just a gif animation inside (CircularProgressDlg). Our application consists of Login dialog part and MainWindow part. Between login is accepted and MainWindow is fully loaded there are 5 to 10 seconds of huge init() function. What I need is to launch my CircularProgressDlg when l...
Use the Qt Concurrent library, specifically its QConcurrent::run method to spawn a thread for your expensive task. You get back a QFuture that you can watch with QFutureWatcher. The QT documentation has an asynchronous image scaling example. I'm adding selected parts below. Creating a QFutureWatcher to be signaled whe...
61,595,990
61,596,251
How to find minimum distance using lambda
I have two classes Entity and Ship. Ship is inherited from Entity. They have x and y as attributes which represents there position on 2D plane. squared_distance function returns distance between a ship and an entity. class Entity { public: int id, x, y; Entity(int id, int x, int y) : id(id), x(x), y(y) {} ...
int squared_distance(const Entity& e, const Ship& s) { return pow((e.x - s.x), 2) + pow((e.y - s.y), 2); } std::min_element(std::begin(entities), std::end(entities), [&ship](const Entity& a, const Entity& b) { return squared_distance(a, ship) < squared_distance(b, ship); }); Note you need to update parameters in ...
61,596,021
61,596,105
Same code getting Time Out because of "if" statement on LeetCode
The question is taken from LeetCode in which we have to find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. My approach is O(N*N) which should not be acceptable but it is...
If we boil it down to the essential, you are comparing for (int i = 0; i < imax; ++i) { if ( some_condition(i) ) { // do something } } vs for (int i = 0; i < imax && some_condition(i); ++i) { // do something } The second loop terminates once some_condition(i) is false while the first always runs all...
61,596,097
61,596,232
C++11 features for generic and meta programming
Can we say that auto and decltype are part of generic programming? Can we say that constexpr is a feature for metaprogramming?
constexpr is most useful for metaprogramming, as it permits the compiler to pull certain parts of our code into the metaprogramming world. That doesn't mean that when you write constexpr you are always metaprogramming. I can declare a nice constant constexpr int x = 42 out of good habits but that doesn't mean I'm metap...
61,596,575
61,596,643
Horizontal Output C++
the codes below represent output of coordinates,for example it'll show faces_x=201 etc. However,they are all displayed vertically. How to print them on the console horizontally? printf("faces_x=%d\n", faces[i].x); printf("faces_y=%d\n", faces[i].y);
If you simply remove the newlines, i.e. \n, the 2 lines will be printed horizontally: printf("faces_x=%d", faces[i].x); printf("faces_y=%d", faces[i].y); Note that your question doesn't actually need the second \n to be removed, unless you want the following output to start on a new line.
61,596,773
61,596,810
c++ program doesn't continue on after loop
#include <iostream> using namespace std; class movie { private: string rating; public: string title; string director; movie(string aTitle, string aDirector, string aRatings) { title = aTitle; director = aDirector; setrating(aRatings); }; void setrating(string aRating) { // this loop checks to see...
Your logical condition is not correct: while (aRating != "G" || aRating != "PG" || aRating != "PG-13" || aRating != "18" || aRating != "NR"); Write out some examples, and you'll see that this condition is always true. (any value of aRating will always be either not G or not PG, for example). You need to replace all th...
61,597,018
61,597,053
Quit while (true) loop in C++
This is my simple while (true) loop: while (true) { int i = 0; ++i; cout << i << endl; if (i == 5) { break; } } } So break; isn't quitting the loop and the output is an infinite 1.
See this for Why use a for loop instead of a while loop?. Now, coming to your question: You are initializing i variable in each iteration of your while loop. Move the definition of i outside the while loop so that it's value can be updated. Try this: #include <iostream> int main(void) { int i = 0; while (true)...
61,597,388
61,597,918
Why would a std::move of std::shared_ptr casue destruction
I got some code look like this struct A { int i; A(int i) : i(i) {} ~A() { cout << "destroy " << i << endl; } }; using p = shared_ptr<A>; p f(int i) { return make_shared<A>(i); } int main() { auto i = f(1); cout << "a" << endl; p && j = f(2); cout << "a" << endl; p &&...
p && j = f(2); Here, f returns a prvalue of type std::shared_ptr<A>. When you bind a reference to a prvalue it extends the lifetime of the prvalue to be that of the reference. That means that the object returned by f will have the same lifetime as j. p && k = move(f(3)); Here, once again f returns a prvalue. std::...
61,597,774
61,597,988
dp[!t][val] for skipping the parts from array
consider the following snippet in cpp. This is taken from dynamic programming tutorial . It is mainly for space optimized knapsack problem. for(int i=1;i<=a;i++) { int t = a%2; for(int j=0;j<1100000;j++) dp[t][j] = inf; for(int j=0;j<1100000;j++){ dp[t][j] = min(dp[t][j],dp[!t][j-v[i-1]]+w[i-1]);//...
Just replace !t with t ^ 1 or 1 - t (whatever you find more readable; the effect is the same). That's all you need to do here. Explanation Java supports all the integer manipulation on display in this snippet: int t = a % 2; <-- this is valid java and means the same thing in java as it does in C: divide a by 2, and put...
61,597,922
61,918,050
VSCode: clang: error: linker command failed with exit code 1 (use -v to see invocation)
I've made a code for one of my classes I'm in where it should split up a string and show how many unique characters there are in a second string. However, every time I try to build the code I get "clang: error: linker command failed with exit code 1 (use -v to see invocation)". I've looked at other questions for this e...
There was a simple typo, that's why I was getting the error. Sorry guys, thanks for answering though! I defined findnumchar as findnumchnar. Always check for stupid stuff
61,598,465
61,598,721
unable to find where memory leaked
Hi I am currently working on my first object orientated c++ project, and when I use valgrind to check memory leakage it outputs: 32 (24 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2 ==1761165== at 0x4839E86: operator new(unsigned long) (vg_replace_malloc.c:344) ==1761165== by 0x4...
Every new should have a corresponding delete. In your Game constructor, you use new to create game_entity - but the destructor doesn't delete it (only its 'members'). You need a delete game_entity; after the for loop in the destructor.
61,598,486
61,599,028
How to Foward Declare Classes Across Files C++
I have been trying to figure out how to forward declare classes across multiple files in C++. I was able to successfully do it with two classes, but doing this across many classes puzzled me. I tried forward declaring all the classes in a header file and including that in all the classes, but I got the error of incompl...
You have to avoid circular dependencies. One common way to avoid them is by pre-declaring the type, and not having any instances or function calls of that type in the header. You do this by changing instances, such as B b, into references or pointers: B* b. You also have to move any code that uses b into the CPP file...
61,598,668
61,599,003
Using class without definition class variable
I'd like to do something like: class StrToHex { public: ??? StrToHex(std::string a) { return class_method1(a) + class_method2(a); } private: std::string method1(std::string a); std::string method2(std::string a); } int main() { std::string var = StrToHex("FF1042"); } I know that I may use S...
In C++ a constructor cannot return a value. So you cannot specify a return type for a constructor. But there are other alternative ways to achieve the same. I have used a std::string cast operator here. class StrToHex { public: StrToHex(std::string a) { _data = method1(a) + method2(a); }; operator std::string() {...
61,598,872
61,598,936
Concepts - how to constrain integral template value
There is a template definition like: template<size_t N> void foo( void ) { /* ... */ } How to define a concept so that N must be non-zero positive value (N >= 1)? Something like: template<size_t N> concept NonZeroSize = /* to be implemented, N>=1 */ template<NonZeroSize N> void foo( void ) { /* Do whatever only i...
Like this: template <size_t N> requires NonZeroSize<N> void foo(); Or just: template <size_t N> requires (N > 0) void foo(); The terser form is reserved for type concepts. The concept definition itself is just an arbitrary boolean expression: template <size_t N> concept NonZeroSize = (N > 0); A requires-expression...
61,599,025
61,621,587
Cross compile modern C++ from Linux to Windows
I have some modern C++ sources (C++17, say) and I have no problem compiling complex source base on Linux for Linux 32/64, and on Windows for Windows 32/64 using mingw-w64 (from msys2). Now I want to cross compile for Windows on Linux, to avoid using a virtual machine just to compile. So I tried installing mingw-w64 fro...
My Ubuntu 18.04 has a POSIX-threaded mingw-w64 toolchain as well. Try update-alternatives --list x86_64-w64-mingw32-g++.
61,599,681
61,599,810
Why can't I set *this == class object
I was reviewing at the overload operator =. Why i can set 'this == &st' but not '*this == st' ? StringBad & StringBad::operator=(const StringBad & st) { if (this == &st) // if the object assigned to itself, return to itself. return *this; // why compiler give error when I set *this ==st ...
Two different objects can be equal each other but this does not mean that they are the same. Consider for example #include <iostream> #include <iomanip> int main() { int x = 0; int y = 0; std::cout << "x == y is " << std::boolalpha << ( x == y ) << '\n'; std::cout << "&x == &y is " << std::boolalpha ...
61,599,976
61,600,014
error trying to access form elements in Qt
I trying to rewrite a project from python to c++. I imported the form into my project, but when accessing it, a runtime error occurs (see below) I can access the methods of the form, but when executed, it gives an error below is all the code involved plaindict.h #include <QDialog> #include "ui_plaindict.h" namespace ...
ui->inputLine->setText("regetrg"); ui->setupUi(this); Here you access inputLine before it is initialized by that setupUi call. To fix, switch order of these lines.
61,600,050
61,600,163
Nested header inclusion prolongs compilation
In my project I am using a third-party lib which is included dynamically - i. e. via an import *.lib-file and an *.h-file. The *.h-file of the lib has an include guard. I #included this file in one of my project headers, which starts from #pragma once. The latter in its turn is also included in several *.cpp-files of m...
is also included in several *.cpp-files of my project. if you compile for instance 2 sources including directly or indirectly your header that one will be included 2 times at total. The protection is only for one source file, each time the compiler moves to an other source file to compile none of the header are known...
61,600,277
62,987,999
Unable to build husky from source in windows using ms-iot/husky
I am trying to build husky from source in windows with the repo from https://github.com/ms-iot/husky/tree/melodic-devel,but when i run catkin_make_isolated ,windows is unable to build it because husky use "unistd.h" and i couldnt get that header in windows,is there any workaound for this? Error: ==> Processing catkin p...
I downloaded the latest version of the repo, found out that there was a mismatched #if/#endif pair in file '\husky-melodic\husky_base\src\horizon_legacy\Logger.cpp'. I built the repo successfully after modified the Logger.cpp file. #include <iostream> #include <fstream> #include <signal.h> #if !defined(_WIN32) # incl...
61,600,378
61,601,312
RAII with std::function
Is std::function smart in nature like std::shared_ptr and std::unique_ptr? I guess no? I have a std::function which is a class member like below. class MyClass { typedef std::function<void(void)> Func; Func m_func; public: MyClass() { m_func = []() { std::cout << "Func called" << std::e...
std::function has a destructor that deletes any resources it managed, if there are any. This line: m_func = nullptr; // Is this required? is never required. A class members destructors are called automatically and if not, assigning nullptr is never "the right" thing. If m_func was a pointer you would loose the poi...
61,600,849
61,600,926
How to store an int from a string
Hello I am using c++ for this assignment. If I have a string such as "P10" and I want to store the number 10 into an integer disregarding the P, how would I do that?
Assuming you only want to remove the first character from your string then #include <string> std::string str = "P10"; int i = std::stoi(str.substr(1));
61,600,854
61,600,886
How to convert auto (for vector<string>) from c++11 to c++98?
I have this code in C++11: vector<int> stariFinale; bool LexAnalyzer::eStareFinala(int q) { for (auto x : stariFinale) if (q == x) return true; return false; } And I tried to convert it to C++98 like: bool Analizator_L::eStareFinala(int q) { for (vector<int>::iterator x = stariFinale....
Now you've got an iterator, not the value, so you must dereference it. And please use prefix ++, not postfix ++. Postfix ++ needs to create a temporary, prefix ++ not, compare the enforcement section of http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rp-waste. for (vector<int>::iterator x = stariFinale.begi...
61,601,288
61,601,914
what is a 'C-like' module in C++? and how to implement it?
I am new to C++, and I have an assignment need to be done in c like module. According to my professor, 'C-like' module has no class is being written, only a non-member (C-like) function. my assignment is to write a C-style module sort.h & sort.cpp with a function sort() in the .h file. sort() accepts an array of intege...
In the C++ language, you can have functions that are outside of a class, called free standing functions. Sort.hpp: #ifndef SORT_HPP #define SORT_HPP #include <vector> void my_sort(std::vector& v); #endif Sort.cpp: #include "sort.hpp" void my_sort(std::vector& v) { // Insert code to sort the vector here. } It ...
61,601,356
61,601,435
c++ struct of vector of struct
Im trying to get a better understanding of structs and I could use some help. Im trying to create a struct which contains a vector of structs, but Im having trouble linking them together. So far I got: struct Vehicle{ string LicensePlate; string VehicleType; vector<string> DamageType; int EstFixDays; }v...
You haven't created a struct containing a vector of structs. All you've done is created a struct which contains a struct. You do have a vector of structs but that is in main, not in any struct. You also have miscellaneous other issues, global variables you aren't using and unnecessary struct uses. Here's how you should...
61,601,379
61,601,695
undefined reference to symbol '_ZN5boost6system15system_categoryEv'
All i found in Stackoverflow, nothing help in my case, maybe there is something that my eyes can't see? undefined reference to symbol occurs, when i include these headers #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> $ echo $LD_LIBRARY_PATH /usr/lib/x86_64-linux-gnu/ PROGNAME := "prog...
Oh my. You have many problems here. As Jesper said, linker issues are normally not related to #include files. First, you should never add libraries to your compile lines: that is, lines that create object files (lines that use the -c compiler option). So this rule: obj/%.o: src/%.cpp @mkdir -p obj @g...
61,601,872
61,602,280
Why do string literals (char*) in C++ have to be constants?
I've recently been learning C++ and have realised that string literals in C++ have to be constants, whereas in C, they do not. Here is an example. The following code would be valid in C, but not in C++: char* str = "Hello, World!"; In order to do the same thing in C++, the following statement has to be used: const cha...
Expanding on Christian Gibbons' answer a bit... In C, string literals, like "Hello, World!", are stored in arrays of char such that they are visible over the lifetime of the program. String literals are supposed to be immutable, and some implementations will store them in a read-only memory segment (such that attempti...
61,602,249
61,604,864
How to detect how many stairs are there in an image using OpenCV C++
I'm trying to detect how many stairs I have in an image using OpenCV with C++, I've tried to do: 1-Binarization. 2-Canny Filter. 3-Hough Filter. 4-Connected Components. I didn't get good results, do you have any idea of which methodology should I follow? Thank you in advance. Here is an image example.
My algorithm approach is simply like that; finding the lines of each stair will give us the stair number. To achieve that Houghline Transform can be used. You should read the documents which are linked below to be able to understand the parameter logic of the HoughLinesP function. First problem will come accross: Hough...
61,602,348
61,602,473
Separating Arguments for Multiple programs from Command line in main
I am integrating 2 programs and turning them into one (I know, not ideal). I expect command line args to look something like bin/programName -optionsProgram1 --optionsProgram2 I have parsed the options out so I now have the separate sets of arguments, shown below. bin/programName -optionsProgram1 bin/programName --op...
Try std::vector<const char*> populated with pointers from std::string::c_str(), eg: std::vector<std::string> myVec; std::vector<const char*> myCharArray; // populate myVec as needed ... ... // add +1 if you need the array to be null-terminated... myCharArray.reserve(myVec.size()/*+1*/); for (auto &s : myVec) { m...
61,602,464
61,602,702
I'm not sure I understand the wording on part 6 of this question
Write a class declaration for a class called Library that has the following private members: mBooks, a pointer to an array of Book structures. mCapacity, the maximum number of books that can be stored in the library. mNumBooks, the actual number of books in the library. allocate, a void member function that allocates...
Let's take the item 6 6 copy, a void member function that takes another Library object by constant reference, and copies the contents of its array into the array of the object it is called on. and look at it piece by piece. copy, a void member function The function name is "copy" and returns void: void copy() {...
61,602,469
61,602,558
How can I copy multiple char* strings into one using strcpy_s()?
Using the strcpy_s() function I want to collate the first three strings into the final one to print my full name. This is what I have and it doesn't work as I'm using char* strings and not std::strings. #include <iostream> using namespace std; int main() { char str_first[] = "Nerf_"; char str_middle[] = " Herd...
You need to use both strcat and strcpy See code comments for more info. // disable SDL warnings in Visual studio #define _CRT_SECURE_NO_WARNINGS #include <cstring> #include <iostream> using namespace std; int main() { // TODO: insert checking code, // to make sure destination can hold all characters + one ter...
61,602,789
61,602,824
std::list and std::vector - Best of both worlds?
By vector vs. list in STL: std::vector: Insertions at the end are constant, amortized time, but insertions elsewhere are a costly O(n). std::list: You cannot randomly access elements, so getting at a particular element in the list can be expensive. I need a container such that you can both access the element at any i...
There's a theoretical result that says that any data structure representing an ordered list cannot have all of insert, lookup by index, remove, and update take time better than O(log n / log log n), so no such data structure exists. There are data structures that get pretty close to this, though. For example, an order ...
61,603,039
61,603,715
How does a BST height algorithm count?
int BianaryTree<T>::height(Node<T>* A){ root = A; if(root==nullptr){ return 0; } else { int lHeight=height(root->left); //how is int counting here? int rHeight=height(root->right); return max(lHeight, rHeight)+1; } } So from what I understand this is a standard Biana...
Each recursive branch will eventually result in a return value of zero, but it then returns the maximum of the left and right heights plus 1. That plus 1 is critical, without that the return value of the entire recursion would indeed be zero but with it you get the height you expect. Imagine a tree like the following: ...
61,603,186
61,603,385
I dont understand why this solution worked. (Integer Overflow)
Sorry for the bad title, but I had no idea of how to name it. I has solving some problems to practice and I came across this one. The challenge was to write a class for a box. So it had the longitude, height, and breadth. One of the methods was supposed to return the volume of the box. This is like a resume of it: #inc...
Really thanks for the help. TIL that if the variables are ints it does not matter that the result of an operation is assigned to a long long int, the operation will be done with int maths. So the ad hoc solution that i had worked because b*h was still an integer with no problems and when i then multiplied it by l it wa...
61,603,219
61,603,349
How to print a vector of pairs that have as first and second 2 classes in c++?
I have something like this where Client and Order are classes : std::vector<std::pair<Client,Order>> pair; pair.push_back(std::make_pair(Client(2,"Anca"),Order(3,1))); pair.push_back(std::make_pair(Client(16,"Maria"),Order(1,3))); pair.push_back(std::make_pair(Client(29,"Alex"),Order(10,5))); class Clien...
Your first attempt does not work because it is the actual pair but std::pair does not have an operator[]. Your second attempt is the correct way to go, but it does not work because you have not defined operator<< for your classes. So, simply define operator<<, eg: class Client { private: int dateWhenOrderWasPlaced...
61,603,288
61,603,403
unique_ptr<T,Deleter> constructor requires that Deleter is nothrow
unique_ptr (constructor) @ cppreference unique_ptr( pointer p, /* see below */ d1 ) noexcept; (3) unique_ptr( pointer p, /* see below */ d2 ) noexcept; (4) Here are 2 constructors and the description for the case Deleter is non-reference a) If D is non-reference type A, then the signatures are: unique_ptr(pointer p, ...
I checked both gcc and llvm code but I don't see nothrow requirement is enforced. It's not enforced - directly. Here's the actual words from the standard: For the first constructor, if D is not a reference type, D shall meet the Cpp17CopyConstructible requirements and such construction shall not exit via an exceptio...
61,603,455
61,603,624
C# Array access vs C++ PInvoke pointer access
I've got an idea of optimising a large jagged array. Let's say i got in c# array struct BlockData { internal short type; internal short health; internal short x; internal short y; internal short z; internal byte connection; } BlockData[][][] blocks = null; byte[] GetBlockTypes() { if (blocks...
This sounds like a question where you should first read the speed rant, starting at part 2: https://ericlippert.com/2012/12/17/performance-rant/ This is such a miniscule difference - if it matters you are probably in a realtime scenario. And .NET is the wrong choice for realtime scenarios to begin with. If you are in a...
61,603,565
61,603,617
c++ struct pointer to adress struct error CDCDCD
struct XYZ { XYZ *adress; }; XYZ *Ex; int main() { Ex = new XYZ[3]; Ex->adress = (++Ex); cout << Ex->adress << endl; Ex->adress = (++Ex); cout << Ex->adress << endl; Ex->adress = (--Ex)->adress; cout << Ex->adress << endl; Output: 0105E424 0105E428 0105E424 struct...
Pointers behave just like regular objects when you copy them, or pass them to a function. Changes to the copy are not reflected in the original. To make the changes in a function visible, you need to take it by reference: void copy_adress(XYZ *&Ex) { Ex->adress = (++Ex); } Now, the 2 versions are equivalent.
61,603,820
61,604,115
Zero initialization of nested struct - compiler bug?
Consider this example: #include <vector> #include <stdexcept> struct A { float a; float b; float c; float d; }; struct B { A a; std::vector<int> b; }; int main() { B b{}; if (b.a.a || b.a.b || b.a.c || b.a.d) throw std::runtime_error("Compiler bug?"); } If I understand correct...
Firstly: the objects b.a.a, b.a.b, b.a.c, b.a.d are guaranteed to be zero-initialized. Which for float is initialized as if by = 0; (not necessarily a representation of all bits zero). B b{}; only translates to zero-initialization in some cases (the cppreference page is a bit misleading). In C++14: Since B is an aggreg...
61,604,128
61,619,921
Texturing an opengl cube
I have an opengl cube and I want to texture all 6 faces. Do I need multiple textures? Here's a screenshot of the current cube: basically I don't know how to wrap the texture around the entire cube... here's my cube.h header file where the IBO's and VBO's are defined #pragma once #include <GL\glew.h> class cube { publ...
the problem is that each cube vertex is shared among 3 faces in which its texture coordinate might not be the same. So you either duplicate such vertexes (each with different texture coordinate) or use 2 separate indices (one for vertex and one for texture). The duplication might look like this (using GL_QUADS primitiv...
61,604,389
61,607,452
Are these allowed optimizations in C++?
Let std::atomic<std::int64_t> num{0}; be defined somewhere accessible/visible in the code. Is the C++ compiler allowed to replace each of the following two codes with an empty code (something that does nothing)? Similarly, are these optimizations allowed to happen at runtime? I am just trying to get a better understand...
I think in theory yes and even yield does not help. But in practice no not today but possible in the future. See: N4455 No Sane Compiler Would Optimize Atomics P0062R1: When should compilers optimize atomics? "Runtime optimization" may happen if modifications coalesce. I don't know if this situation may happen in pr...
61,604,425
61,604,473
static class member for header files
I am working on a class hierarchy where I have a base class containing a value which needs to be shared with all other derived classes in my code. I currently have this working by using a static double within a base class with pure virtual functions to set the value: class base { public: static double shared_value...
You will need to define shared_value in a source file like so: double base::shared_value = 0; Now any child class can access that value including editing it.
61,604,641
61,638,179
How can I tab away from a Fl_Button in FLTK?
I have a custom class, CustomButton that extends Fl_Button. On my screen there are a bunch of Fl_Input and CustomButton widgets that I want to be able to navigate between using a tab keypress. Tabbing between input fields works fine, but once a CustomButton gets focus, I can't seem to tab away from it. Here's my handle...
My problem was my CustomButton::handle() returning 1 after a FL_KEYBOARD event without actually using the tab key press. Moving is_event_handled = 1 into the if statement lets me consume the FL_Enter keypress only and lets other widgets (i.e. the Fl_Group that controls navigation) take any other keypresses. Alternative...
61,604,694
61,604,740
Check if a type is a partial order
Can a type be checked for partial ordering property in C++20? If so, how can such a check be made with the use of concepts? Is the the following code enough for this purpose? #include <compare> #include <concepts> template<class T> concept PartialOrder = requires (const T& lhs, const T& rhs) { // Is there any caveat...
There already is such a concept in the standard library: three_way_comparable. T satisfies three_way_comparable if all the binary comparison operators and <=> are all valid expressions and the invocation of <=> gives you at least std::partial_ordering. It's a little bit more involved than the one you're proposing - par...
61,604,705
61,606,016
C++ Byte, sprintf, hex. Convert byte to binary
I am working on this project which has this format/command. My problem is with b0,b1..b5. I am not very good at c++. I can do this in c#. Configure Image Data (CID) Command Esc*v6W b0 b1 b2 b3 b4 b5 Where: • 6 = the number of bytes following the command • b0 = byte 0 = the color space • b1 = byte 1 = the Pixel Encodin...
Judging by the functions used there, you probably need to build and output that sequence to a stream (but you should really try to explain better next time), so try this: std::vector<unsigned char> v = { '*', 'v', '6', 'W', 0x02, // b0: ColourSpace 0x00,...
61,604,708
61,604,921
Trying to use a bubble sort to sort a string array alphabetically but sort is returning the reverse of the array
I'm currently trying to read from a .txt file into a string array and then use a bubble sort to sort them alphabetically though when I actually run my code it gives the reverse of my array as seen below: bool swapped = true; int j = 0; string tmp; while (swapped) { swapped = false; j++; for (int i = 0;...
I fixed a few problems and this should work: bool swapped = true; string tmp; int j = 0; while (swapped) { swapped = false; ++j; for (int i = 0; i < n - j; i++) { // 1. Your original code has a comma in the following line which terminates the if statement // 2. compare function returns ...
61,604,983
61,605,242
Switch statement and conditional operators c++
My Q is why to use switch statement and the conditional operator when we have the (if else && else if) Example 1 : unsigned short int any_number ; any_number = ((15>0)? 10 : 5);//using here the conditional operator if(15>0)//using if & else any_number=10; else any_number=5; Example 2 : unsigned short int my_score; st...
Your main concern is code readability and how error-prone it is. For example, when not used with switch, case and breaks (!), it's probably safer to go for if-else. In C++ is it better to use switch and case statements or to use if statements? Personally I find the answers there as great as they are simple.
61,605,111
61,607,943
nodes are being added at some unknown locations in my binary search tree
To learn implementation of binary search tree, I created a class bst and am facing problem in its add_node_private function. bst.cpp - #include <iostream> #include <cstdlib> using namespace std; #include "bst.h" // bst constructor bst::bst() { root = nullptr; } // methods of binary search tree bst::node* bst::create_...
I made a stupid mistake of using ptr in the function add_leaf_private by value. I should have passed it by reference as I intend to change it in the function. Replacing ptr with &ptr solved the problem.
61,605,181
61,632,837
Declaration of cuda variables in header which is included in cpp project
I have a class containing several variables only available when compiling with nvcc, such as thrust::device_vector<>. The class declaration itself is in a header file, the implementation of it is in a .cu-file. This class is to be included in the main project which is compiled using g++, which means that the compilatio...
that my class contains variables such as thrust::device_vector<>, but still can be included in the full project? You have to compile thrust containing code with nvcc. There is no alternative. If you include headers which include thrust into vanilla C++17 code and compile with a C++ compiler, you will get errors. Can...
61,605,247
61,605,278
Confused about ranged for loops
To me, this doesn't produce the expected results: int main() { int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; for (auto v : i) std::cout << v << std::endl; for (auto v : i) v = v+1; for (auto v : i) std::cout << v << std::endl; return 0; } The second for loop doesn...
In your second loop, auto v : i, v is a copy of each i. To change the i values, you need a reference: int main() { int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; for (auto v : i) std::cout << v << std::endl; for (auto& v : i) // Add "&" here. Now each v is a reference of i. v = v + 1; for (auto...
61,605,368
61,606,930
How to describe a member function with "void*" as input in UML?
I'm new to UML, how to describe the following class with a member function that takes void*? // used on linux #include <unistd.h> class LinuxReadWrapper { public: LinuxReadWrapper(){/** Ctor */} ~LinuxReadWrapper(){/** Dtor */} ssize_t WrapperRead(void* buf) { return read(fd, buf, cnt); }...
One solution is maybe to create a void or void* type in your model. Then type your input parameter with it cf below. This also dependsif you need this for documentation purpose only or also for code generation/reverse. In the last case, this will depends of the tool used...
61,605,453
61,605,590
How do I implement the number of rounds in this C++ code?
int round; int Starting_index; int hop_count; for( round = 0; round < gNumRounds; round++) { Starting_index[round] = gPasswordHash[0+round*4] * 256 + gPasswordHash[1+round*4]; hop_count [round] = gPasswordHash[2+round*4] * 256 + gPasswordHash[3+round*4]; if(hop_count == 0) hop_count = 0xFFFF; } gPassword...
You need to declare those variables as arrays, not single int. int Starting_index[MAXROUNDS]; int hop_count[MAXROUNDS];
61,605,501
61,605,642
Multiple, exclusive, conditions in an if statement
One of the first two statements in the if statement is false but I would like both of the first two statements to be false for the code to NOT run. please help. void change(Shore* left, Shore* right, int ex, int can) { if (((ex!=left->lastMove[0]) && (can!=left->lastMove[1])) && (left->hasBoat)) { I also trie...
void change(Shore* left, Shore* right, int ex, int can) { if (((ex!=left->lastMove[0]) || (can!=left->lastMove[1])) && (left->hasBoat)) {
61,605,558
61,605,722
Separate integers in a file by tabs into an array
Honestly, its a file of 200k integers and have no idea how to error check if the way I am doing it is correct so I'd like some help! There are 10 integers per line and 20k lines total. Here's my code: void readFile(int searchValues[VALUES], string fileName, string fileExtension, string filePath){ string fileLine; ...
Here is a working example for 3 integers ... do the same for 10. #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fl=fopen(argv[1],"rt"); int a,b,c,line=0; while (3 == fscanf(fl,"%d\t%d\t%d",&a,&b,&c)) { printf( "line %d contains ints: %d %d %d\n", ...
61,605,600
61,606,059
Why can't a typedef type be used to declare its parent class' ctors?
template<typename> struct A { int n; A(bool) {} }; template<typename> struct B { struct C : A<B> { using Base = A<B>; using A<B>::A; // ok using Base::n; // ok // error: dependent using declaration resolved to type without 'typename' using Base::A; }; ...
Similar behaviour was earlier reported as a possible Clang bug: [Bug 23107] Constructor inheritance on template not working correctly. Richard Smith's comment on this report: The C++ committee have discussed this case and did not intend for that syntax to be valid. Use using myBase::myBase; instead to declare an inh...
61,606,165
61,606,789
sendto() while blocked on select()
Can I call sendto() from other thread on socket, when main thread is blocked on select() for same socket for checking readability? Is this behavior defined across different systems like linux or windows? Or do I have to always do socket related stuff (select() / sendto() / recvfrom()) from single same thread only?
I use such architecture in my application. I've checked in multiple sources (for Linux) and haven't found anything against it. The only formal foundation proofing this concept is POSIX standard - it says that sendto() as well as select() are thread safe functions: POSIX.1-2001 and POSIX.1-2008 require that all funct...