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
68,277,399
68,289,753
Correct way to define integral constant in .cpp file
I have a class source file Foo.cpp and I need to define IntVal constant only for local use by class methods. // Option 1 const int IntVal = 5; // Option 2 static const int IntVal = 5; // Option 3 namespace { const int IntVal = 5; } int Foo::GetValue() { return this->value + IntVal; } Which one is pref...
For hardcoded constants like that, I'd pretty much always go with: static constexpr int kIntValue = 5; If I had to bet, I'd say all of those compile to almost exactly the same code though (unless you're trying to use the number in a constexpr context) so it probably comes down to personal preference/style.
68,277,477
68,278,201
Why can I compile and use std::cout << std::chrono::year_month_day data type on Windows, but in VS Code on macOS I can't compile?
My problem is pretty straight forward I think but please forgive me if I suck at explaining still. Basically I am learning C++ and playing around with <chrono> from C++20 to store date values in a simple Person class. The problem is this source code on my M1 MacBook Pro using VS Code with standard set to C++20, it thro...
libc++ (the clang std::lib) isn't yet shipping this part of C++20. However if you would like to use a transition tool, there exists an open-source preview of this part of C++20. For the parts you're using in this example, the preview is in date.h, which is header only. Just #include "date/date.h", and point the compi...
68,277,717
68,277,829
function template overload with rvaule reference as argument does not work?
The function template with && as argument seems cannot be overloaded, when input is not rvalue. See here as example: template<typename A, typename B> void test_tp_func(A&& a, B&& b) { std::cout<<"tp1(" << a << "," << b << ")\n"; } template<typename A> void test_tp_func(A&& a, int&& b) { std::cout<<"tp2(" << a <...
How can you choose the rvalue overload? It would help if the argument was an rvalue which i is not. It's not a prvalue (it's a named variable) and it isn't an xvalue either. If you just want to intercept the case where B = int, why not just make the argument type int? Using int&& will only match rvalues by definition. ...
68,277,814
68,277,851
C++: returning shared pointer destroys the object
I'm trying to return a new shared_ptr from a method: std::shared_ptr<VertexBuffer> VertexBuffer::Create(float* vertices, uint32_t size) { return std::make_shared<OpenGLVertexBuffer>(std::move(OpenGLVertexBuffer(vertices, size))); } I have a destructor and VertexBuffer gets destroyed after exiting this method. Why ...
The destructor is being called on this temporary object: return std::make_shared<OpenGLVertexBuffer>(std::move(OpenGLVertexBuffer(vertices, size))); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You're slightly misusing std::make_shared and invoking the move/copy constructor ...
68,278,071
68,281,253
BLE api converts negative temperature to positive
I want to extract the temperature from a BLE beacon using the ESP32 chip. I have used the following code to do this: class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { void onResult(BLEAdvertisedDevice advertisedDevice) { std::string strServiceData = advertisedDevice.getServiceData(); uint8_t...
I looked at the library you linked to and it had the following for temperature: void BLEEddystoneTLM::setTemp(float temp) { m_eddystoneData.temp = (uint16_t)temp; } // setTemp and BLEEddystoneTLM::BLEEddystoneTLM() { beaconUUID = 0xFEAA; m_eddystoneData.frameType = EDDYSTONE_TLM_FRAME_TYPE; m_eddystone...
68,278,225
68,278,332
Why do we use left and right node pointers within the node structure?
This is the class binary search tree Why do we create nodes left and right pointer within the node structure which will again have 3 attributes? Why not just use an int? class bst { struct node { int key; node *left; node *right; }; node *root; };
Following your comment, I believe I understand your confusion. The reason the node structure contains pointers to other node structures and not to int is to allow the tree to have multiple levels. Each node has a value, and can have one or two children nodes, but each of those nodes can have its own children. BST - a b...
68,278,321
68,278,335
String Class C++ Why the reversed string is not build correctly?
I have to check if a string is palindrome. I'm new to C++ and I really can't understand why my code is not working.. bool isPalindrome(string str) { string str2; int length = str.length(); for(int i = 0; i < length; ++i) str2[i] = str[length - 1 - i]; if(str ==...
string str2; This creates a string object that is empty. str2[i] = ...; Since str2 is empty, str2[i] is always out-of-bounds. This is undefined behavior. It might do random things, or it might crash, or it might appear to work. You probably want to add str.resize(length); so that you can write to those indexes.
68,278,481
68,278,634
How to create blob stream using unique_ptr?
When using the following code I am successfully saving the image into "Image" blob field: if (OpenDialog1->Execute()) { ADOTable1->Insert(); TStream* BlobStream = ADOTable1->CreateBlobStream(ADOTable1->FieldByName("Image"), bmWrite); std::unique_ptr<TFileStream> FileStream(new TFileStream(OpenDialog1->FileN...
In the original code, you were delete'ing the blob TStream object before you called Post(). Per the TADOBlobStream documentation: http://docwiki.embarcadero.com/Libraries/en/Data.Win.ADODB.TADOBlobStream.Destroy Destroy [ie, the destructor] performs the following tasks: Sets the field's data. Changes the field objec...
68,278,693
68,278,716
Use boolean template argument to change return type
I am in the process of writing a function where the code is the same regardless of the return type. I want to return an integer whenever possible, but sometimes the code requires a floating point. I want something like this: template <bool floating_p> (floating_p ? float : int) func() { // ... return some_num; }...
You can use std::conditional_t like this template <bool floating_p> std::conditional_t<floating_p, float, int> func() { return 42; } Here's a demo.
68,278,783
68,278,933
Checking function with given signature then compile differently
In a templated class, can we check a member function's signature and define different compilation behaviors for different subclasses? To be more specific, consider the following simple example: template <typename T> class Foo { // ingore all other functions virtual std::shared_ptr<T> do_something(int a) { ...
As far as I can tell, we need class template specialization here. Not even C++20 requires-clauses can be applied to virtual functions, so the only thing we can do is have the whole class change. template<typename T> // using C++20 right now to avoid SFINAE madness struct Foo { virtual ~Foo() = default; virtual ...
68,279,039
68,279,309
Understanding compiler optimisations for compile time logic
If we have a program which specifies certain fixed conditions at compile time, does the compiler determine and fix which 'branch' of the decision tree the program will always run in? For example, if the following program is compiled with the -Ofast flag, does the program spend any time at all actually checking the if (...
In the code you show, every good compiler will recognize the if condition is true and the Run_B(); code is unreachable if optimization is enabled. It will then remove the evaluation of aFixedCondition and the Run_B(); code from the program, as well as the bool aFixedCondition = true;. The conditions you show are of cou...
68,279,165
68,279,262
Circular template argument list between circular dependency class members producer/consumer
I have a circular dependency between two templated classes. Aggregator contains a class member of template parameter type DATA_LISTENER. However, DATA_LISTENER needs to contain a reference to Aggregator to return data. This means I cannot define the template for each because they both require the other. What's the best...
The third template parameter to Aggregator should be a template parameter, and not a type parameter. Making it a template parameter results in everything else falling into place. template<class NA, class ABC, template<typename> class DATA_LISTENER> struct Aggregator { Aggregator() : _sd(*this){} void receiveData...
68,279,358
68,279,393
Accessing an array within a struct causes warnings with clang
struct test{ char c_arr[1]; }; test array[1] = {{1}}; test get(int index){ return array[index]; } int main(){ char* a = get(0).c_arr; return 0; } Compiling this with g++ has no warnings but with clang++ prints the following: warning: temporary whose address is used as value of local variable 'a' will be de...
get returns by-value, then get(0) does return a temporary which gets destroyed after the full expression, left a being a dangling pointer. Note that the returned temporary test is copied from array[index], including the array data member c_arr. a is supposed to point to the 1st element of the data member array c_arr of...
68,280,900
68,281,022
How do I know the actual type and size of the return type of a non-static method in C++?
In C++, we can use sizeof and decltype on non-static data member of a function, but either of them doesn't work on non-static method's return type, e.g. decltype(std::vector<int>::size()), sizeof(std::vector<int>::size()), any reason why this is restricted? or there are some way works i didn't discovered?
The decltype specifier needs to be given a legal expression - something you could use in actual code. So you can create an instance and call the member on that instance like this: decltype(std::vector<int>().size()) It is the same for the sizeof operator. It needs to receive a legal expression.
68,280,947
68,281,217
Timer ID in timer call back is different from defined timer ID
I implemented two timers with SetTimer function : UINT TimerId1 = SetTimer(NULL, IDT_TIMER1, 2000, TimerProc); UINT TimerId2 = SetTimer(NULL, IDT_TIMER2, 2000, TimerProc); And pump windows messages with GetMessage loop to get timer messages too : #define IDT_TIMER1 1 #define IDT_TIMER2 2 int main(int argc, char *ar...
Thread timers (when hWnd is null), as opposed to window timers, do not use the ID you give them - instead they assign their own, which is returned to you by the SetTimer function. This is described in the docs for SetTimer: If the hWnd parameter is NULL, and the nIDEvent does not match an existing timer then it is ign...
68,281,610
68,294,930
How can I remove command line option for single file in the visual studio c++ project?
I tried to use _penter() function. This function needs "/Gh" options, so I added "/Gh" options at the project file. After that, "/Gh" option applied to cpp file that contains _penter() function, so this function(_penter) called itself continuously. It cause stack overflow. If I add "/Gh" options at one cpp file, it wor...
You could remove directly: right click .cpp ->properties -> c/c++ -> All Option -> Additional Options.
68,281,984
68,282,166
what is this 0=1 in lamda capture in the following code and 0++ % xy in the following code?
int main() { constexpr int xy = 4; using Cell = std::array<unsigned char, 8>; std::array<Cell, xy * xy> board; board.fill({ {0xE2, 0x96, 0x84, 0xE2, 0x96, 0x80, 0, 0} }); // "▄▀"; std::for_each(board.cbegin(), board.cend(), [xy, O=1](const auto& c) mutable { std::cout << c.data()...
That's a capital O. In the font used on cppreference for code zero has a dot in the middle and O doesn't. I changed the name O to count, hope it saves confusion for someone in the future.
68,281,993
68,282,123
Using std::setw() without <iomanip> header
How is it possible for this code to compile even though I didn't include <iomanip> ? #include <iostream> #include <fstream> int main() { std::cout << std::setw(5) << "test" << std::endl; return 0; } Compiles with: clang++ test.cpp But without <fstream> it throws the error: test.cpp:5:20: error: no member nam...
The headers include themselves internally, depending on the standard library implementation. The standard doesn't guarantee that a symbol is undefined unless you include a certain file - instead it guarantees that a symbol will be defined if you do include it. In this case, the fstream header includes code internally t...
68,282,296
68,282,346
Write overloads for const reference and rvalue reference
Recently I find myself often in the situation of having a single function that takes some object as a parameter. The function will have to copy that object. However the parameter for that function may also quite frequently be a temporary and thus I want to also provide an overload of that function that takes an rvalue ...
My opinion is that understanding (truly) how std::move and std::forward work, together with what their similarities and their differences are is the key point to solve your doubts, so I suggest that you read my answer to What's the difference between std::move and std::forward, where I give a very good explanation of t...
68,283,195
68,285,034
Undefined reference when defining a template function in the global namespace which is declared in an inline anonymous namespace
Given: namespace ns { inline namespace { template<typename T> void f(); } } template<typename T> void ns::f() {} int main() { ns::f<int>(); } GCC (trunk) complains that ns::f<int> is not defined. Clang (trunk) is fine with this. See: https://godbolt.org/z/n5qMs85q5 Is this a known bug in GCC? Is Cl...
GCC is right, the program is ill-formed. What can be done with members of an inline namespace is specified in [namespace.def]/7: Members of an inline namespace can be used in most respects as though they were members of the enclosing namespace. Specifically, the inline namespace and its enclosing namespace are both ad...
68,283,467
68,283,598
sort() error even when including <algorithm>
I have also copied the exact code from Programming Principles & Practice but to no avail. I get an error message when I try to use std::sort(word) or sort(word): <source>: In function 'int main()': <source>:13:14: error: no matching function for call to 'sort(std::vector<std::__cxx11::basic_string<char> >&)' 13 | ...
There are two problems in your code: your usage of sort is wrong, it's std::sort(words.begin(), words.end()). This should be in your book or in your learning material. in if (i == 0; words[i-1]!=words[i]) during the first iteration i is 0 and therefore you are accessing words[-1] which is out of bounds and which will...
68,283,528
68,284,411
Tinkercad Circuit: How to Make the Built-in LED and LED light up through a push button
I am new to Arduino and I have a problem making the built-in LED of the arduino board as well as the external LED connected to a bread board light up through a click of a push button. When I run it, it doesn't do anything. It only prints 0 on the terminal continuously. This is what my arduino looks like And this is th...
Your Arduino UNO built-in LED is on pin 13 so you can refer to it using the LED_BUILTIN constant. As for the push button, adding an internal PULLUP will work better (you can read about it in many posts). Also note the usage of bool instead of int for buttonState, it is more appropriate to my opinion. int pushButton = 2...
68,284,157
68,285,494
How many times value is copied when we return object by value?
I want to know if my understanding of temporary objects and returning by value is correct. So consider next code: int function() { int value = 0; /* Some calculations */ return value; } int main(int argc, char *argv[]) { int i = function(); return 0; } So when we call function in m...
It can be 0, 1 and 2, depending on compiler optimization capabilities and setting. See e.g. this answer: What are copy elision and return value optimization? One way how to be sure is to inspect the assembly created by your compiler. Another way is to use a single value class and add a print to all special member funct...
68,284,297
68,289,775
Parsing JSON data from TCP stream
I am using nlohmann's json library for parsing json data from a TCP stream. I am not quite sure how to handle partial json reads from local socket. Suppose that in the first read() I get: { "MessageType": "CancelOrder", "Account":11111, "CustomerNo":11111, "Side":"A", "DestinationMarket":"DUMB_MAR...
You've gotten some good answers in the comments. I'm going to assemble some and add one more choice. If you have control over both ends of the communications, then some people feel you should change the communications in one of two ways: Send the length of text first Or use a smarter messaging system over the socket ...
68,284,560
68,284,746
Google Kickstart 2020 round D- Record Breaker Question
is my solution is working Fine for all test cases. this is google kickstart 2020 round d question. for 4 test cases my output is correct. Time Complexity is also O(n). #include <iostream> using namespace std; int main(){ int n; cin>>n; int a[n+1]; a[n] = -1; for(int i = 0; i < n; i++){ cin...
The problem should be: Record Breaker - Kick Start Your code is wrong because it outputs 1 for input 3 1 2 2 while the answer should be 0. The first day is not record breaking because it is not the last day and the number is not strictly larger than one on the following day. The second day is not record breaking beca...
68,284,931
68,285,226
Single iterator for 2 vectors holding different elements (c++)
I have two vectors of same length. One of them holds vectors of double : std::vector<std::vector<double>> A; and the second one holds doubles std::vector<double> B; By "the same length" I mean that A contains as many vectors of double as B contains double. I would like to iterate through both of them with a single it...
In priciple you could write a custom iterator that has a first and a second that reference elements of A and B respectively. However, custom iterators aren't simple. The easier alternative is to use a plain old index based loop: for (size_t i = 0; i < A.size() && i < B.size(); ++i) { A[i]; // I access an element o...
68,285,765
68,285,816
Sorting vector of custom type with std::sort not working as expected
This is my class: class Animal { /// protected: const std::string name_; } This is my copy assignment operator: Animal& Animal::operator=(Animal const& a) { return *this; } And here my sort: std::sort(std::begin(animalVec), std::end(animalVec), [](Animal a, Animal b) { return a.getName...
Your copy assignment is wrong. It does not modifies its left-hand side operand. You should look toward this: Animal& operator=(Animal const& a) { name_ = a.name_; return *this; } Then note: The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defin...
68,286,052
68,287,667
CreateProcessAsUserW error code 6 Invalid Handle JNA
I'm using the JNA to call the Windows API. I want to start a process (doesn't matter which) as a specific user. The two API calls I use are: LogonUserW CreateProcessAsUserW LogonUserW succeeds, but CreateProcessAsUserW fails with Error 6. According to the Windows System Error Codes Doc, this corresponds to "ERROR_INV...
Looking at this piece of code: final PointerByReference userPrimaryToken = ...; Online documentation says it represents a pointer to pointer, C notation void** https://java-native-access.github.io/jna/4.2.1/com/sun/jna/ptr/PointerByReference.html On documentation for LogonUser it expects a PHALDLE pointer to a HANDLE,...
68,286,242
68,476,908
How to hide QMainWindow and show splashcreen during startup?
I am trying to hide the MainWindow of my Qt desktop app during startup, and to show a splashscreen. Both only happens after the loading phase, even though I call both splash.show() and window.hide() before the loading phase. I tried to split loading phase and constructor, but result is the same. How can I achieve both ...
Based on your code and some example I could make it run like you are trying to do. You only need to call your promptLogin function instead. #include <QApplication> #include <QTimer> #include <QSplashScreen> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app...
68,286,513
68,287,435
Creating a compile time string repeating a char n times
I'm using a function like this to export data in a xml file (note: silly example): void write_xml_file(const std::string& path) { using namespace std::string_view_literals; // Use "..."sv FileWrite f(path); f<< "<root>\n"sv << "\t<nested1>\n"sv << "\t\t<nested2>\n"sv << "\t\t\t<nested3>\n"sv...
If you want indent to work at compile-time, then you will require N to also be a compile time value, or for indent to be called as part of a constexpr sub-expression. Since this is for the purpose of streaming to some file-backed stream object FileWrite, the latter is out -- which means that you need N to be at compile...
68,286,800
68,289,143
Why is SSE alignement necessary while doing SIMD instructions?
I am new to C++, I only have 1.5 years of experience with that language. I have to work with a library that has premade data structures, and it offers a way to make our own data structure following certain rules in order to adapt it with the library. This is the PCL library. The data structure I am talking about is the...
SIMD means "single instruction multiple data". Modern computers have a number of ways to do more than one thing at once. There are physics limitations that make building computers that run much faster than 5 GHz difficult. So modern computers have instead gotten better at doing more than one thing at a time, rather t...
68,287,086
68,289,993
how to get the original mpi rank from split communicators
I split the world rank to the different commiunicators MPI_Comm_split(world_comm, color_, key_worker, &color_comm_worker); MPI_Comm_split(world_comm, color_master, key_master, &color_comm_master); int color_worker_size, color_master_size; MPI_Comm_size(color_comm_worker, &color_wor...
Let's start with communicator A containing ranks 0 1 2 3 4 5 You already know that the 'color' determines which processes end up in which communicator, so if we give the first three processes one color and the next three a different color, we end up with two communicators: The key tells the MPI implementation where to ...
68,287,218
68,287,328
different ways to pass an entire array by reference in C++
#include <iostream> template <class T> void call_1(T& in){ printf("%d\n", sizeof(in)); // 12 } template <int N> void call_2(int (&in)[N]){ printf("%d\n", sizeof(in)); // 12 } int main(){ int a[] = {1,2,3}; call_1(a); call_2(a); return 0; } I have a few questions based on the code snippet above: 1- is...
1. Yes, both are valid. 2. The type of a is int[3]. But arrays in most rvalue contexts, such as when passing by-value, decay to a pointer. The decaying doesn't happen when passing by-reference, so you end up with int(&)[3]. 3. Of course you can, but the type of the array dimension is not T, but size_t. So it should be ...
68,287,813
68,288,203
OMNeT ++ direct message transmission visualizations in 3D
I am new to OMNeT++ and I'm trying to implement a drone network that communicate with each other using direct messages. I want to visualize my drone network with the 3D visualization in OMNeT using the OsgVisualizer in inet.visualizer.scene package. In the dronenetwork.ned file, I have used the IntegratedVisualizer and...
Message passing and direct message sending visualizations are special cases implemented by the Qtenv automatically for 2D (default) visualization only. You can add custom 2D message visualization (like the one in the aloha example). OMNeT++ does not provide any 3D visualization by default. All the code must be provided...
68,288,476
68,405,145
Limit number of threads used in Concurrency::parallel_for
How to limit number of threads used in Concurrency::parallel_for<int>(0, 100, 1, [&](int k) I saw the scheduler/task idea, I fail to use it cause inside the parallel for there is a lot of logic and I need to pass arguments, all the examples for tasks is containing only std::cout<<"Hey"<<std::endl; inside the task. Ho...
I haven't used the interface - but the following might work (assuming 8 workers and parallel for 100 cases - otherwise adjust the 100/8). Concurrency::simple_partitioner splitter(100/8); Concurrency::parallel_for<int>(0, 100, 1, [&](int k) { //a lot of logic depends on the input }, splitter); This does not limit the n...
68,288,792
68,291,096
_mm256_rem_epu64 intrinsic not found with GCC 10.3.0
I try to re-write the following uint64_t 2x2 matrix multiplication with AVX-512 instructions, but GCC 10.3 does not found _mm256_rem_epu64 intrinsic. #include <cstdint> #include <immintrin.h> constexpr uint32_t LAST_9_DIGITS_DIVIDER = 1000000000; void multiply(uint64_t f[2][2], uint64_t m[2][2]) { uint64_t x = (f[0...
As Peter Cordes mentioned in the comments, _mm256_rem_epu64 is an SVML function. Most compilers don't support SVML; AFAIK really only ICC does, but clang can be configured to use it too. The only other implementation of SVML I'm aware of is in one of my projects, SIMDe. In this case, since you're using GCC 10.3, the ...
68,289,283
68,289,424
Problem while initializing reference variable of class through Member initialization list
code #include<iostream> struct A { private: public: int &p,q; A(int &k1,int k2):p(k1),q(k2) { } }; int main() { int x=2; A a1(x,3); std::cout<<&x<<"\n"; // std::cout<<&k1<<"\n"; commented out this as it gives error std::cout<<&a1.p<<"\...
It seems you misunderstand how references work. Once you have initialized a reference, you can never access the reference variable itself again. All use of the reference variable will be redirected to the variable being referenced instead. So in the A constructor, the variable k1 can never be used, all use of it will b...
68,289,963
68,300,601
Opencascade surface from points
I just want to write two simple functions with opencascade to be called from a C# winform application: one for create a surface from points, one for get the points of the surface. I don't write in C++, but following opencascade samples and by documentation and peace of code I arrive to this: OCCProxy.h #pragma once #i...
FINALLY, I could replicate and resolve the problem on my computer. The problem is in line #include "pch.h". This is precompiled header. It has to be included first. See here for the reason why: What is "pch.h" and why is it needed to be included as the first header file? So just move #include "pch.h" as first line and ...
68,290,161
68,290,495
C++ constructor: which exception type should I throw when malloc fails to allocate memory
So, imagine I have this code: typedef struct Point { float x; float y; } Point; class Foo { private: Point * p; public: Foo () { this->p = (Point *) malloc(sizeof(Point)); if (this->p == NULL) { // throw exception_malloc_fail; } ...
The most appropriate exception would be to throw std::bad_alloc; however it is strongly discouraged to use malloc unless you have a good reason to -- and so I would advise against throwing this explicitly. If you absolutely need heap memory, you should be using new/delete -- which will automatically invoke constructors...
68,290,362
68,292,743
Obtain TypeParam() inside the TYPED_TEST
I have a templated class that takes data type T and size_t size as templated arguments and wrote some unit-test to client class. I am repeating the same type of code at two different places one at the fixture and the other at TYPED_TEST in order to get the typed parameters. In Fixture using T = typename std::tuple_el...
After referring to the documentation from gtest The type alias (using or typedef) are made public in TestFixture template <typename Tup> class ClientTest : public testing::Test { public: using T = typename std::tuple_element_t<0, Tup>; static constexpr std::size_t size = std::tuple_element_t<1, Tup>::value; using...
68,290,802
68,291,197
Is this the best way to use unique_ptr to avoid leaks?
I'm a beginner and I am working to understand memory leaks. Does the code below have any leaks? Does it make sense to use unique_ptr for the vector and map? My purpose is mostly for performance and minimal tolerance in my code. If this code is wrong, please tell me where I made a mistake. typedef struct MyStruct { ...
The code is overly elaborate. If you just write the obvious it will work: std::vector<MyStruct> m_mp; void addvec2(std::string name, int age) { m_mp.emplace_back(name, age); } There is no need for pointers here. The best way to avoid leaks is to not make heap allocations. Of course, if the code in the question wa...
68,291,276
68,291,394
Find all n-digit strictly increasing numbers using c++
Problem Statement: To generate the n-digit numbers which will be in strictly increasing order. for example: 8–digit strictly increasing numbers are: 12345678 12345679 12345689 12345789 12346789 12356789 12456789 13456789 23456789 I am trying to use recursion to create n digit strictly increasing numbers. But I ain't ...
By removing +'0' in your code I already have something that works better (see here to test it online): #include <iostream> #include <string> #include <vector> // #include <string_view> #include <cmath> using namespace std; class Solution { public: void gen_num(int prev, string ans, int n, int ind){ // cout<<prev...
68,291,387
68,291,835
decltype of ternary operator is different in MSVC ~C++17
std::common_reference uses decltype to the ternary operator ?: Otherwise, if decltype(false? val<T1>() : val<T2>()), where val is a function template template<class T> T val();, is a valid type, then the member type type names that type; But MSVC says decltype(false? val<int&&>() : val<int&&>()) is int in the below c...
This is an MSVC bug. The rules for the conditional operator are in [expr.cond]. There are many parts of those rules that are quite complex, but this case is actually the easy one: If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value categ...
68,291,699
68,294,008
Problem with changing image inside the box FLTK
I have a problem with changing images(Fl_PNG_image size 25x25[enter image description here][1]) inside Fl_Box. So here is the part of code that changes the box: if(strcmp(payload, "heat")==0) tryb_pracy_box->image(grzanie_png); if(strcmp(payload, "cool")==0) tryb_pracy_box->image(chlodzenie_png); ...
I find it easier to just subclass Fl_Box and implement (override) the draw method. Within it you can call fl_draw_image(…) and fl_draw(const char *, …). This allows you to specify the coordinates of the text exactly over the image without fiddling with alignment relative to the image. You can store an image pointer wit...
68,291,738
68,292,334
Function call ambiguity in templatized code
Here is a (very distilled) use case and code example (sorry if it doesn't look too minimal, I couldn't figure out what else to exclude. The complete 'just compile' code can be found here: https://gcc.godbolt.org/z/5GMEGKG7T) I want to have a "special" output stream, which, for certain user types, does special treatment...
So you need to lower the priority of operator<<(Stream& s, const T& t) to make it the last resort. You can do it by making it (seemingly) less specialized, by templating the first parameter: auto operator<<(std::same_as<Stream> auto &s, const auto &t) -> decltype(s.stream(t)) { s.stream(t); return s; } The cha...
68,292,303
68,292,765
C# marshaling C++ functions
I am trying to use the Hikvision SDK https://www.hikvision.com/en/support/download/sdk/ My current goal is to open the door (trigger an output) with the intercom outdoor station. I managed to do the login (NET_DVR_LoginV40) and display the outdoor station's camera feed. My next step would be to open the door. For this ...
You allocate some memory with Marshal.AllocHGlobal, you do not copy your gateWay structure into that memory, you pass the pointer to the allocated memory to NET_DVR_RemoteControl so that it sees random garbage, and then you do not free the allocated memory so that it leaks. You could have fixed it by copying gateWay in...
68,292,337
68,292,822
Simple Time Comparison Multithreading Program in C++ (and 4 questions)
I have experience in C++ and I am trying to learn multithreading with the language. I just wrote the following program (code below questions) to compare the time efficiency of running ten function calls one by one vs in parallel. My four questions are: Is this a correct usage of the thread library ? The time seems rea...
This is not the correct way of measuring time. thread A(add, a); Here, a thread object will be created and it might execute the function immediately (depends on the OS scheduler). A.join(); Here, you are waiting for the thread to finish. Your basic flow is thread A(add, a); start timer A.join() end timer. So, your t...
68,292,524
68,292,611
member variable of a class needs more memory: address changes?
I guess my question requires no minmal working example; it's possible a no-brainer and easy to describe. Let's assume there is a class instance which stores some objects as members. Now one of the members grows during runtime. After creating the instance member1 consumed 10 bytes and member2 20 bytes. Then object1 is m...
Now one of the members grows during runtime. This scenario is not possible in C++. The size of an object (and the size of a type) is constant at runtime. member1 has now another address as before? No. The address of an object will never change through its entire lifetime. I have a Class instance whose members are ...
68,292,760
68,304,644
Pybind11: Wrap a struct with a pointer member?
I have the following struct I need to wrap struct dataStruct { const std::vector<int>& data; bool valid_data = true; } In my wrapper file, under PYBIND11_MODULE and so forth I have py::class_<dataStruct>(m, "dataStruct") .def(py::init<>()) .def_readwrite("data", &dataStruct::data) .def_readwrite("vali...
What I have done before is to write a wrapper struct around dataStruct that you expose to Python. This will allow you to keep an extra copy of the vector as an actual Python list. struct dataStructPy : dataStruct { const py::list & data_py; } You can then set data_py as a property instead of a readwrite and you ca...
68,292,775
68,292,803
Deallocating Template Objects on the Stack
Suppose I have a class that looks like the following: #include <stdlib.h> #include <stdio.h> #include "entry.hpp" #include "hashes.hpp" using namespace std; const double MAX_LOAD = 0.5; template <typename K, typename V, typename H = GenericHash<K> > class HashMap { public: HashMap(size_t init_capacity){ ...
Yes. For objects with automatic storage duration (e.g. local variables in functions), the destructor is always called as soon as that object goes out of scope. This is one fundamental piece of "RAII". This pattern is frequently used to create objects that "clean up after themselves." For example: struct Resource { ...
68,292,898
68,294,101
I cannot access some openGL functions
When I attempt to generate a buffer by executing the glGenBuffer() function - no function like that is found. Some functions are still working, and from what I see most do work, for instance the following code works perfectly: #include <iostream> #include <GLFW/glfw3.h> using namespace std; class Window_Manager { publ...
In addition to replacing glGenBuffer with glGenBuffers(1, &VBO) as rpress mentioned in the comments, OpenGL is a weird library in that you have to load most of the functions dynamically. The exact details differ from platform to platform. On Windows, for example, you can use wglGetProcAddress to get pointers to desired...
68,292,937
68,293,319
Proper way to use OpenMP in find all divisors of big number
On my class on university I need to create program in C++ which find all divisors of big number. I need to do it in several ways. One of them is to use OpenMP. So far i have this: void printDivisors(unsigned long long n) { stack<unsigned long long> numbers; #pragma omp parallel for shared(numbers) for (unsi...
Since it is your university work I give you hints not solution (code). The problem is with the OpenMP code is that numbers are shared, and write operations to containers and container adapters from more than one thread are not required by the C++ standard to be thread safe. So you have to add an openmp directive to pro...
68,293,177
68,293,749
GCC "AddressSanitizer: heap-buffer-overflow" when initializing struct
I've been writing an VM/Interpreter combination thingy, I don't know how to exactly describe it. Everything behaved as it should, now before I have hundreds of lines of code, I wanted to go into Garba Collection, because there were some pointers which somehow got lost, in some way. Not that I didn't delete pointers, I ...
Well, thanks to Retired Ninja and Richar Critten, I've got the solution. In mem_alloc() I've used sizeof(size) to allocate memory to the pointer, which of course is wrong. I guess my head was pretty much off after hours of coding. But I guess this problem is now solved.
68,293,221
68,293,350
Receive signal 6 in CCC grader, 2020 s3 Searching for Strings
Canadian Computing Competition: 2020 Stage 1, Senior #3 You're given a string N, called the needle, and a string H, called the haystack, both of which contain only lowercase letters a..z. Write a program to count the number of distinct permutations of N which appear as a substring of H at least once. Note that N can ha...
This error message is most likely because you keep adding a copy of each permutation to the no_repetition vector, which eventually exhausts the grader's memory and results in std::bad_alloc being thrown; this exception is not caught, and an uncaught exception results in std::terminate being called, which calls abort, w...
68,293,403
68,293,535
How can sizeof childclass be used in a parent template class with the child class as a template argument?
I'm reverse engineering and recreating a program which implements global static singletons. "A" would be a class that is stored in the singleton, and "B" is the singleton itself. Is there any way to make the following code work? template <class TClass> class B { static char cBuffer[sizeof(TClass)]; }; class A : pu...
You could do this but it's less than ideal: template <class TClass> class B { static char cBuffer[]; }; class A : public B<A> { int a; int b; }; template <> char B<A>::cBuffer[sizeof(A)];
68,293,556
68,293,585
Using pointer to print each element in a string by C++
I am currently working on a question, which uses a string input, then output each element in this string for example: input: "abcd" output: "a", "b", "c", "d" I know there are some easy ways to solve this problem, but I am trying to use a pointer, my idea is simple, find a pointer points to the initial char of the stri...
When you print a char* - while it DOES point to just a single character, you're actually telling the function to keep going until it gets to a null terminating character. ie - your string is actually "a" "b" "c" "d" "\0" Since the null is just a little further down, it prints all the way to the end; and then you do the...
68,293,886
68,293,905
"Double" is not printing more than 6 significant digits even after setprecision
I'm self learning C++ and for some reason "double" doesn't print more than 6 significant digits even after std::setprecision. Do I need to do something else? Most recent version of codeblocks if that helps. This is all the code: #include <iostream> #include <iomanip> using namespace std; int main() { std::setpreci...
You need to feed the result of std::setprecision(9) to std::cout. Otherwise it has no way of knowing what output stream it applies to (and so it won't apply to anything). std::cout << std::setprecision(9) << A << std::endl; Or if you prefer you can do it separately: std::cout << std::setprecision(9); std::cout << A <<...
68,294,194
68,296,866
Test full path to folder exists without relying on exception
I am working on a C++ UWP / WinRT application, and would like to test whether a given string represents a path to an extant folder, and I would like to do it without relying on catching an exception. Motivation at bottom. Looking through the UWP Storage API, it seems like the only routine along these lines which does n...
Test full path to folder exists without relying on exception I'm afraid you can't check the folder exists without relying on exception. You could refer the document. It is recommend way that check the folder relying on exception. As you mentioned above TryGetItemAsync is not static method, so it need a base folder in...
68,295,096
68,306,385
gsl::fail_fast not found in the namespace
In this simple use of C++ contracts, I get the error: no type named 'fail_fast' in namespace 'gsl'. Will try block throw the fast_fail exception or some other exception? #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/gsl> #include <iostream> int main(void) { try { Expects(false); } catch(co...
GSL_THROW_ON_CONTRACT_VIOLATION and gsl::fast_fail were removed from the Microsoft GSL starting with release v3.0.0. All contract violations result in a call to std::terminate unless you are building in kernel mode for MSVC where it invokes __fastfail. Header file gsl_assert.h only defines gsl::fail_fast exception wit...
68,295,121
68,296,899
How to add all the folders under `/lib` to "Additional Library Directories" in visual studio 2019
I have a folder path /lib. In it there is /lib/A/a.lib, /lib/B/b.lib, /lib/C/c.lib, .../lib/Z/z.lib. When I just put /lib in "Additional Library Directories", the linker cannot find a.lib, b.lib, ..., z.lib. It seems the linker will just search '/lib'. So how to make the linker search all the folders under /lib to find...
Unfortunately, you couldn't add all the folders under /lib to “Additional Library Directories”. You could only add the library path one by one.
68,295,406
68,297,225
A strange question on fread, offset don't match the document
//encrypt data void EncryptBlock(unsigned char*& blockdata, size_t n) { } //encrypt file bool EncryptFile(const char* path, size_t blocksize) { FILE* fp = NULL; auto erno = fopen_s(&fp, path, "rb+"); if (erno != 0) { printf("openfile:[%s] fail!!, errno=%d\n", path, erno); return false; ...
You need fseek between fwrite and fread. The standard says output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positionin...
68,296,163
68,299,630
Cleanup resources of base class before destructing derived class
I implemented an own Runnable to call threads: #include <iostream> #include <memory> #include <thread> class Runnable { public: Runnable(): running_thread_(nullptr) {} void run() { if(running_thread_) return; running_thread_ = std::unique_ptr<std::thread>(new std::thread(&Runnable...
An alternative could be to not let TestRunner inherit from Runnable but to let Runnable have a TestRunner member variable. This avoids the problem completely. I've removed the smart pointers here because I think they are only taking focus from the real problem that the derived class object may get destroyed under the f...
68,296,707
68,298,118
Recursive depth first search function is not working
Here is the code that I tried. class Node { public: char value; bool visited; vector<Node> adj; Node(char v) { value = v; visited = false; } }; void DFS(Node node) { node.visited = true; cout << node.value << endl; int i; for(a...
It is already suggested that you should use pointers to nodes in the adjacency vector of the node, but then you have to maintain the lifetime of the nodes outside of your graph and you can expect changes on the nodes outside the graph. You can also keep your node as it is and then work directly on the nodes in the grap...
68,297,904
68,297,960
C++ returning invalid iterator
My task is: Write a function that takes a pair of iterators to a vector and an int value. Look for that value in the range and return iterator to requested element. My implementation for the above task is: #include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; using data = vector...
When container is passed by value, it's a new vector copied from the argument. Then for return container.end();, the returned iterator belongs to container but has nothing to do with the original vector numbers. You should just return the e_iter directly, and no need to pass the vector, just like STL algorithms do. ite...
68,298,351
68,326,131
openmp omp declare uniform this not supported in GCC?
I have a simple matrix class which I'd like to vectorize its add operator. However, uniform this seems not to be supported under GCC (works fine using Intel C++ Compiler). I am curios if there is any workaround. (below is the code along compile command) Please let me know if you have any comments. #include <iostream> #...
It seems that in gcc you cannot use uniform(this) inside class declaration. It is OK in clang and Intel compilers. So, definition of the member function should not be in class declaration: #pragma omp declare simd simdlen(16) uniform(this) template <typename V> V& Matrix<V>::csi0 (int i) const { return data[i]; } ...
68,298,994
68,299,482
Non-const copy constructor compiles fine with C++17
I'd like to find out why the code below doesn't compile with C++14, but compiles fine with C++17. Any ideas what could be changed since C++17? The thing is of course about non-const copy constructor of a class A. I am using VS 2019. Is this code valid at all? class A { public: A() { } A(A& a) { } }; A fun() { ...
fun() is a prvalue of type A, so A a = fun(); means that a is the result object of the function call, there is no intermediate temporary. The text for this is in C++17 [basic.lval]/2: The result object of a prvalue is the object initialized by the prvalue; It would be the same for A a = A(A(A(A(A(fun()))))); etc. -...
68,299,518
68,299,631
Removing classes from an array C++
I have a vector array for classes and im making a method that can delete the classes from that array, using std::remove(). The problem is Weapon (the class) doesn't have an operator == that std::remove needs to compare the elements. the code: class Weapon { public: std::string name; Weapon(std::string x) { ...
std::remove needs operator== (this is requirement of c++ standart library). And you can adds the operator into your class, or use std::remove_if - it use predicate - external function for comparison. There is third way: you can erase items from vector manually: for (...) { erase ...}
68,299,663
68,301,955
C++: candidate template ignored when iterating over tuple
I am attempting to iterate through a tuple using the following code: template <std::size_t I = 0, typename... Ts> requires (I >= sizeof...(Ts)) static inline auto consume_all(std::tuple<Ts...>&&, auto) -> void {} template <std::size_t I = 0, typename... Ts> requires (I < sizeof...(Ts)) static inline auto consu...
After looking at @Jarod42 's comment I have found a better way to iterate through a tuple that side-steps the template issue. Defining consume_all as an iterative function is not the way to go. Instead consume_all should be defined using std::apply(func, tup) which parses the tuple tup as the argument for func. This no...
68,299,971
68,300,041
Visual studio error: Error (active) E0254 type name is not allowed
Visual Studio says: Error (active) E0254 type name is not allowed What did I do wrong? #include <iostream> #include <string> using namespace std; class ComplexNumber { public: float Real; float Virtual; ComplexNumber Addition(ComplexNumber a, ComplexNumber b) { ComplexNumber Result;...
ComplexNumber is a name of the class, so you cannot use its member via . operator like ComplexNumber.Display and ComplexNumber.Addition. You should spedify a name of variables, not a name of a class, before . operator like: string str = a.Display(a.Addition(a, b)); In this case it looks better to declare static functi...
68,300,013
68,300,068
Anomaly in Priority Queue Custom Sort in C++
I went through a couple of StackOverflow and Codeforces articles for custom sorting priority queues in C++. By default the C++ implementation is a MaxHeap , so it would output elements in decreasing order. I minor tweak adding greater<int> would pop ascendingly. I tried this out using my own comparator function, as bel...
I would suggest you to read the compiler warnings... you will see that bool operator()(const int &a,const int &b) if a<=b doesn't have a return statement... and that's Undefined Behavior Instead you should do this: #include<bits/stdc++.h> using namespace std; class comp{ public: bool operator()(const int &a,con...
68,300,026
68,301,140
Number of ways in which you can climb a staircase with 1, 2 or 3 steps - memoization
I have to calculate the number of ways one can climb a staircase taking 1, 2, or 3 steps at a time. I know of ways to do this, for example, f(n-1) + f(n-2) + f(n-3) but I would like to know why in my implementation (which is different from the above) I do not get the correct answer. I'm using a for loop instead. The pr...
I solved it like this : #include <iostream> #include <map> using namespace std; map<int, int> memo; int stepPerms(int n) { if (memo.find(n) != memo.end()) return memo[n]; if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; if (n == 3) return 4;...
68,300,742
68,301,506
Can template specialisation be avoided in this case?
I recently came across the following: // declare template <class> struct A; // specialise template <template <class...> class C, class... Fields> struct A<C<Fields...>> { template <typename... Args> explicit A(C<Fields...>* c, Args&&... args) {} }; // instantiate template <template <class...> class C, class... Fields...
Their usage syntax is different: first snippet would be A<std::vector<int>> a(&some_vector, 42, 51); whereas the second would be A<std::vector, int> a(&some_vector, 42, 51); Which is indeed mitigated with MakeA. But, difference might be important in template, where you would need to "propagate" the different signatur...
68,300,868
68,300,985
Update the value of object reference
I have a function as below. I tried to change the value of object reference to a new object by using dir = Directory(path); but I got a compilation error as below. Any advice? Also is this a good way to do this? Error C2280 'Directory &Directory::operator =(const Directory &)': attempting to reference a deleted func...
You ask your copy-assignment operator to be implicitly defined: Directory& operator=(const Directory&) = default; Meanwhile you have const data members: const fs::path path; // Consider omitting the const here const double deltaBase = .001; // Seems like a candidate for a static member The synthesized (implicitly def...
68,300,950
68,304,664
Roman to Integer using STL in C++
I'm new to STL, I was trying to convert the Roman numerals into their corresponding integers using maps and vectors. But, my outputs are varying a lot and aren't accurate. For Instance output for "X" is 20 but output for "XI" is 12. I am taking string as an input and then splitting it up into characters and storing the...
Your for loop seems to run more than needed. int res=0; for(int i=0;i<s.size();++i){ if(roman[s[i]]<roman[s[i+1]]){ res -= roman[s[i]]; } else{ res += roman[s[i]]; } } res += roman[s[s.size()-1]]; cout<<res; There is another iteration at the end of the for...
68,301,184
70,565,212
How do I convert HSV mask to BGR?
For this colour detection program I'm writing, I essentially convert an image to HSV and mask it to detect yellow (so white where yellow is, black otherwise) & then simply see if a given pixel is white or not. const cv::Mat roiImage = // read in image ... ; cv::Mat tmpMask ; cv::cvtColor(roiImage, tmpMask,...
"Your tmpMask is a single channel (i.e. grayscale) image, so you can't convert from HSV, which would be a three channel (i.e. color) image. Also, you don't need to convert to BGR. Simply check, where tmpMask is 255 (white in "grayscale color space")." ~ @HansHirse cv::cvtColor(tmpMask, yellowMask, cv::COLOR_GRAY2BGR) ;...
68,301,341
68,301,383
How to declare a function which takes an array by reference as an argument in C++?
I have this code with function which takes two-dimensional array by reference and its bounds by template as an arguments: #include <stdio.h> void Foo(); // I need it here int main() { char Space[10][10]; Foo(Space); return 0; } template <size_t rows, size_t cols> void Foo(char (&array)[rows][cols]) { ...
Just put that declaration up where you want it: #include <stdio.h> template <size_t rows, size_t cols> void Foo(char (&array)[rows][cols]); int main() { char Space[10][10]; Foo(Space); return 0; } template <size_t rows, size_t cols> void Foo(char (&array)[rows][cols]) { size_t j; size_t i; fo...
68,301,924
68,303,399
expose c++ class to cython via module
What do I want to do: install a python/cython module exposing a c++ class and being able to cimport it in any .pyx files later. What does not work: I cannot manage to cimport the file once the module is installed. The cython compilation is working as I can use the wrapped class in pure python. File structure: ├── cytes...
I managed to get it to work: I renamed the extension names to fit the pyx I made sure the pxd imported the hpp in relative import (cdef extern from "../hpp/node.hpp":) Finally, in order to make the package_data to find and include all the files in the repository (needed to reuse the code in later pyx), I added an empt...
68,302,020
68,302,179
Boost cubic Hermite interpolation "requires template argument list"
I am attempting to use cubic Hermite interpolation from the boost library in order to interpolate non-equispaced data. However, implementing the example from the documentation produces the error "C2955: 'boost::math::interpolators::cubic_hermite': use of class template requires template argument list". Here is my code:...
The code example suggests that you want to use class template argument deduction (for the RandomAccessContainer template parameter of cubic_hermite). Either make sure that your compiler is working with the C++17 standard (as no earlier standard supports this feature) or explicitly specify the template argument, such as...
68,302,226
68,302,308
Stop ofstream from creating a file
I'm trying open a file and check if it exists yet it creates a new file if the given file does not exist. If it is going to automatically create a file, what's the point of the isOpen() then? int main() { std::ofstream defaultFile; defaultFile.open("AAAAA.txt"); std::cout << defaultFile.is_open();//this will always pri...
what's the point of the isOpen() then? Creating a file can fail for numerous reasons. One could be that you have no write access in the directory where you try to create the file. In that case defaultFile.open("AAAAA.txt"); will fail and is_open will return false. If you want to know if the file exists before creati...
68,302,536
68,303,434
Thread-ID is always the same in my boost::asio::thread_pool
I tried the example from the boost docs: #include <boost/thread/thread.hpp> #include <iostream> #include <boost/asio/post.hpp> #include <boost/asio/thread_pool.hpp> int count = 0; void my_task() { count++; const auto my_count = count; std::cout << "Task " << my_count << ") BEGIN: Thread-ID:" << boost::thi...
Thanks Kaldrr! I changed all occurances of boost::this_thread::get_id to boost::this_thread::get_id() which led to the expected output of different Thread IDs: Main-thread-ID: 5a78 Task 1) BEGIN: Thread-ID:77d0 Task 1) BEGIN: Thread-ID:5f34 Task 1) END: Thread-ID:5f34 Task 1) END: Thread-ID:77d0 Task 2) BEGIN: Thr...
68,302,704
68,303,738
read csv string into vector C++
There are many options of csv to vector, including read a csv file and and add its all data into vector in c++ however I want to something a bit above or below csv -> vector. Instead, I have a CURL function that loads csv data into a std::string in the format of col1,col2,col3 abc,2,ghi jkl,2,pqr which, each row is se...
If it is only parser you need to crate in your application, you can build some simple streaming recursive parser like this: #include <cctype> #include <cstring> #include <vector> #include <string> #include <iostream> struct data { std::string col1; int col2; std::string col3; }; std::ostream& operator<<(std::os...
68,302,855
68,302,996
boost::spirit string to array by separator
I need to parse number from string "1/20/10/3/5". Number - is positive integers, "/" is separator. I write the next expression: ('"' >> +(qi::uint_ ^ "/") >> '"') It's work fine, but parser allow the next string "1//3". How I can change my expression to fail that string?
You are using ^, the permutation parser, which matches "/" and/or qi::uint_. What you want is the list parser: %. ('"' >> qi::uint_ % "/" >> '"')
68,302,912
68,306,527
Call Ninja.exe exited with code1
I am trying to create an application in which I am using gn. I tried creating the .exe file with the following command. gn gen out --ide=vs ninja -C out Then, I opened the generated solution file and tried building it, but I am getting an error which says MSB3073 The command "call ninja.exe -C path\to\sln\file main" ...
My Solution revolves around GN with ninja for Cross-platform development. We use the following commands for creating build files:- gn clean out //Cleans the build files gn gen out gn gen --ide=vs out //Creates .sln file for the build files ninja -C out //Build Files But to build using visual studio, by default, the...
68,303,194
68,303,708
Why adjustSize doesn't resize MainWindow in Qt?
I have a simple application. In MainWindow's constructor I have: _someWidget = new someWidgetClass(this); _someWidget ->setFixedSize(700,700); _someWidget ->move(50,50); wid = new QWidget(this); wid->move(800,800); wid->setFixedSize(100,100); centralWidget()->adjustSize(); adjustSiz...
you should set one layout for centralWidget , For Example, I test it with QGridLayout. then add your widget in that layout : auto _someWidget = new QWidget(this); _someWidget->move(50, 50); _someWidget->setFixedSize(700, 700); centralWidget()->layout()->addWidget(_someWidget); auto wid = new QWidget(this); wid->mo...
68,303,313
68,303,472
Narrowing conversion required while using a P-RNG
I am trying to get a random number between a minimum value and a maximum value, but i get a narrowing conversion error. I have checked the template parameters of uniform_int_distribution so using a short shouldnt be an issue. Template parameters IntType - The result type generated by the generator. The effect is und...
1 is an int, as numeric literals are int unless otherwise specified. maxPosX-1 and maxPosY-1 are also ints, for historical C reasons. Operators on integer types that are smaller than int produce int results. Solution 1: Cast them to short. std::uniform_int_distribution<short> randX{ short(1), short(maxPosX-1) }; std::...
68,303,436
68,305,068
Missing elements in unsorted array in C++
Anyone can explain to me this logic of unordered set in STL C++ because I am new to this concept. How that they are printing missing elements of an array using an unordered set. Is this approach is efficient or there is any other approach efficient than this one. Logic is below: for (int x = low; x <= high; x++) ...
In the general case this will likely be the most efficient way to do it. An unordered_set has a constant time complexity on average for insert and find so you're able to store elements you've seen before quickly in the first for loop, then go through the whole range and quickly check if you've seen them. As an example ...
68,303,854
68,303,917
c++ - have a function output the information of a separate function to a textfile
I want to output what one of my functions prints out into a separate textfile. I have tried what I have below but I get an error saying "invalid operands to binary expression" when I try outfile << print();. Any help would be appreciated. #include <fstream> #include <iostream> #include <sstream> #include <string> usin...
print() returns a void, so you can't use it in a ... << print() expression. Make print() take the desired output stream as a parameter instead, eg: #include <fstream> #include <iostream> #include <sstream> #include <string> #include "Lab.h" using namespace std; void print(ostream &out = cout); int main() { print()...
68,303,988
68,304,028
Is a member initialization list without a value defined?
Say I have : class Foo { public: int x; Foo() : x() {} } Would it be UB to read x after the constructor has ran? More specifically, what type of initialization is this, zero, direct or default initialization? I know if instead we'd have: Foo() : x(42) {} x would be direct-initialized to 42 but I'm not so sure fo...
what type of initialization is this x() performs value-initialization: when a non-static data member or a base class is initialized using a member initializer with an empty pair of parentheses or braces (since C++11); As non-class type int, x is zero-initialized as 0 at last. otherwise, the object is zero-initial...
68,304,229
68,405,634
Project Linking and Compiling files
I want to start building a project and I have the following folder structure: lib |---class1.cpp |---class1.hpp src |---main.cpp I have the MinGW compiler and I don't know how to compile all .cpp files. I know the command g++ *.cpp -o main for compiling all the files, but works only for files in the same folder. Shou...
For a barebones project, your structure is fine. Just add the following CMakeLists.txt file to the root of your directory: cmake_minimum_required(VERSION 3.5) # Given your project a descriptive name project(cool_project) # CHoose whatever standard you want here... 11, 14, 17, ... set(CMAKE_CXX_STANDARD 14) # The fir...
68,304,268
68,304,347
C++ pthread hand over object to thread
I think with my code, I hand over the address of the object to the thread. However I cannot access the object directly (args.getTerminationStatus). Unfortunately I only make a copy of that passed object and therefore changes of attributes take no effect (the while loop ist running forever, even thought the attribute be...
You can avoid the copy by changing the conversion line to: Sensors& dev = *(Sensors *) (args); so that now it will be a reference to a Sensors object rather than a copy. Assuming getID() is a Sensors class method you can then do: cout << dev.getID(); after you've converted it. If you haven't considered it yet, using ...
68,304,356
68,304,990
What object is produced by ternary operator in C++?
The following program #include <optional> #include <iostream> int main() { std::optional<int> a; constexpr bool x = true; const std::optional<int> & b = x ? a : std::nullopt; std::cout << (&a == &b); const std::optional<int> & c = x ? a : (const std::optional<int> &)std::nullopt; std::cout <<...
First you have to undesund what is the type of ternary operator result. x ? a : std::nullopt; Here a is variable which can be reference and std::nullopt is something which is implicitly converted to optional of matching type (here std::optional<int>). So conversion of std::nullopt ends with creation of temporary value...
68,304,606
68,304,652
Printing Doubly-Linked-List in main() behaves different than printing it with an outside function
If I write the while loop below (uncomment to compile it) that prints the nodes in this doubly-linked-list, I see that "all_gods" list becomes empty (because of "all_gods = all_gods->next();") all_gods: 0x560c837b1f30 Odin 0x560c837b1ef0 Ares 0x560c837b1eb0 Zeus 0x560c837b1f30 Odin 0x560c837b1ef0 Ares 0x560c837b1eb...
Function arguments in C++ (other than references) are copies of what are passed. When you use the loop function to print the list, the value of all_gods is copied to the argument p. Then, the argument p is used to print the list without giving any effect to the variable all_gods.
68,305,059
68,305,185
C++ templated function with various amount of argument
I have a templated function which generates a list of a certain type. For each type the list is formed by an overloaded function. Roughly it looks something like this void Process(std::vector<Type1> &vector){ } void Process(std::vector<Type2> &vector){ } void Process(std::vector<Type3> &vector){ } template <class T>...
An option would be something like this: void Process(std::vector<Type2> &vector); void Process(std::vector<Type3> &vector, const Config& config); template <class T, typename...ProcessParams> std::vector<T> DoFoo(ProcessParams&&... process_params) { std::vector<T> my_vector; ... Process(my_vector, std::forw...
68,305,172
68,305,342
Combining auto template parameters with std::optional, possible?
I really like C++17's auto template parameters as I don't have to jump through hoops in order to use non-type template arguments (such as functions with forwarded arguments). But it got me thinking if it was possible to combine it with some other type (such as std::optional) in cases where there's no valid result from ...
You could deduce what type of std::optional you want from the function passed in. Then you can return an empty optional if it throws. #include <iostream> #include <optional> template <auto Func, typename E, typename ...Args> auto safeCaller(Args&& ...args) { using ret = std::optional<decltype(Func(std::forward<Arg...
68,305,755
68,305,984
C++20 custom class for combining std::osyncstream and std::cout together
I would like to use std::osyncstream and std::cout in a multi threaded context without writing everytime: std::osyncstream(std::cout) << "my message" << std:endl; What I want to achieve: streams::synced_cout << "my message" << std:endl; What I have done: namespace streams { class _synced_cout { private: ...
osyncstream is kind of like unique_lock: every thread needs to construct its own instance of osyncstream because there is no synchronization on access to the osyncstream itself. All it does is buffering output in an internal buffer and eventually transferring that to the wrapped stream (or really, streambuf). Only the ...
68,305,792
68,306,081
Function candidates and declaration order
Consider the following snippet: template<typename T> int foo(T) { return 1; } struct my_struct{}; template<typename T> int do_foo(T t) { return foo(my_struct{}) + // 1 foo(t); // 2 (via ADL) } int foo(my_struct) { return 2; } int main () { return do_foo(my_struct{}); } At first ...
This entire paragraph only applies to functions resolved with ADL: For a function call where the postfix-expression is a dependent name [...] If the call would [...] (Here "the call" refers to each call with a dependent name, so this wouldn't apply to foo(my_struct{}), which isn't dependent) The second case is covere...
68,306,057
68,306,985
Checking whether a pointer has been set to an initialized object
Suppose I have a class called Entry: template <typename K, typename V> class Entry { public: Entry(K const &key, V const &val, size_t const hash_val) : key(key), val(val), hash_val(hash_val), empty(false){ } K getKey() const { return key; } V getValue() const { return val; ...
You want optional. It's always either a valid object, or in an "empty" state. #include <cstdio> #include <optional> #include <vector> struct Foo { int bar; }; int main() { std::vector<std::optional<Foo>> vfoo{ Foo{1}, std::nullopt, Foo{2}, Foo{3}, std::nullopt, }; for (auto const& foo : vfoo) { if ...
68,306,229
68,312,374
error: Microsoft Visual C++ 14.0 or greater is required during installation of pandas-profiling
As a dependency of the Python module pandas-profiling, an attempt is made to install the module Bottleneck (offers Fast NumPy array functions - but is written in C). The installation aborts with this error message: error: Microsoft Visual C ++ 14.0 or greater is required. Get it with "Microsoft C ++ Build Tools": ht...
I found a compiled version of the module Bottleneck (Unofficial Windows Binaries for Python Extension Packages. After the installation as wheel the Python module pandas-profiling could be updated.
68,306,443
68,306,788
Print values of an array without passing as a parameter
Is there a way to print the values of infoArray from PrintReport() without passing the infoArray as a parameter? int main() { int sizeOfArray = 3; float subjectP[sizeOfArray]; float subjectQ[sizeOfArray]; float infoArray[sizeOfArray]; InputMarks(subjectP, sizeOfArray); InputMarks(subjectQ, ...
You can either make the variable infoArray[] global, or make use of classes. I recommend using a class, making the variable infoArray be a private member. You can access it within the class, and you have the possibility to create a public getter for that variable, if needed.
68,306,464
68,306,887
Taking input inside a recursive function (one time input on the first iteration) in c++
Until now, for me the only way to retain a particular variable value inside of a recursive function is to pass it as a parameter. But this time i am specifically required to write a function which takes only two integers as parameters, and takes a string input on the first iteration. Pseudo code: function (int a, int ...
The simple solution is to use a "static" variable instead of a local variable. According to the specific instructions given, it was not possible to declare a variable globally outside of the function and the parameters were fixed. By simply declaring the string variable as static, it is possible to make it retain it's ...