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
69,604,839
69,617,582
Unable to display image opencv (c++)
I finally managed to build the opencv4.5.4 library from source but now I'm facing errors that I'm unable to fix. I'm using this medium article as my guide https://medium.com/analytics-vidhya/how-to-install-opencv-for-visual-studio-code-using-ubuntu-os-9398b2f32d53 When I try to execute a simple program that prints the ...
When I tried to build opencv4 again, I was able to figure out that cmake was unable to find the gtk+-3.0 module that's installed in my system. username@Inspiron-7591:~$ pkg-config --modversion gtk+-3.0 Package gtk+-3.0 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtk+-3....
69,605,048
69,605,126
Calling a callback passed from another class
I want to register a callback handler (method) of the one class (Y) in another (X). I can't use std::function because of possible heap allocation and I must have an access to members of a class that registers the handler. I also want to avoid static functions. I've came up with some workaournd but got stuck on calling ...
The member function pointer needs a specific class object to invoke, so you need to do this: template<class T> class X { public: // ... void call(T& obj) { (obj.*callback)(); } // ... }; class Y { public: // just for a test: fire a callback in class X void fire() { x.call(*this); ...
69,605,073
69,605,540
antlr visitor: lookup of reserved words efficiently
I'm learning Antlr. At this point, I'm writing a little stack-based language as part of my learning process -- think PostScript or Forth. An RPN language. For instance: 10 20 mul This would push 10 and 20 on the stack and then perform a multiply, which pops two values, multiplies them, and pushes 200. I'm using the vis...
With ANTLR, it's usually very helpful to label components of your rules, as well as the high level alternatives. If part of a parser rule can only be one thing with a single type, usually the default accessors are just fine. But if you have several alternatives that are essentially alternatives for the "same thing", o...
69,605,973
69,606,233
Comparison of two vectors leads to an exception
Comparing the two vectors in the if statement throws an exception (segmentation fault). I was having an attempt to create a system, which, user details are being saved in a file and being read to give security questions to the user. #include <iostream> #include <string> #include <vector> #include <fstre...
Thanks to @IgorTandetnik the issue was that the file was empty.
69,606,301
69,606,443
How can i create multiple threads cleaner?
so i creating multiple threads with the following way: std::thread Thread1(func1); Thread1.detach(); std::thread Thread2(func2); Thread2.detach(); I doing that around 10 times, and it works perfectly fine, but it just looks ugly, is there any method to do it cleaner? Thanks!
You can achieve this syntax for (auto func : { func1, func2 }) async(func); with this example : #include <chrono> #include <functional> #include <vector> #include <thread> #include <iostream> void func1() { std::cout << "1"; } void func2() { std::cout << "2"; } // Make functions out of repeated things temp...
69,606,521
69,607,314
How to remove the last number 0 in the fibonacci series in c++?
I m trying to remove the last 0 in the fibonacci series as i m removing return 0; the last value is showing garbage value something like 735150 what should i edit to get the desired output as 0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 as i m getting the output 0 1 2 3 5 8 13 21 34 55 89 144 233 377 6...
I'm perfectly aware this isn't code review but OP asked for a simpler version. This is not conforming to the odd copy constructor requirement, but rather to show that printing the fibonacci numbers can be dealt with in a few(8) lines of code. #include <iostream> #include <vector> #include <algorithm> // This is a poor...
69,606,918
69,608,298
Maximum number of packets
There are r red balls, g green balls and b blue balls. Also there are infinite number of packets given to you. Each packet must be filled with only 3 balls and should contain balls of at least 2 different colors. Find the maximum number of packets that can be filled? Here is my approach using Dynamic Programming which ...
Assume without loss of generality that r ≥ g ≥ b by permuting the colors. The answer is at most ⌊(r+g+b)/3⌋ because every packet needs 3 balls. The answer is at most g+b because every packet needs a green ball or a blue ball. It turns out that the answer is equal to the minimum of these two quantities (so without the a...
69,607,185
69,607,296
How to know which keys are pressed in SDL2
How would I know what keys are currently being pressed in SDL2 (not event)?
if (SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_???]) {/*the key is held*/} where ??? is a key name, one of those.
69,607,408
69,644,189
C26485 and pointer decay with TCHAR in exception handler
I don't understand this C26485 warning I receive. My code is an exception handler: catch (CDBException* e) { TCHAR szError[_MAX_PATH]; e->GetErrorMessage(szError, _MAX_PATH); AfxMessageBox(szError); } It is saying: Expression szError: No array to pointer decay (bounds.3). Both GetErrorMessage and AfxMess...
This diagnostic is an unfortunate result of the code analysis taking too narrow a view, ignoring hints that are readily available. C26485 warns against array-to-pointer decay, one of C++' most dangerous features. When passing the name of an array to a function that expects a pointer, the compiler silently converts the ...
69,607,416
69,607,512
Operator Overloading Matrix Multiplication
The issue I am having is how to get the correct number columns to go through for the inner most loop of K. An example is a 2x3 matrix and a 3x2 matrix being multiplied. The result should be a 2x2 matrix, but currently I dont know how to send the value of 2 to the operator overloaded function. It should be int k = 0; k ...
Linear algebra rules say the result should have dimensions rows x dx.cols Matrix Matrix::operator * (Matrix dx) { Matrix mult(rows, dx.cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { mult.cx[i][j] = 0; for (int k = 0; k < cols;k++) //...
69,607,484
69,607,550
Generate string lexicographically larger than input
Given an input string A, is there a concise way to generate a string B that is lexicographically larger than A, i.e. A < B == true? My raw solution would be to say: B = A; ++B.back(); but in general this won't work because: A might be empty The last character of A may be close to wraparound, in which case the resulti...
You can duplicate A into B then look at the final character. If the final character isn't the final character in your range, then you can simply increment it by one. Otherwise you can look at last-1, last-2, last-3. If you get to the front of the list of chars, then append to the length.
69,607,662
69,607,757
Why does This program have a logical error
this is the code i wrote for simple grading exams (im still a very beginner) but when i do a wrong input in (Grades) it doesnt go to the function i made which is called (FalseInput) to make the user able to re-enter the (Grades) any suggestions to how to solve? and how to improve in general ? here is an example of what...
You don't check if the extraction of an int succeeds here: cin >> Grades; You can check the state of the input stream after extraction like this and it needs to be the first condition or else the program will make the comparisons with MinGrade first and will get a true on Grades < MinGrade. if(!(cin >> Grades)) { ...
69,607,676
69,608,519
C++ and reading large txt files
I have a lot of txt files, around 10GB. What should I use in my program to merge them into one file without duplicates? I want to make sure each line in my output file will be unique. I was thinking about making some kind of hash tree and use MPI. I want it to be effective.
build a table of files, so you can give every filename simply a number (a std::vector<std::string> works just fine for that). For each file in a table: open it, do the following: read a line. Hash the line. Have a std::multimap that maps line hashes (step 3) to std::pair<uint32_t filenumber, size_t byte_start_of_line>...
69,607,679
74,289,942
Cereal seems to not properly serialize an std::string
I am trying to serialize a class into a binary, to that effect I first started trying to serialize an std::string member within the class, I wrote this serialization method: template<typename Archive> void ShaderProgram::serialize(Archive& archive, ShaderProgram& program) { archive(CEREAL_NVP(program.program_name))...
Here is an example. All is fine with cereal. In plain C++ remove Rcpp connections. // [[Rcpp::depends(Rcereal)]] #include <string> #include <fstream> #include <cereal/archives/binary.hpp> #include <cereal/types/string.hpp> #include <cereal/access.hpp> #include <Rcpp.h> struct ShaderProgram { ShaderProgram(){}; Sha...
69,607,808
69,607,842
Why is my change to a range-for loop not work?
I'm at a loss. I am trying to sum two numbers of vector such that they equal target, then return their indices; however, when running the code with a C++11 for-loop, the result is incorrect. With vector [2,7,11,15] and target=9, the result for the C++11 loop is [0, 0]. Using the C-style loop, it is [0,1]. What gives? c...
Your outer loop is setting i to the actual value within your nums vector, but your inner loop is using it as if it's an index! As an explicit example, on the first iteration of your outer loop, i will be 2 and so your inner loop will start at x : 3. Since you're actually interested in the index as part of your calculat...
69,608,219
69,608,598
Getting incorrect vectors when trying to do mouse picking in OpenGL 3
I am trying to get a direction vector to where my cursor is on the screen, however it gives me large values instead of the actual values. When doing mouse picking I am getting extremely small numbers for my world coordinates such as Mouse is pointing at World X: 4.03225e-05 Y: -0.00048387 Z: -1 Am I doing something wr...
When using orthographic (parallel) projection, the point of view is not (0, 0, 0), (not in view space and of course not in world space). You have to create a ray from the near plane (-1) to the far plane (1): glm::vec4 worldPosFar = invVP * glm::vec4(mouseX, -mouseY, 1.0f, 1.0f); glm::vec3 mouseClickVecFar = glm::norma...
69,608,300
69,608,382
Why does this char array need to be static?
const char * u8_to_bstr(const uint8_t & u8) { static char s[9]; // space for 8-char string s[8] = 0; // terminate string char * sp = s; for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) { cout << s << endl; *(sp++) = ((u8 & xbit) == xbit) ? '1' : '0'; } return s; ...
The function returns s, which is declared on the stack of this function. Were it not static, it would go out of scope, effectively disappear, once the function returns because all the storage on the stack is made available for reuse once a function returns. By making it static, it’s forced to have a persistent address ...
69,608,468
69,687,474
How to force llvm cmake to use only given path to libs?
I try to build llvm on a system where I have no root access. So, I've got some problems: I have been obliged to install gcc, cmake in my $HOME path because system's gcc and cmake are very old and I cannot update them with sudo. I finely installed gcc and cmake and mentioned new paths to PATH env variable. I ran cmake f...
I found a solution that worked out for me. Find out what a path contains needed libraries (in my case it is /home/my_user/local/lib64 and then run LD_LIBRARY_PATH=/home/my_user/local/lib64 make!
69,609,113
69,609,158
For loop won't run when comparing length of Vector to a negative number in C++
I have a pair of nested for loops and I am attempting to print the following structure: 0 1 2 3 4 0 - - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - If I attempt to initialize the row counter of the outer loop to -1, and compare it to the length of the vector using .length(), the outer loop simply doe...
If all you're doing is printing out the board, you really shouldn't be starting at -1, but 0 instead. That is: std::cout << " "; for (std::size_t col = 0; col < board[0].size(); ++col) { std::cout << col << " "; } std::cout << std::endl; for (std::size_t row = 0; row < board.size(); ++row) { std::cout << row...
69,609,483
69,611,541
c++ partial template specialization with requires statement: error: out-of-line definition of 'foo' from class Bar<T> without definition
Consider the following code which attempts to implement a partial specialization of class Bar. In the first case, the foo member function is defined inline and in the second case out of line. The out of line definition produces a compile error which I cannot figure out: error: out-of-line definition of 'foo' from class...
Might be clang bug. It was reported at https://bugs.llvm.org/show_bug.cgi?id=50276. Anyway GCC is fine
69,609,675
69,609,719
What does explicit *this object parameter offer in C++23?
In C++23, deducing this is finally added to the standard. Based on what I've read from the proposal, it opens up a new way of creating mixins, and possible to create recursive lambdas. But I'm confused if this parameter creates a "copy" without using templates since there is no reference or does the explicit this param...
Section 4.2.3 of the paper mentions that "by-value this" is explicitly allowed and does what you expect. Section 5.4 gives some examples of when you would want to do this. So in your example, the self parameter is modified and then destroyed. The caller's hello object is never modified. If you want to modify the caller...
69,609,778
69,619,946
Using ctypes to call a C++ method with parameters from Python results in "Don't know how to convert parameter" error
I'm trying to use the following C++ class from Python3.7, but can't get the first method 'Set' to work, much less the operator overload methods. I've tried many variations of the Python wrapper and the extern block but I either get the "Don't know how to convert parameter 5" error or a segmentation fault. The examples ...
You have to match the arguments exactly. Set the .argtypes and .restype of every function you use so ctypes can properly marshal the parameters to C and back again. If you do not set .restype ctypes assumes the return value is c_int (typically a signed 32-bit integer) instead of a (possibly 64-bit) pointer. Here's a ...
69,610,000
69,610,043
Why does the compiler not recognize Node as a type? It is a private class within AVLTree
class AVLTree{ struct Node { K key; V value; Node* left; Node* right; int height; /** * Node constructor; sets children to point to `NULL`. * @param newKey The object to use as a key * @param newValue The templated data element that the constructed * node will hold. ...
The basic issue is that the return type is parsed in the global scope, and not in the scope of the method (due to the fact that it is before the method name and its scope specifier). So you need to explicitly scope it: AVLTree::Node* AVLTree::findParent(Node *&current, Node *& child ) {
69,610,082
69,610,741
How do I get accurate outputs when reading large amounts of data from a file?
I'm trying to use a for loop to read 100,000 int values from a file. I also want to add them up, find a min, and find a max. My code right now only reads correctly if I change the number of read values from 100,000 down to just 100. Even at 200 values, my code just skips data and doesn't give correct outputs. Can anyon...
As others have stated, your 1st loop is reading and discarding integers, and then your 2nd loop picks up where the 1st loop left off, rather than starting at the beginning of the file again. You should be using only 1 loop. You are also not initializing your sum and big variables before entering the loop that increment...
69,610,608
69,611,460
windows mingw32-make "no such file" error when installing opencv
I've been trying to build OpenCV-4.5.1 from source with CMake 3.22.0-rc1. When execute "mingw32-make", this problem below showed up. I guess something went wrong with the CMakeList but I'm not sure. I found that there's no such file named "thread.c.obj", so I tried to compile thread.c with gcc, but some reference error...
The error you get is from mingw32-make trying to run .bat files, which can't be be run by CreateProcess (which is internally used to execute programs), as it requires something like CMD /C to run. You could try using CMake flag -GNinja in combination with Ninja as build tool. This is also a lot faster. Another solution...
69,610,798
69,610,934
How to retain filesystem path while converting to string?
#include <iostream> #include <filesystem> namespace fs = std::filesystem; using namespace std; int main() { fs::path p = fs::current_path(); cout << p << endl; string p_string = p.string(); cout << p_string << endl; return 0; } When printing out 'p' the path is shown as this. "C:\\Users\\tp\\sourc...
From cppreference's page on operator<<(std::filesystem::path): Performs stream input or output on the path p. std::quoted is used so that spaces do not cause truncation when later read by stream input operator. So we'll get the same string by manually calling std::quoted: #include <iostream> #include <iomanip> #inclu...
69,611,248
69,611,277
What does someone mean when they write something to "gobble a newline"? C++
I am currently learning how to write a code that prompts the user to define how many players and rounds they want in a dice game, with the additional goal to output the results of both into a file. A couple of resources I have seen have suggested when defining the string variable, you want a secondary string for the so...
Many input streams have extra newline characters between inputs. "Gobble up a newline" is to get rid of those to get the correct output. For example: 5 //number of inputs //empty newline character 89 //first input value ... The dummy variable is used to store it since it is not of much use to store a newline character...
69,611,558
69,612,249
How does *node copy *next?
I understand how linked lists work but this particular code is tough to grasp for me. Its this leetcode problem (basically we are given address of a node which is to be deleted) whose solution can be implemented like the code snippet below: 1. class Solution { 2. public: 3. void deleteNode(ListNode* node) { ...
node->next is actually equivalent to (*node).next. So there's an implicit dereference there already. As for the copying, I assume you understand assignment between e.g. plain int variables? As in: int a = 5; int b = 10; a = b; It's quite natural that the value of b will be copied into a. Now lets do the same again, b...
69,611,696
69,611,882
hHow to fill remaining places with zeros?
#include <bits/stdc++.h> using namespace std; int main() { array<vector<int>,10>arr1; arr1[0].push_back(1); arr1[0].push_back(2); arr1[0].push_back(3); arr1[1].push_back(4); arr1[1].push_back(5); arr1[2].push_back(6); arr1[7].push_back(100); for(auto i:arr1) { for(auto j :i) cout<<j<<"...
You can do: array<std::vector<int>,10>arr1; for ( auto& vec : arr1 ) vec = std::vector<int>(10, 0); To fill all the vectors with 0s by default. But, you can no longer do push_back as it will insert at the 11th position. Second question: They are both equivalent ( static arrays holding pointers to dynamic arrays) ....
69,611,697
69,611,811
Divide without divide c++
There is a problem I am supposed to solve that is normally easy, but it has a catch. There are 2 types of candy. One type weighs m1 kg and is sold for s1 Euro. A second type weighs m2 kg and is sold for s2 Euro. All numbers are integers. The question is, which type of candy costs more per kg? The catch is, you can't us...
Compare X ≡ s1 * m2 with Y ≡ s2 * m1. If X > Y, then s1 / m1 > s2 / m2. No division is required to do the comparison. The caveat to this solution is that s1, s2, m1, and m2 should all have the same sign, and m1 and m2 should be non-zero. Let's assume all the values are positive integers (hence, greater than 0). Conseq...
69,611,945
69,613,196
C++ template argument deduction for pointers to overloaded member function
I'm currently working on a template function that deals with pointers to member functions. It originally looked like this: template <typename C, typename RT, typename... P> auto CreateTestSuite(RT(C::* pFunc)(P...)) {...} However, I soon found that if I try to pass to it a pointer to a const member function, the templ...
As your issue is just to select the right overload, you might write helpers: template <typename C, typename RT, typename... P> constexpr auto non_const_overload(RT (C::*pFunc)(P...)) { return pFunc; } template <typename C, typename RT, typename... P> constexpr auto const_overload(RT (C::*pFunc)(P...) const) { return p...
69,612,041
73,302,460
Simple and easy way to move visual studio vcxproj files from one folder to another
So I have a bunch of vcxproj files under the following folder E:. ├───vddproject │ └───scrproj │ └───pjrdir │ └───winsix │ └───Arithmetic.vcxproj There are bunch of vcxproj under winsix, I have taken one example here. The files for Arthmetic.vcxproj are stored under E:. ├───vddproject │...
Here is what you need to do. Remove the project Arithmetic from the sln Math from the solution explorer. Move the following files from winsix to your folder Idexter->Arithmetic Note : You don't need to move Arithmetic.vcxproj.user files as these are automatically created. Arithmetic.vcxproj Arithmetic.vcxproj.filter...
69,613,009
69,616,999
Is a float member guaranteed to be zero initialized with {} syntax?
In C++17, consider a case where S is a struct with a deleted default constructor and a float member, when S is initialized with empty braces, is the float member guaranteed by the standard to be zero-initialized? struct A { int x{}; }; struct S { S() = delete; A a; float b; }; int main() { auto s = S{}; /...
Because S is an aggregate, S{} will perform aggregate initialization. The rule in the standard about how members are initialized when there are no initializers in the list is basically what you cited: If the element has a default member initializer ([class.mem]), the element is initialized from that initializer. Othe...
69,613,399
69,613,553
Does the compiler really optimize to make these two functions the same assembly?
I plugged this into Godbolt and was pleasantly surprised that these two function calls a() and b() are equivalent under anything other than -O0 (using most major compilers): #include <cmath> struct A { int a,b,c; float bar() { return sqrt(a + b + c); } }; struct B { int a[3]; float bar() {...
This function: float a() { A a{55,67,12}; return a.bar(); } Has exactly the same observable behavior as this one: float a() { return sqrt(55+67+12); } The same is true for b(). Further, sqrt(55+67+12) == sqrt(134) == 11.5758369028. Binary representation of the IEEE-754 floating point value 11.5758369028 i...
69,613,809
69,614,033
how can i show Gaussian cube file with vtk?
I have a file with .cube format. I want show it with vtk as such as this image. how can i show this file with C++ vtk?
I stop working with VTK some years ago, but I think you're searching for a Gaussian Cube file reader. Some research leads here: https://vtk.org/doc/nightly/html/annotated.html In the provided link, you can find some official examples, in particular there are two classes that I think could help you: vtkGaussianCubeRead...
69,613,884
69,613,957
c++ char array returns some strange value
After inserting values in dynamic char array, trying to get first value from the top. Method gives me back ² value. Can you help me with understanding, what I am doing wrong? Here is main method: char* arr = new char[5](); arr[0] = 'h'; arr[1] = 'e'; arr[2] = 'l'; arr[3] = 'l'; char result = top...
In the first iteration of the loop, you access the array outside of its bounds, and the behaviour of the program is undefined. Note that your function doesn't handle the potential case where all elements are the null terminator character. In such case the function would end without returning a value and the behaviour o...
69,614,109
69,619,614
Why does C++23 string::resize_and_overwrite invoke operation as an rvalue?
In order to improve the performance of writing data into std::string, C++23 specially introduced resize_and_overwrite() for std::string. In [string.capacity], the standard describes it as follows: template<class Operation> constexpr void resize_and_overwrite(size_type n, Operation op); Let — o = size() before the ca...
op is only called once before it is destroyed, so calling it as an rvalue permits any && overload on it to reuse any resources it might hold. The callable object is morally an xvalue - it is "expiring" because it is destroyed immediately after the call. If you specifically designed your callable to only support calling...
69,614,204
69,614,290
Why is lambda not converted to function in this case?
I'm writing code with parameter packs and std::function. The goal is to be able to pass a function and a pack of parameters into a function, and be able to call the function of that pack (and do some other work). Here is the stripped down example of what I want: #include <functional> #include <iostream> template<typen...
The problem is template argument deduction for Args on the 1st function parameter f fails since implicit conversion (from lambda to std::function) won't be considered in the deduction. You can use std::type_identity (since C++20; it's quite easy to write one for pre-C++20) to exclude f from deduction. E.g. template<typ...
69,614,345
69,614,454
Child constructor uses grandparent constructor
I have the following class hierarchy with a virtual GrandParent and non-virtual Parent and Child: class GrandParent { protected: explicit GrandParent(const float &max_dur); virtual ~GrandParent() {} private: const float _max_dur; }; class Parent : public virtual GrandParent { public: explicit Parent(c...
From the faq: What special considerations do I need to know about when I inherit from a class that uses virtual inheritance? Initialization list of most-derived-class’s ctor directly invokes the virtual base class’s ctor. Because a virtual base class subobject occurs only once in an instance, there are special rules t...
69,614,745
69,614,887
Access to derived class members through a base class reference
considere a simle class stDeriv which inherits from stBase. I'am surprised to see that we cannot access to the stDeriv class members through a stBase reference. Below the basic example to illustrate my point : #include <fstream> // std::ifstream #include <iostream> // std::cout using namespace std; typedef struct st...
You cannot rebind references like you do. rBase already has a value and cannot be assigned to again. why doesn't C++ allow rebinding a reference? So just make a new reference: int main(int, char* []) { int iErr = 0; stBase aBase(0); stDeriv aDeriv(1); stDeriv& rDeriv = aDeriv; stBase& rBase = aBase;...
69,614,880
69,615,425
Is there any way that data can be inherited from one class to another?
I am trying to learn object oriented programming, and I got stuck at a problem. I have two class A and B. I am passing command line argument into class A, which then performs some computations and forms a 2d vector. (lets call the vector data) I want class B to inherit class A. So I was wondering is there any way, in w...
You seem to misunderstand how inheritance works, it is just not clear what you expected. The thing is: Members of a base class are always inherited. Their access can be limited, but they are still there. Consider this simplified example: #include <iostream> class A { public: int data = 42; ...
69,615,670
69,618,642
Convert numbers into letters and multiply the number by itself
Sample Input #2 8 5 12 12 15 23 15 18 12 4 Sample Output #2 helloworld 8:8-16-24-32-40-48-56-64 5:5-10-15-20-25 12:12-24-36-48-60-72-84-96-108-120-132-144 12:12-24-36-48-60-72-84-96-108-120-132-144 15:15-30-45-60-75-90-105-120-135-150-165-180-195-210-225 23:23-46-69-92-115-138-161-184-207-230-253-276-299-322-345...
#include<iostream> #include<iomanip> #include <iterator> using namespace std; char secretCode(char number) { if(number >= 1 && number <= 26) { return static_cast<char>('a' - 1 + number); } else if (number >= 27 && number <= 52) { return static_cast<char>('a' - 27 + number); }...
69,615,772
69,615,866
Make extern variable can't be accessed in specific files
So I have: foo.h #ifndef FOO_H #define FOO_H extern int bar; void change_bar_value(const int& value); #endif foo.cpp #include "foo.h" int bar = 10; void change_bar_value(const int& value) { bar = value; } and main.cpp #include "foo.h" int main() { bar = 20; change_bar_value(20); } So I want that yo...
"Don't make it extern" is the obvious answer, and the generally preferrable solution. If you desparately want something is globally readable but not writeable, alias it with a const reference. (And don't pass primitives by const reference - it is a pointless pessimization.) foo.h: extern const int& bar; void change_bar...
69,616,001
71,200,363
Input C++ Vector into C function
I have a std::vector<float> containing sound data. Without copying its data, I'd like to use this vector as input to the sonicChangeFloatSpeed function of the Sonic library. This method expects a float* as first argument and mutates the input array. After completion, the pointer in first argument would point to the res...
As I mentioned, I solved this problem by not using sonicChangeFloatSpeed at all, but the code within it. Before reading the results from the stream into vec, I do vec.resize(numSamples): sonicStream stream = sonicCreateStream(16000, 1); sonicSetSpeed(stream, speed); sonicSetPitch(stream, pitch); sonicSetVolume(stream, ...
69,616,145
69,616,197
My C++ program can't print out an entity's attribute
This is a simple C++ program that I made, I'm only using classes and constructors on this code. The problem here is, if I print out one of the entity's attributes, C++ would give me a runtime error where it won't print out the entity's height, weight, material or place. It just prints nothing. here's the code: #include...
You're assigning nothing at all, because you assign to your local variables. Either try: Monolith (int height, int weight, string material, string place){ this->height = height; this->weight = weight; this->material = material; this->place = place; } or this: Monolith (int height, int weight, string materi...
69,616,430
69,616,549
Can lambda() that never evaluates to a constant expression be a `constexpr`-function in C++?
Lambda's operator() is implicitly constexpr according to https://en.cppreference.com/w/cpp/language/lambda When this specifier (constexpr) is not present, the function call operator or any given operator template specialization will be constexpr anyway, if it happens to satisfy all constexpr function requirements And...
All three compilers do issue an error when you actually try to use the result of t() in a context that requires a constant expression. For example: auto l = []()->bool { throw 42; }; constexpr bool t() { return l(); } template <bool x> struct dummy {}; int main() { dummy< t() > d; // error: t() is not a constant...
69,616,631
69,616,690
Why I don't get any error (C-style casting)
char c{ 10 }; int* i = (int*)&c; *i = 1; // Run-Time Check Failure #2 - Stack around the variable 'c' was corrupted. But I don't get any error in this case char* c = new char{ 10 }; int* i = (int*)&c; *i = 1; //delete c; Why is it so?
With int* i = (int*)&c; you make i point to the variable c itself, not where c is actually pointing. Thus *i = 1 will change the value of the pointer variable c not the value of *c. If you want to get the same (or similar) behavior you should make i point to where c is pointing: int* i = (int*) c; As for why it does...
69,616,738
69,617,027
Allocator in create publisher ROS2
Based on ROS2 documentation there is a third argument called an allocator that can be used when creatinga publisher. How can this allocator be used ? Does it allocate memory for the publisher ? std::shared_ptr< PublisherT > rclcpp::node::Node::create_publisher ( const std::string & topic_name, const rmw_qos_pro...
The custom allocator will be used for all heap allocations within the context of the publisher. This is the same as how you would use a custom allocator with an std::vector as seen here. For ROS2, take the following example of a custom allocator. template<typename T> struct pointer_traits { using reference = T &; u...
69,616,858
69,616,920
Template member function syntax
I'm currently implementing containers in C++ and I have a question about the syntax used to declare member functions. I have a Vector_declaration.hpp file where I declare the vector class and all its components for instance: reference operator[](size_type n); Where reference is defined by typedef typename Allocator::re...
Here: template <typename T, typename Allocator> typename vector<T, Allocator>::reference vector<T, Allocator>::operator[](size_type n); The typename vector<T, Allocator>::reference is the return type of the method. Consider how it would look without templates: struct foo { using reference = int&; reference bar...
69,617,121
69,617,228
Lemires Nearly Divisionless Modulo Trick
In https://lemire.me/blog/2019/06/06/nearly-divisionless-random-integer-generation-on-various-systems/, Lemire uses -s % s to compute something which according to the paper is supposed to be 2^L % s. According to https://shufflesharding.com/posts/dissecting-lemire this should be equivalent, but I'm getting different re...
Unary negation on integers operates on every bit (two's complement and all that). So if you want to simulate 32 bit operations using uint64_t variables, you need to cast the value to 32 bits for that step: #include <iostream> int main() { uint64_t s = 1440000000; uint64_t k1 = (1ULL << 32ULL) % s; uint64_t k2 = ...
69,617,341
69,617,449
c++ Variadic boost fusion map alias template
Consider this snippet: #include <boost/fusion/container/map.hpp> #include <boost/fusion/include/pair.hpp> struct MsgA {}; struct MsgB {}; using MsgList = std::tuple<MsgA, MsgB>; template <typename Msg> class MsgSignal {}; template <typename... Args> using MsgSignals = boost::fusion::map<boost::fusion::pair<Args...
You can use template partial specialization to extract the types in std::tuple: template <typename Tuple> struct MsgSignalsImpl; template <typename... Args> struct MsgSignalsImpl<std::tuple<Args...>> { using type = boost::fusion::map<boost::fusion::pair<Args, MsgSignal<Args>>...>; }; template <typename Tuple> using...
69,617,421
69,617,594
Why use iter = lst.insert(iter, word) and not just lst.insert(iter, word)
I'm still learning about insert() on C++. Why use iter = here? list<string> lst; auto iter = lst.begin(); while (cin >> word) iter = lst.insert(iter, word); Why not like this? list<string> lst; auto iter = lst.begin(); while (cin >> word) lst.insert(iter, word); I'm confused because there is also this case, w...
The difference becomes immediately apparent when you look at the output of the following input: 1 2 3 A: #include <list> #include <iostream> using namespace std; int main() { std::list<std::string> st; auto iter = st.end(); std::string word; while (cin >> word) iter = st.insert(iter, word); ...
69,617,802
69,618,235
How to overwrite conan shared option inside my project?
I have a project with the following conan recipe: from conans import ConanFile, CMake class MyLibConan(ConanFile): name = "mylib" version = "1.16.0" generators = "cmake" settings = "os", "arch", "compiler", "build_type" options = {"shared": [True, False]} default_options = "shared=False" ex...
The obvious suggestion is fixing your server script, because your library can be built as shared and static. Another possibility is updating your server script to generate static and shared, not only one option. If in your company you need to maintain an internal script, I would suggest using Conan Package Tools instea...
69,617,908
69,623,018
How to call a x64 Assembly procedure in C#
I am working on a project and currently have the following structure: C# WPF project containing the User Interface as well as calls to external methods. C++ DLL project containing an algorithm. ASM DLL project containing an algorithm. For simplicity, let's assume the algorithm simply takes no parameters and returns t...
is calling ASM code actually possible directly in C#? Example of this with two projects, C# and assembly based DLL. Looks like you already know how to get a C++ based DLL working. The project names are the same as the directory names, xcs for C# and xcadll for the dll. I started with empty directories and created emp...
69,618,468
69,621,175
How can i set text size in wxWidgets?
Compiled application I want to make the Hello World text bigger, but i can't figure out how I tried using staticText1->SetSize(32), staticText1->SetSize(wxSize(32,32)) and replacing wxDefaultSize with wxSize(32, 32), but nothing works (I am not getting errors, it just doesnt change the text size) This is my current cod...
You need to change the font size and not the window size. The best way to do it is to change the size of the same font it already uses, e.g. window->SetFont(window->GetFont().Scale(1.5)), which would make the font 1.5 times bigger. The same approach can be used to make it bold, or italic etc.
69,618,469
69,635,732
C++/OpenGL Texture appearing Pixelated
Here is my code for generating the texture(MRE): glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if(readAlpha) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_U...
Your geometry shader does not make sense: First of all, you use the same data_in.TexCoords[0] for all 3 vertices of of the output triangle, which means that all fragments generated for this triangle will sample the exact same location of the texture, resulting in the exact same output color, so the "pixelated" structur...
69,618,549
69,618,824
Do C++ Objects (Standard Definition) persist in memory map files?
Question inspired by Dealing with large data binary files Link to Object Program (1) creates a memory-mapped file and writes some Objects (C++ Standard definition) to it, closes the file and exits. Program (2) maps the above file into memory and tries to access the Objects via reinterpret_cast. Is this legal by the Sta...
No, objects do not persist this way. C++ objects are defined primarily by their lifetime, which is scoped to the program. So if you want to recycle an object from raw storage, there has to be a brand new object in program (2) with its own lifetime. reinterpret_cast'ing memory does not create a new object, so that doesn...
69,619,660
69,629,318
How can I guarantee the position of data inside a separate linker section does not change when I extend it?
In an embedded C++ context, I have defined a separate linker section in flash memory, far away from the rest of the code/data, in which I store data that the user may modify at runtime. (EEPROM emulation, basically) I also have a custom device firmware updater, that's going to overwrite the read-only code/data in flash...
Several compilers and/or linkers order variables by some (to us users) unknown (hashing?) algorithm. If you rename a variable or add a variable, each of the variables might change its location. However, there is help, as the standard says in chapter 6.5.2.3 paragraph 6 (emphasis by me): One special guarantee is made i...
69,619,831
69,620,374
How to pass jthread stop_token to functor?
I'm trying to work with the new jthreads and have started a std::jthread where the operator() does get called, but I am unable to get it to stop. I want to create the thread by calling it as a function object. my_thrd = std::make_shared<std::jthread>(&Test::operator(), &test); If operater() of my Test class is written...
You can use std::bind to bind &test to &Test::operator(), then use std::placeholders::_1 to reserve a place for unbound std::stop_token: struct Test { void operator()(std::stop_token token) { using namespace std::literals; while (!token.stop_requested()) { std::cout << "Working ...\n" << std::flush; ...
69,620,024
69,620,052
Including constants without functions
I am making a c++ library and I want to include fcntl.h in the header (for the permission constants) But I have a function called open, the argument list contains classes that can be casted to the fcntl's open argument list types. That means when i use #include<fcntl.h> I am getting an ambiguous error. I want the libra...
is there a better solution? Use a namespace: namespace my_lib { int open(const char *pathname, int flags); } And to be clear, a library should always declare its functions/classes/constants/etc... in a namespace, not just as a means to fix a specific issue. This way, you avoid potential conflicts with other librar...
69,620,442
69,620,561
Why does my reference update the element array it is referencing?
Could anyone explain to me in layman's terms why my reference is updating the element array that it is referencing? I thought the whole point of a reference was to only reference a value. #include <iostream> int main() { int arr[4] = { 0,0,0,0 }; arr[0] = 1; int& reference = arr[0]; reference = 2; ...
In layman terms, as requested: References and pointers are basically the same thing, the main difference being that references cannot be null and simplified syntax when you work with them. Also, array variables are also pointers. arr is a pointer to the beginning of the array, arr[1] is the pointer to the second elemen...
69,620,861
69,620,912
Unable to create object from Main
I'm new to C++. This question might be easy, but I didn't find a proper answer to it after my Internet searches. I have a class with a public method to do some task. From the main() method, I'm trying to instantiate an object of my class to further call my method. I'm getting a compile-time error: MyClass: undeclared ...
You have to put the class definition before main() here, because it (the compiler) has to know the size of the object it is creating (instantiating). //class definition class MyClass { public: void MyMethod() { //some code } }; int main() { MyClass sln; sln.MyMethod(); } Check out the working ...
69,621,052
69,621,117
C++ nested try-catch catching the same exceptions - how should I rewrite this code?
I currently have code in C++ 14 that looks like this: try { // create objects, process input myObject obj; // may throw std::invalid_argument in constructor for (i = 0; i < n_files; i++) { try { process_file(); // may throw std::invalid_argument and std::runtime_error() ...
this code as is won't work from what I understand Yes, it will work just fine, for the scenario you have described. exceptions thrown in the outer try block would hit the inner catch statement first, as that is the first catch statement reachable in the code. That is not correct. It is not about the order in code, ...
69,621,111
69,621,340
Are mutex locks necessary when modifying values?
I have an unordered_map and I'm using mutex locks for emplace and delete, find operations, but I don't use a mutex when modifying map's elements, because I don't see any point. but I'm curious whether I'm wrong in this case. Should I use one when modifying element value? std::unordred_map<std::string, Connection> conne...
Consider what can happen when you have one thread reading from the map and the other one writing to it: Thread A starts executing the command string myLocalStr = element->second.foo; As part of the above, the std::string copy-constructor starts executing: it stores foo's character-buffer-pointer into a register, and ...
69,621,131
69,621,525
Find a sum of all positive matrix elements that located before of the largest positive element
here is what i tried before: //finding maximum for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (arr[i][j] > max) { max = arr[i][j]; imax = i; jmax = j; } } } //finding a sum for (in...
Let's think step by step. Assuming, imax is the row number and jmax is the column number of the maximum elements present in the matrix. Row selection procedure: So, to accomplish our object, we will traverse row which is <= imax. That means, we'll consider the value of the current row as our answer only if current row ...
69,621,633
69,621,884
Microsoft Visual Studio - Default/Auto apply settings?
How do I auto apply certain settings? For example: In this example, I want these settings to stick and not have to reapply them, but if I make a new project I have to constantly reapply them. How do I make them stay in those specific settings?
You can create your own template for the wizard, or just modify an existing one. Here are the steps: https://learn.microsoft.com/en-us/visualstudio/ide/how-to-update-existing-templates?view=vs-2019
69,621,893
69,636,868
What happens when the encryption algorithm receives an unsupported key size?
I try to build an encryption program, and I use AES (256/192/128) from realisation I took from GitHub there is an exception if the key is not of these sizes. But I want to use the key as a password, in KeePass (they also encrypt with this algorithm) we can create passwords of different sizes. What should I do? I must a...
The accepted answer is not correct, misleading, and insecure! password-based key derivation (PBKDF), a small intro Normally, the key for AES must be generated uniformly randomly. It is hard for humans to memorize random keys, so we use passwords and derive keys from them. The correct way to convert a password into a ke...
69,621,960
69,622,573
Why does this nostdlib C++ code segfault when I call a function with a thread local variable? But not with a global var or when I access members?
Assembly included. This weekend I tried to get my own small library running without any C libs and the thread local stuff is giving me problems. Below you can see I created a struct called Try1 (because it's my first attempt!) If I set the thread local variable and use it, the code seems to execute fine. If I call a co...
The ABI requires that fs:0 contains a pointer with the absolute address of the thread-local storage block, i.e. the value of fsbase. The compiler needs access to this address to evaluate expressions like &t1, which here it needs in order to compute the this pointer to be passed to Try1::Get(). It's tricky to recover t...
69,622,589
69,627,172
move semantics 2d vector in C++
I have a question on C++ move semantics in 2D vector (or a vector of vectors). It comes from a problem of dynamic programing. For simplicity, I just take a simplified version as the example. //suppose I need to maintain a 2D vector of int with size 5 for the result. vector<vector<int>> result = vector<vector<int>>(5);...
Yes, because result is not '2D' vector, it's simply 1-D vector of vectors.
69,622,953
69,623,102
CMake include header file in different directory
So I have a directory that's formatted as follows: Project: - src - a.cpp - b.cpp - c.cpp - include - h.cpp - h.hpp How would I get CMake to include h.hpp in the files in the source folder? I tried doing include_directories(include) but CMake is still unable to find the file. I also tried changin...
You should add h.cpp as a source for each executable that uses functions from h.hpp: add_executable(a ${CMAKE_CURRENT_SOURCE_DIR}/src/a.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp) add_executable(b ${CMAKE_CURRENT_SOURCE_DIR}/src/b.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp) add_executable(c ${CMAKE_CURRENT_SOURCE...
69,623,199
69,623,227
Problem in memory allocation of char variable in C++, through visual studio debbuger
char is a type that have one byte in C++, in a way that we can use it as signed or unsigned, changing the values it can allocate. I'm new using debugger in Visual Studio and also in reading about memory. I'm using the following code: int main() { signed char a = 170; signed char* b = &a; } the range of a varia...
The 170 literal is an int represented by 0x000000AA. When you convert that into a single byte signed char, it simply truncates the bytes, so you wind up with 0xAA, which happens to be -86 in twos-complement notation.
69,623,544
69,667,431
Cmake: How to link multiple libraries?
I am using CMake to define the compilation of a C++ executable. The goal is to use 2 third-party libraries, Open3D and OpenCV. I am able to include one of the two with target_link_libraries, but including both results in OpenCV functions not being found. This is my current CMakeLists.txt minimum_required(VERSION 3.20) ...
The problem was solved by finding this Github issue: https://github.com/isl-org/Open3D/issues/2286 By using specific build flags when building Open3D, the libraries could both be linked correctly and simultaneously with the target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}) command. The build commands w...
69,623,714
69,623,794
Dynamic Array - Problem with memory management
I'm working on the dynamic array. Related part of code of the array class: #pragma once #include <iostream> template <class T> class Darray { private: T* dataArray; int a_size = 0; int a_capacity = 0; double expandFactor = 1.5; private: void memLoc(int n_capacity) { T* newArray = new ...
There are a couple of mistakes in your code. In memLoc(), you are destroying the new array you just created. You need to instead destroy the old array that is being replaced. The statement dataArray = newArray; is just assigning a pointer to another pointer. dataArray is pointing at the previous array, and newArray p...
69,624,502
69,624,536
Segmentation fault when initialize an array after create object of template class
Below is my linked list template class and i define it in "LinkedListTemplate.h": template<typename T> class Node{ T data; Node<T> *next; public : void setData(T new_data){ data = new_data; } Node<T>* &getNext(){ return next; } T getData(){ return data; } }; template<typ...
template<typename T> class LinkedList{ private : Node<T> **head_ref; public : LinkedList(){ (*head_ref) = NULL; // HERE } What do you think head_ref points to in the line that I marked? You never initialize head_ref. So when you do (*head_ref) you are dereferencing a pointer that doesn't point to a...
69,624,688
69,624,876
How do you generate subarrays of an array with specific number of elements and then store it in another array?
What I need to do is to create subarrays of an existing array and the subarray should have a given number of elements. For eg. if I have the array [1,2,3,4] and I need to generate subarrays of it with exactly three elements, I would want the a separate 2-d array to include the following arrays: [1,2,3] [1,2,4] [1,3,4] ...
You can do it by first calculating how many combinations there are by picking 3 elements in a group of 4 and what these combinations look like. Then you can use these combinations to pick elements from your input and create output like this : #include <cassert> #include <algorithm> #include <iostream> #include <numeric...
69,625,197
69,625,276
Can you access the current iterator from a function used by the transform function in c++?
Can you access the current iterator from a function used by the transform function in c++ so that you can reference previous and latter values? I want to use the transform function to iterate through a vector, performing operations on the vector that rely on values before and after the current value. For example, say I...
Clearly the tool std::transform simply doesn't give you a way to do that: it either takes a unary predicate to be applied to individual elements of of one collection, or a binary predicate to be applied to corresponding elements of two collections. But the point is that, from the functional programming perspective, wha...
69,625,262
69,625,289
Loop isn't printing expected results
I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector. #include <iostream> #include <vector> using namespace std; int main(){ // Declaring vectors vector...
You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop: int i{0}; for(auto item: items){ cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl; ++i; cout << "--------------------" << endl; }
69,625,541
69,625,919
Why traversal on modified 'std::vector' more slowly than unmodified 'std::vector'?
This is the code that shows the access behavior of std::vector slows down when std::vector is sorted by std::sort(). #include <cstdio> #include <chrono> #include <random> #include <cstdlib> #include <cstring> #include <algorithm> constexpr auto NUM_KEYS(24000000); constexpr auto CLOCK_MILI(CLOCKS_PER_SEC/1000); conste...
The selection of the vector name is accidentally quite revealing. Because the vector is a vector of pointers, it behaves similarly to a list, causing data that was originally allocated in (probably) linear order to be accessed after sorting in random order. If in contrast all the data you access is contained within the...
69,625,589
69,625,669
Operator Overloading C++ for + operator
I am currently learning how to do operator overloading in C++, i found some codes online that works when it is run below. class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) { real = r; imag = i; } // This is automatically called when '+' is used with // between two Comp...
Below is the corrected example. First, you were getting the error because inside operator+ you were default constructing an object of Chicken type but your class doesn't have any default constructor. The solution is to add the default constructor. #include <iostream> class Chicken{ //needed for cout<<W; to work ...
69,625,818
69,625,844
Question about constructors & memory leak
I was testing with constructors and destructors, and I want to see if I can pass an object to a function without declaring it first, like this example: #include<iostream> #include<stdlib.h> using namespace std; class car { public: string name; int num; public: car(string a, int n) { cout << "C...
Would that new cause a memory leak? Yes, it is causing the memory leak. Whatever you newed should be deleteed after wards(Manual memory management). why didn't my user-defined destructor get called? Because the object has not been deleted and hence not been destructed. You should be doing void display(car* p) { ...
69,626,176
69,632,639
Creating TCanvas to measure text width
I want to measure text width of a TButton so that I can resize it when the text changes. If the button uses ParentFont, I can use the form Canvas to get the width: int GetButtonTextWidth(TForm* form, TButton* btn) { const int base = form->Canvas->TextWidth(btn->Caption); const int margin = 16; return base +...
The VCL has a TControlCanvas class for associating a Canvas with a UI control. int GetButtonTextWidth(TButton* btn) { std::unique_ptr<TControlCanvas> canvas(new TControlCanvas); canvas->Control = btn; canvas->Font = btn->Font; const int base = canvas->TextWidth(btn->Caption); const int margin = 16; ...
69,626,335
70,359,263
How to implement Cryptarithmetic using Constraint Satisfaction in C++
I'll start by explaining what a cryptarithmetic problem is, through an example: T W O + T W O F O U R We have to assign a digit [0-9] to each letter such that no two letters share the same digit and it satisfies the above equation. One solution to the above problem is: 7 6 5 + 7 6 5 1 5 3 0 There a...
Here is how I solved it using backtracking My approach here was to smartly brute force it, I recursively assign every possible value [0-9] to each letter and check if there is any contradiction. Contradictions can be one of the following: Two or more letters end up having the same value. Sum of letters don't match the...
69,626,935
69,660,384
Error building Qt6 where to find error log?
I'm trying to build Qt 6.2 from sources with VS2019 under Win10. I followed the steps described in https://doc.qt.io/qt-6/windows-building.html: > set QTDIR=C:\dev\qt6\qt-everywhere-src-6.2.0 > cd %QTDIR% > set PATH=%QTDIR%\qtbase\bin;%PATH% > set PATH=C:\dev\qt6\Python39;%PATH% > set PATH=C:\dev\qt6\perl\perl\bin;%PAT...
When building in parallel Ninja does not stop output just after an error, so an error description can reside far before the log end. Besides, if your console window buffer size is small, an error description can be completely re-written by a later output. So, you can: Increase console buffer Build Search (CTRL+F) for ...
69,626,953
69,630,163
Fix warning: 'Foo::fooObj1' should be initialized in the member initialization list [-Weffc++]
foo.h #ifndef FOO_H #define FOO_H class Foo { int fooObj1; bool fooObj2; public: Foo(int input1); }; #endif foo.cpp #include "foo.h" Foo::Foo(int input1) { fooObj1 = input1; // some code logic to decide the value of fooObj2 (an example) // so I can't really do member initialization list. ...
Two solutions to get rid of the warning. Solution 1 Make some static method, say CalculateFooObj2InitialValue, and use it in member initialization list. Foo::Foo(int input1): fooObj1(input1), fooObj2(CalculateFooObj2InitialValue(input1)) { ... } Solution 2 Initialize fooObj2 with a default, yet not quite meani...
69,627,207
69,642,459
Boost.Test - How to write a test that doesn't run automatically
A project I am working on uses continuous integration (CI) system that automatically builds and runs all test suites. Auto tests are run without any command line arguments. I would like to add long running tests into existing suites and I don't want those test to be trigger by CI. What is the proper way to add tests th...
See Enabling or disabling test unit execution. Essentially, BOOST_AUTO_TEST_CASE(test1, * boost::unit_test::disabled()) { ... } If you run without parameters, it will not execute. With --run_test=test1 or --run_test=*, it still will execute.
69,627,248
69,627,339
takes one float value and immediately ends the program in template c++
okay so I have a question where im required to take user input of two int or float and then find the maximum and minimum of those two numbers. my if loop for int works fine, but for the float , it takes one float value and immediately ends the program. can anyone help me with this error? here's my code: #include <...
In if (opt == 'f' || opt == 'F') you declared numbers as int, not as float.
69,627,288
69,627,407
Earliest support of __alignof__ in GCC
I need a portable way to determine alignment requirements of a structure, where portability includes legacy versions of GCC. Parts of project are stuck with embedded platforms supporting pre-C++11 standard only, as early as GCC v.3.6. There is a non-ISO __alignof__ (a macro? a function?) analog of C++11 operator aligno...
The oldest version of GCC with documentation available online at gcc.gnu.org is 2.95.3. That version does support __alignof__ extension.
69,627,667
69,628,077
Skip function params calculation if first param less than threshold
I have a function like this: void WriteLog(int severity, ...); And it is used in a next way: WriteLog(2, "%d\n", SomeHugeCalculations()); But in case the application is configured to write logs only with severity > 2, execution of SomeHugeCalculations() is redundant. I think it can be solved by wrapping it into a mac...
The approach with macro can be ported C but problematic in form you did it. Consider this code: if ( logging ) WRITE_LOG(1, "Starting program"); else printf("Hello world!"); Non-isolated if-statement in macro causes "Hello world!" being printed if logging is true and if 1 is less than threshold because e...
69,627,728
69,637,366
OpenSSL 3.0.0 include files difference official release conan vs github
I'm building an app for both Windows, Linux and Android in c++. As with many third party dependencies, the windows and linux binaries are to be found on conan (which I use for dep management) but Android is not. This is usually not a big issue, building one extra library from source. However for OpenSSL I have the susp...
For the version you are downloading it looks like it is 3.0.0-beta1, while ConanCenter packages 3.0.0. Indeed, the beta version doesn't define CMP_R_MISSING_CERTID while the released one does. Maybe it is just a version mismatch? The diff is huge https://github.com/openssl/openssl/compare/openssl-3.0.0-beta1...openssl-...
69,628,131
69,628,227
-Wundef does not warn about an undefined symbol in front of #ifdef
Please consider the following code: // program.cpp #include <iostream> int main() { #ifdef LINUX std::cout << "Linux\n"; #elif MAC std::cout << "Mac\n"; #elif WINDOWS std::cout << "Windows\n"; #elif BSD std::cout << "BSD\n"; #else std::cout << "Something else\n"; #endif return 0; } If I compi...
The reason is that your preprocessor code asks if LINUX is defined. But for MAC, WINDOWS and BSD you don’t bother checking whether the symbol is defined; instead, your code assumes it is defined and asks for its value. Change your code to use #elif defined(…) instead of #elif … to fix the warning.
69,628,241
69,632,024
Where can I put my SQLite database in my QT application if I can't put it in my resources?
Recently I was trying to put a SQLite database into a QT 5 application I'm writing. I want it to be universally accessible - that is on all systems regardless of where it's installed. I put it as a resource then found out that evidently you can't put databases in resources as the string for the database path passed t...
For such purposes Qt provides a list of QStandardPaths functions that return platform specific standard paths, such as a path to desktop, temp directory etc. For your particular case you might put your database in the directory that corresponds to the QStandardPaths::AppDataLocation key.
69,628,509
69,628,642
Initializing integer with leading zeroes gives unexpected result (C++)
Problem summary Assume that for some reason one tries to store the integer 31 as int num = 0031; If I print out num I get 25 instead. If I use cin however, the number stored is indeed 31. You can verify this by running the following code and type 0031 when prompted. Code #include <iostream> using namespace std; int m...
For integer literals in C++ see eg here: https://en.cppreference.com/w/cpp/language/integer_literal. Yes, 0031 is an octal integer literal. To get expected output from the second version of your code you can use the std::oct io-manipulator: int num; cout << "Insert num: "; cin >> std::oct >> num; cout << "Input was: " ...
69,629,967
69,759,857
C++17 PMR:: Set number of blocks and their size in a unsynchronized_pool_resource
Is any rule for setting in the most effective way the number of blocks in a chunk (max_blocks_per_chunk) and the largest required block (largest_required_pool_block), in a unsynchronized_pool_resource? How to avoid unnecessary memory allocations? For example have a look in this demo. How to reduce the number of all...
Pooled allocators function on a memory waste vs upstream allocator calls trade-off. Reducing one will almost always increase the other and vice-versa. On top of that, one of the primary reason behind their use (in my experience, at least) is to limit or outright eliminate memory fragmentation for long-running processes...
69,630,292
69,632,567
Why is this code printing aa0 as an element in set although aa is not a substring of ab?
strong text #include <iostream> #include<set> #include <string> #include <string_view> #include <boost/algorithm/string.hpp> using std::string; using std::cout; using std::cin; using std::endl; int main() { long int t; cin>>t; while(t--) { string s1,s2,x,a,b,f; cin>>s1>>s2>>x; ...
I cleaned up your main function a little and removed boost usage (since you don't really need it here). I've also removed your namespace declarations as that is a bad idea. Lastly, I replaced your boost usage with a simple string::find. You can find the live example here. The output is : 4 0b a0 ab The updated main()...
69,630,735
69,630,865
Why does compiler treat class as abstract?
I tried to compile the program, but compiler treats ParameterExpr class as abstract. I did not work with multiple inheritance and I thought that it should be work (because get_type was actually implemented in Expr class) class IMetaExpression { public: virtual int get_type(void) = 0; virtual ~IMetaExpression(){...
I believe this is an issue called the diamond problem. https://www.geeksforgeeks.org/multiple-inheritance-in-c/ This is where two classes inherit fully or partially from a base class, which then also has a child class inheriting both of these classes. Creating a diamond shape. The solution to this is adding virtual to ...
69,630,902
69,631,175
Microsoft Visual Studio - Why am I getting this error?
I am so confused what is causing this error code, can anyone point out what is wrong? #include <iostream> main() { int x; std::cin >> x; std::cout << "Answer is " << x + x << '\n'; return 0; }
You missed function type specifier. It should be like this int main() { //... }
69,631,475
69,632,184
Can't get an item from tableWidget in QT
I have the function like this below, and global QVector<pid_t> pid; in the header file which elements are Linux process ids. But when I'm trying to push the button "priority" - programm unexpectedly finishes. Due to qDebugs I've realized that function interrupts after if statement. And I can not understand the matter o...
Not sure if this is your problem, but if ui->tableWidget->item(curI,1) doesn't exist (or is null), then calling ->text() on it will cause a crash. You might need to check if it exists first: void MainWindow::on_priority_clicked() { int curI = ui->tableWidget->currentRow(); int prio = ui->prioritySpi...
69,631,754
69,632,315
How to avoid bitwise operations outside the width of the data type in c++
For sake of experiment lets have a function that takes in a bitmask and offset and returns the mask shifted by offset. What would be a performance friendly way to determine if the operation will not shift any parts of the bitmask past the width of the data type? This is what I've tried so far, but maybe there is more o...
Not sure would this be faster, but you can check whether before and end value have same number of bits set uint16_t TestFunc(uint16_t offset, uint16_t mask) { if (offset >= std::numeric_limits<uint16_t>::digits) throw "Offset outside bounds (Possible Undefined Behavior)"; uint16_t result = mask << ...
69,632,040
69,642,848
My program prints the output occasionally although it is correctly compiled?
My program here is to randomly assign the variables (number1, number2, number3, number4) to a number stored in vector <int> number. I want to make sure each number will appear only 1 time Here is my code : #include <iostream> #include <vector> #include <random> #include <ctime> using namespace std; int main() { sr...
I want to make sure each number will appear only 1 time Rather than picking an index, you can shuffle the selection. #include <iostream> #include <vector> #include <random> int main() { std::vector<int> number = { 5, 6, 7, 8 }; std::shuffle(number.begin(), number.end(), std::random_device{}); std::cout <...
69,632,042
69,632,112
not getting same output via user defined function
I was trying something in Cpp, but not getting same output when I used the same thing in a user defined function CODE #include <iostream> using namespace std; int sum(int x, float y){ return (x / y); } int main(){ int a; float b, c; a = 12; b = 5; c = a / b; cout << sum(12, 5) << endl; c...
The return value of sum is int. #include <iostream> using namespace std; int sum(int x, float y){ return (x / y); //<< this is an int } int main(){ int a; float b, c; a = 12; b = 5; c = a / b; << this is a float cout << sum(12, 5) << endl; //...