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 |
|---|---|---|---|---|
71,888,354 | 71,888,427 | Why don't we have to declare static functions the same way we need to declare static variables in c++? | Consider the following struct:
struct Toto {
static int a;
static void Print() {
std::cout << a;
}
};
And the following main function using the struct in the same cpp file (main.cpp):
int main()
{
Toto::Print();
}
Building this gives the following error:
Error LNK2001 unresolved external sy... | Static member functions are ordinary functions at the assembly level. The difference is only the hidden pointer 'this' that does not exist in them. They are basically global functions that exist like any other non static or non member (and not inline) function within the C++scope of a class name. Function scopes are C+... |
71,888,462 | 71,892,261 | Doxygen: document a class in the cpp file with separate source and header directories while using macros to define namespaces | I'm trying to document a library with the following files:
include/mylib/mylib_global.h
include/mylib/SomeClass.h
source/SomeClass.cpp
Doxyfile
include/mylib/mylib_global.h:
#pragma once
#define MYLIB_NAMESPACE_BEGIN namespace mylibns {
#define MYLIB_NAMESPACE_END }
include/mylib/SomeClass.h:
#pragma once
#include ... | In the file source/SomeClass.cpp you have:
#include "mylib/SomeClass.h"
but the file SomeClass.h is located in include/mylib so you have to tell doxygen where to find the include file. This can be done by means of the setting:
INCLUDE_PATH = include
(analogous what you probably have done for the compiler with the set... |
71,889,509 | 71,892,076 | How do I show the function parameter names in function calls (not as tooltips but actually written) or declarations | In the Image a good example is the InitAbilityActor info function call or the Binds declaration. For the info you'll see "InOwnerActor: this", so the "InOwnerActor" label placed there is what I'm asking about.
I was watching an Unreal Engine tutorial and saw the author casually doing this, and I didn't know that it exi... | The screenshot is most likely showing the inlay hints feature of the Resharper C++ addin.
I am not aware of any other readily available addin or built-in option that allows this for C++. Note that Visual Studio supports it out-of-the-box for C# and Visual Basic since VS 2019 v16.8, but not for C++.
EDIT: As noted in th... |
71,889,512 | 71,889,861 | Is there a shortcut to write a function with the same definition but different prototypes? | I have a method of a class which basically looks like this:
void MyClass::method() {
// Here I'm just doing something with parameters which are class attributes
parameter_3 = parameter_1 + parameter_2
}
I need another method which would have exactly the same body, but now I want the parameters to be passed in ... |
I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call:
This can be solved using delegation. Simply call one overload from the other. Example:
void MyClass::method(type1_t parameter_1, type2_t parameter_2) {
parameter_3 = parameter_1 + pa... |
71,890,075 | 71,891,337 | Difference between passing value in function by int ** a and int & a | Is there any difference if i pass int **a in any function and at same place i pass int& a, will both create any difference?.
Ex
Bool issafe(int**arr, intx, int y)
Bool issafe(int& arr, intx, int y)
| There is a lot of difference between the '*' notation and '&' notation.
Let us have a look at what both mean, in a general sense and little bit of technical detail.
Reference Operator (&)
&x simply means Address of x. It will be a an address value, often represented in hexadecimal notation.
It is often used to pass by ... |
71,890,241 | 71,890,682 | Restoring a C++ stream's exception mask for caller | I am writing a C++ function that takes a std::istream as an argument and reads from it to decode an image. When decoding the image, I want the stream to throw exceptions if some error occurs during reading. That way, I don't have to intersperse checking the error flags with the rest of my decoding logic, making my code... | If the caller doesn't want stream exceptions, the old mask will not enable exceptions, so the restoration of the old mask will not throw any exception. Not a problem.
If the caller does want stream exceptions, then the restoration will throw an exception if the stream state matches what the caller wants an exception f... |
71,890,413 | 71,891,017 | How to understand "well formed when treated as an unevaluated operand" | As per the document, which says that[emphasis mine]:
template <class Fn, class... ArgTypes>
struct is_invocable;
Determines whether Fn can be invoked with the arguments ArgTypes.... Formally, determines whether
INVOKE(declval<Fn>(), declval<ArgTypes>()...) is well formed when
treated as an unevaluated operand, where... |
How to understand the statement in bold? What's "an unevaluated
operand"?
An unevaluated operand is an operand that is not evaluated.
Maybe, a simple example helps to fully understand this matter.
void g(auto) requires false;
void f(auto x) { g(x); }
static_assert(is_invocable_v<decltype(f<int>), int>);
f(0); // i... |
71,890,415 | 71,890,468 | Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) on vector insert | I am trying to insert an element into a vector using the .insert(<#const_iterator __position#>, <#const_reference __x#>)
This is my code:
hpp:
typedef int elementType;
class Heap{
private:
std::vector<elementType> myVecrtor;
int mySize = 1; //The minimum size is 1 since the first element is a dummy.
publi... | typename std::vector<elementType>::iterator it;
This statement declares a vector iterator. As you can see here, it is completely uninitalized. It is not initialized to anything.
for(int i = 0; i <= mySize; i++){
it++;
}
And this sequence increments the iterator some unspecified number of times. Since ... |
71,890,509 | 71,890,527 | Why does creating an object in a function and returning it call copy construct and move assignment operator? | #include <iostream>
class MyClass
{
public:
MyClass() = default;
MyClass& operator=(const MyClass& other) { std::cout << "copy\n"; i = other.i; return *this; }
MyClass& operator=(MyClass&& other) noexcept { std::cout << "Move\n"; i = other.i; return *this; }
MyClass(const MyClass& other) { std::cout <... |
I can understand that the contents of local variable c gets moved
This is incorrect. The declared class does not have a move constructor, so it cannot be moved, only copied into the caller's context. Which is what happens. That's step 1. Step 2 invokes the move-assignment operator, in the caller's context, to move th... |
71,890,570 | 71,890,582 | Why is my pow function returning 0 when it's being called as a variable? | I'm new to coding and have been learning on youtube and one of the functions im learning is the pow function. When i call the function in a cout directly, it outputs the correct value, but when i use a variable to call it, it outputs 0 as the value. Am i missing a step in the declaration of the function?
#include <iost... | Call double power = pow(base, exponent); after base, exponent are assigned values
cin >> exponent;
double power = pow(base, exponent);
cout << power << endl;
|
71,890,603 | 71,890,741 | How do I redirect stderr to /dev/null in C++? | #include <cstddef>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//read the lines from the piped file using cin
string response;
int i = 0;
while (getline(cin, response)) {
//if the response is empty, stop
if (response.empty()) {
... | Besides the excellent commentary above, it is pretty easy to make a “null” streambuf sink in C++.
#include <iostream>
struct null_streambuf: public std::streambuf
{
using int_type = std::streambuf::int_type;
using traits = std::streambuf::traits_type;
virtual int_type overflow( int_type value ) override
{
... |
71,891,002 | 71,891,075 | Template instances with different return types | As per this document, which says that[emphasis mine]:
The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time erro... | In the first snippet, you're providing two specializations of the more general primary function template foo<T>. In particular, you have provided specializations for T=int and T=double meaning we'll have foo<int> and foo<double> which are different from each other.
So in the 1st snippet there is no function overloading... |
71,891,113 | 71,891,153 | prefix operator behaviour in c++ when used multiple times in a statement | I am not able to understand prefix operator behaviour in scenario when it is used multiple times in a statement .
Here is an example code to illustrate my problem
#include<iostream>
using namespace std;
int main()
{ int a=2,adup=2;
int b = (++a) * (++a);
cout<<endl<<"square of "<<a<<" is "<<b<<endl;//i get 1... | Earlier iterations of C++ (and C for that matter) had the concept of sequence points, where it was guaranteed all previous "things" (like the i++ side effect of evaluating that expression) would have completed.
This was replaced at some point with more tightly described "sequencing" along the lines of:
if A is sequenc... |
71,891,197 | 71,891,270 | c++ type trait to detect if any function argument is reference | I need a type trait to detect if any of the function parameters of a template argument is a reference.
This code is working, the trait is "is_any_param_reference" and the static_assert is trigged the signature of foo is changed form void foo( std::string s, int i) to void foo( std::string& s, int i) (first parameter co... | template<typename T> struct is_any_param_reference :
is_any_param_reference<decltype(&T::operator())>{};
template<typename R, typename...Args>
struct is_any_param_reference<R(*)(Args...)>: any_is_reference<Args...>{};
template<typename T, typename R, typename...Args>
struct is_any_param_reference<R(T::*)(Args...)... |
71,891,633 | 71,892,779 | In C++ why is it when I reassign a reference variable to a different reference variable it creates a copy of that variable instead? | struct configfs
{
int & foo;
configfs(int & foo_) : foo(foo_) {}
void set_foo(int & foo_)
{
foo = foo_;
}
};
int main() {
int a = 1;
configfs conf(a);
a = 3;
std::cout << conf.foo; // 3
std::cout << a; // 3
int b = 2;
conf.set_foo(b);
b = 9;
std:... | When you wrote:
conf.set_foo(b);
The following things happen:
Member function set_foo is called on the object conf.
Moreover, the reference parameter named foo_ is bound the the argument named b. That is, b is passed by reference.
Next, the statement foo = foo_; is encountered. This is an assigment statement and no... |
71,891,653 | 71,891,685 | Copy lambda which captures moved object | Why this code snippet does not compile?
#include <functional>
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> uniq_ptr(new int{6});
auto foo_a = [&uniq_ptr]{std::cout << *uniq_ptr << std::endl;};
std::bind(foo_a)(); //works
foo_a(); //works
auto foo_b = [up = std... | [up = std::move(uniq_ptr)] just moves uniq_ptr to a member variable of the lambda.
std::bind will internally construct a copy of foo_b. Since foo_b contains a unique_ptr that is not copyable, foo_b itself is not copyable.
You should move foo_b into std::bind:
std::bind(std::move(foo_b));
Or move foo_b into foo_b1
auto... |
71,891,761 | 71,892,785 | what is the difference between vector.push_back() and inserting element like Vector[index]? | class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
vector<int> ans(2*n);
for(int i=0;i<2*n;i++)
{
if(i<n)
{
ans.push_back(nums[i]);
}
else
{
a... | When you create the vector you have specified a size already (usually not done with vectors) so your vector already filled with ints that have been set to 0. So when you use ans[i] = nums[i]; you are simply editing one of the already existing elements stored in the vector.
Usually when you create a vector you create it... |
71,892,458 | 71,892,512 | static class member not recognised but only for new versions of C++ compile | The static class member static_member not recognised in the following code.
However, it works on older versions of the compiler. The compiler I use is based on clang.
class my_class {
public:
static int static_member;
};
int main() {
my_class::static_member = 0;
}
To reproduce the error, save above file as c1... | From static data member's definition's documentation:
The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared.
So we have to first provide an out-of class definition for the static data member a... |
71,892,557 | 71,910,614 | WHY Qt reports **_resource_res.o Error 1? | I was using Qt Creator on my Windows11 virtual machine,and I cloned my team's repository from github.I did no changes to it at all, and when I tried to build it reports error.
I asked my teammates to try building it, and they all finished the build without any problem. Confusingly I uninstalled the Qt and install it ag... | I have solved it by myself. I had a missing resource file: "logo.ico". It seems that my teammates forget to upload that image, so it can be built on their machine, but mine failed. :/
Besides, I moved the file from USB device to the desktop, but I think that's not the point. Anyway, at least one of these works.
|
71,892,807 | 71,893,041 | "no matching function for call to" when having a function pointer with template arguments as a template argument | I'm writing a template wrapper function that can be applied to a functions with different number/types of arguments.
I have some code that works but I'm trying to change more arguments into template parameters.
The working code:
#include <iostream>
int func0(bool b) { return b ? 1 : 2; }
//There is a few more funcX...... | This doesn't work because a pack parameter (the one including ...) consumes all remaining arguments. All arguments following it can't be specified explicitly and must be deduced.
Normally you write such wrappers like this:
template <typename F, typename ...P>
int wrapper(F &&func, P &&... params)
{
return std::forw... |
71,893,029 | 71,893,129 | How can I assign the integers in an input like 1.2.3 to variables in C++? | Here is an example of what I mean.
Input: 10.20.50
a = 10
b = 20
c = 50
| you will need to store the input in a string or char[] and then iterate over the string or char[] and write some code that will identify the separate parts of the input and convert them to ints using stoi().
this would work but just an example (and i think it will not print the final number unless the input is ended wi... |
71,893,273 | 71,893,321 | First input number turns 0 after the executing the codes | I'm writing a program to generate a line equation using given slope and y-intercept, below are the codes i extracted from my program:
int m,c;
cout<<"m >>";
cin>>m;
cout<<endl;
cout<<"c >>";
cin>>c;
cout<<endl;
if (m=0){
cout<<"y= "<<c;
}
e... | You are setting m to 0 in the first if check. Should be using == not =.
|
71,893,308 | 71,893,684 | MinGW undefined reference libcurl | So i have written an app in c++ to download mp3s from the web using a list.
It uses libcurl to download them.
I am on linux. Compiling with
g++ main.cpp -lcurl -o word2mp3
works fine.
I need an windows executable, but running
x86_64-w64-mingw32-g++ main.cpp -o wordtest returns the
undefined reference to `__imp_curl_... | You need to compile libcurl with MinGW, or find a precompiled one. The one you installed to compile your app on Linux was compiled with a Linux compiler, and wouldn't work with MinGW.
MSYS2 repos have a bunch of precompiled libraries for different flavors of MinGW.
I've made a script to automatically download those lib... |
71,893,568 | 71,893,659 | How does std::map's emplace() avoid premature construction? | I am confused about std::maps's implementation of emplace(). emplace() is a variadic template function with the following declaration:
template <class Args...>
iterator emplace( Args&&... args );
As far as I understand, emplace() completely avoids constructing its value_type, i.e., std::pair<const key_type,mapped_type... | emplace constructs the pair in-place forwarding the arguments to its constructor; it does not avoid element_type construction, it just avoids one copy of a useless temporary pair compared to insert. In this regard, it's just as for the other containers: emplace is like insert, but instead if receiving a ready-made elem... |
71,893,745 | 71,895,697 | cannot gate index of arrival gate of new message in omnet++ 5.6.1 | I am following the tictoc tutorial and I want to change the code of tictoc12 so that I'll get the index of the gate from which we received the message so that the message will not send out from the same gate. This is my handleMesssage() function:
void Txc12::handleMessage(cMessage *msg)
{
if (getIndex() == 3) {
// ... | The value of exit code -1073741819 is equal to 0xC0000005 - an access violation. However, handleMessage() presented by you cannot be source of that error.
I strongly suggest using debugger to find the lines that cause that error. To do this:
Compile your project in debug mode.
In your omnetpp.ini set:
debug-on-errors... |
71,893,860 | 71,900,918 | New Sec-* headers in WebView2 | Working with MS WebView2 in C++ I can see a number of "Sec-*"-headers if visiting https://manytools.org/http-html-text/http-request-headers/
Example of a few:
Sec-Fetch-Dest document
Sec-Fetch-User ?1
Sec-Fetch-Mode navigate
Sec-Fetch-Site none
Sec-Ch-Ua-Mobile ?0
Sec-Ch-Ua "Not A;Brand";v="99", "Chromium";v="100", "Mi... | You are correct that the sec-* headers are part of the "forbidden header" lists. But they are forbidden for client code like the JS that runs on the user-agent. But user-agents like the browser can set those fields.
You can change some of the sec-* headers inside a callback added to add_WebResourceRequested. Some field... |
71,893,987 | 71,894,223 | Why isn't cin taking input after an invalid type is passed to the variable | It is a menu driven program and works completely fine when an int is passed to the variable options but runs into an infinite loop when char is passed.
int main(){
while(true){
int options{0};
cout<<"\nYour choice >>";
cin>>options; //this line doesnt execute after any char(say r) is given as an inp... | This is because of how C++ streams work.
When there is an error related to the internal logic of a stream operation (such as expecting an int but getting a char), its failbit is set.
When one of the stream bits (failbit, badbit, eofbit) are set, stream operations will not do anything.
To reset the iostate, you can use ... |
71,894,053 | 71,894,331 | Why does a moved class object not trigger the move constructor when bound to function parameter? | Lets say
I have a non-trivial class object A that defines a copy and move constructor
I move this object to a function which takes either A or A&&
Now in case of foo's parameter type being A, the move constructor is called (this is to be expected as A&& is passed as an argument to the function-local A).
But in case o... | When foo takes A&&, you are binding to a r-value reference and not making any new A objects that need construction.
This is because std::move is basically just a cast to r-value reference.
When foo takes A, you are passing a r-value reference to A as a means of constructing A. Here, the move constructor is chosen as it... |
71,894,415 | 71,894,532 | Why is there still no range-enabled reduction algorithm in std? | The only options available are std::ranges::for_each and simple range-based for loop. No counterparts for std::accumulate, std::reduce or std::inner_product. std::ranges::reduce would be enough, if it were present; inner product can be achieved combining reduce with zip. Falling back to iterator based algorithms is dis... |
Why is there still no range-enabled reduction algorithm in std?
Because they were not included in "The One Ranges Proposal" P0896 for C++20.
I am wondering if there is such function ... on the 23 horizons.
The expansion of ranges in C++23 has been planned in proposal P2214 "A Plan for C++23 Ranges". The proposal wa... |
71,895,213 | 71,901,609 | pthread_cond_wait never returning with EOWNERDEAD | I tried sharing a mutex and a condition variable between two processes. One process owns the mutex and sets the condition variable while the other waits on the condition variable.
My understanding is that the process currently holding the mutex is the "owner". When the owner app exits, a mutex lock on that specific mut... | EOWNERDEAD is a defined return value for pthread_mutex_lock(), not for pthread_cond_wait(). This is perhaps because CVs do not have owners in the same sense that mutexes do. In any case, there is no reason to expect a wait on a CV ever to return EOWNERDEAD.
Moreover, a thread waiting for on CV specifically does not ho... |
71,895,283 | 71,895,302 | How to use spaceship <=> operator with strcmp style function? | Suppose I have a C library with a struct cat, and a function compare(cat a, cat b) which returns an integer according for following rules :-
if a < b then returns -1
if a = b then returns 0
if a > b then returns +1
I am writing c++ wrapper (say catxx, with ct as C struct member) for this library and would like to us... | From cppreference:
The three-way comparison operator expressions have the form
lhs <=> rhs
The expression returns an object such that
(a <=> b) < 0 if lhs < rhs
(a <=> b) > 0 if lhs > rhs
(a <=> b) == 0 if lhs and rhs are equal/equivalent.
So you can just simply do
auto operator <=> (catxx& a, catxx& b)
{
return... |
71,895,330 | 71,895,351 | Why can't a function that has heap memory passed to it delete it in c++? | I tried to make a function that could delete memory on a int pointer. Unfortunately, it did not succeed. I feel like I made a mistake. Can someone help me find it?
#include <iostream>
void clean(int * x){
delete x;
x=nullptr;
}
int main() {
int * integer = new int;
clean(integer);
if(integer){
std::cout<<... | Your clean function actually does deallocate the memory.
But it doesn't update the pointer passed to it.
Change clear to accept the pointer by refernce to fix the problem:
void clean(int *& x) {
delete x;
x = nullptr;
}
Some more information:
Parameters in C/C++ are actually always passed by value. In your ori... |
71,896,829 | 71,897,131 | c++ using std::copy to copy an istream to a char* buffer | Is there a way to copy a std::istream to a buffer of data accessed by a "data()" method which returns a char*? For instance, the below code example. It results in a segfault. I know I could use std::back_inserter in this example, but my goal is not to copy to a vector ultimately.
#include <sstream>
#include <algorithm>... | No problem to copy provided enough storage is allocated upfront:
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::vector<char> vec(6); //note what happens here!
std::istringstream ss("foobar");
std::copy(std::istream_iterator<char>(ss), std::istream_iterator<char>
... |
71,897,055 | 71,897,067 | Reassigning pointer argument inside function in C++ | If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
In the following code, s==nullptr gets printed. Why did assignment to s inside the function assign_string not reflected in the main function?
#include<iostream>
#include<stri... |
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
No. When you pass an object by value, the parameter and the argument are separate objects. Modifying one object has no effect on the other object. This applies to all objec... |
71,897,288 | 71,897,329 | Removing the first word from a sentence and store it c++ | I am reading from a file in C++, and I want to remove all but the first word and store it,
sentence = sentence.substr(sentence.find_first_of(" \t") +
1);
this code remove the first word and keep the whole sentence , is there a way to store the removed word.
| https://en.cppreference.com/w/cpp/string/basic_string/find_first_of
take position of first match from find_first_of and then sentence start pos to position from find_first_of
std::string w1 = sentence.substr(0, sentence.find_first_of(" \t"));
|
71,897,375 | 71,900,891 | Modify line behind QStatusbar widgets | Is there a way to modify (remove) the line behind a permanent widget in a QStatusbar?
I don't know if it's important, but that's how I added the labels to the status bar:
wStyleTest::wStyleTest(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::wStyleTest)
{
// ...
ui->statusbar->addPermanentWidget(ui... | Subclass QProxyStyle and reimplement the drawPrimitive method. In there, check for the QStyle::PE_FrameStatusBar element and return from it instead of calling the base method.
#include <QProxyStyle>
#include <QStyleOption>
class StyleFixes : public QProxyStyle
{
public:
void drawPrimitive(PrimitiveElement element... |
71,897,899 | 71,897,993 | The following code is supposed to return true if i compare a1 with a2. But it is returning false | #include<iostream>
#include<cstring>
using namespace std;
class Array {
private:
int* array;
int s;
public:
Array()
{
array = NULL;
s = 0;
}
Array(int size)
{
size = (size > 0 ? size : 10);
array = new int[siz... | Three issues. The first is that you never allocated memory in the Array(int*, int) constructor for the array. The second is that this assignment...
*(arr + i) = *(array + i);
should be
*(array + i) = *(arr + i);
or even better
array[i] = arr[i];
The third is that you are neglecting to assign s to the length of the a... |
71,898,998 | 71,934,476 | Return a named object of a class from a function (by value ) and implicit move rule? | I have a problem with understanding what happens when you return an object of a class ( Not a specific class ) form a function ( pass by value )
in this code :
EXAMPLE 1
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class test {
public:
test(int y) {
printf(" test(int y)\n");
... | The behavior of your program can be understood with the help of Automatic move from local variables and parameters:
If expression is a (possibly parenthesized) id-expression that names a variable whose type is either
a non-volatile object type or
a non-volatile rvalue reference to object type (since C++20)
and tha... |
71,899,293 | 71,899,307 | When I attempt to add a specific character of a string through push_back() it throws me a type conversion error | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string input;
getline(cin, input);
int x = input.length();
vector<string> arr;
for(x; x==0; x-2){
arr.push_back(input[x]);
}
return 0;
... | There are several bugs in the code that make it fail; most important the third part of the for loop: x-2 calculates the result of the subtraction, and then moves on. It is never stored anywhere, so x never changes. The loop runs forever, inserting over and over input[x] into the vector, until something blows up. You pr... |
71,899,678 | 71,901,448 | Color Output in MFC List issue | This code is about the worm game. It is a problem to print the color of the tail section. The code is written so that the worm's head grows longer and longer each time it eats. And from head to tail, it goes from green to blue. where the initial values for _GboxColor, _BboxColor, and Colornum are 255, 0, and 1, respect... | Have a breakpoint to see the value of _GboxColor when drawing the 3rd segment. Maybe an overrun occurs (the RGB macro hides the fact that the color is just a 32-bit value). Maybe you should initialize _GboxColor and _BboxColor before the while loop, not after it.
|
71,900,146 | 71,901,361 | How to avoid dynamic_cast in this case? | I have 3 classes in my program:
class GameObject{
private:
std::pair<int, int> position;
}
class World{
private:
std::vector<GameObject*> gameObjects;
int gravity;
}
class MovingObject : public GameObject{
private:
int velocity;
bool isSensitiveToGravity;
... | When you think in terms of functionality in OOP you should think in terms of interfaces and not structs of data. This is exactly the case so you should create an interface with a function interactWithGravity and use it. In case this is an object that does not interact with gravity simply do nothing.
To emphasize why th... |
71,900,460 | 72,008,239 | Tiff Windows Imaging Component c++ | I am trying to replace libtiff into WIC (since libtiff is not able to pass Black Duck Analysis tool anymore)
I have used their example
https://learn.microsoft.com/en-us/windows/win32/wic/-wic-creating-encoder
And I was able to create a tiff.
I also needed to change the compression type
so I change the code into
if ... | The WIC built-in TIFF encoder always writes the TIFFTAG_RESOLUTIONUNIT as 2 (inches). You can use WIC to read the existing tag, but you can't write a different value for this particular metadata item.
|
71,900,490 | 71,901,791 | vulkan error when creating a vulkan instance when pNext is initialized | I'm following a vulkan tutorial and when I'm initializing the instance createInfo.pNext with
VkDebugutilsmessengerCreateInfo*
I'm getting an erorr.
populateDebugMessengerCreateInfo(debugCreateInfo);
createInfo.pNext = & debugCreateInfo;
populateDebugMessengerCreateInfo:
void app::populateDebugMessengerCreateI... | You need to set pNext to NULL or it leads to uninitialized pointer dereference.
|
71,900,677 | 71,902,312 | CMake project building with SFML library | i can't understand how to build SFML-project using CMakeLists.txt file.
Help me, please, if you have time. Thank you!)
Details
I downloaded SFML library from official site (https://www.sfml-dev.org/index.php), moved it to my project root (see screenshots below), wrote C++-code using SFML and entered this cmake-command:... | Dumb rule when you have a CMakeLists.txt in which dependencies are discovered with find_package(): add their install folder to CMAKE_PREFIX_PATH while calling CMake configuration.
In you case, the CMake configuration of your project should be:
cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="... |
71,901,011 | 71,901,012 | Can we convert a matlab built in function to c/c++ code using matlab coder | Can we convert matlab built in function that are present in 5G toolbox to c/c++ code using matlab coder.
| It is shown at the end of the help page of that specific function. Type
>> help yourFunctionName
at the command line. Then scroll to the very bottom and then look at Extended Capabilities > C/C++ Code Generation. When that is present, you should be able to generate code (please unfold to see the details).
If C/C++ Cod... |
71,901,206 | 71,902,812 | Show all QCompleter elements on click | There is QComboBox with QCompleter. It is necessary to show all complementer elements when clicking on the LineEdit combobox. There is this code:
completer = new QCompleter(this);
completer->setModel(assignment_contacts);
completer->setCompletionMode(QCompleter::CompletionMode::PopupCompletion);
completer->popup()->set... | Put this code after installing event filter to lineEdit of your combobox:
//...
ui->comboBox_NewClientContacts->installEventFilter(this);
And this one to eventFilter of MainWindow:
//...
if (object == ui->comboBox_NewClientContacts){
if(event->type() == QEvent::KeyRelease && ui->comboBox_NewClientContacts->cur... |
71,901,327 | 71,901,593 | Why is getline not splitting up the the stringstream more than once? | When I'm trying to read data from a file, it is not updating the value of tempString2.
Instead of grabbing and splitting the new line, it just holds the last value of the first data line.
The reason I believe that the second getline is the issue is that the data is being read in, and the loops are running the exact num... | std::getline() extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
end-of-file condition on input, in which case, getline sets eofbit.
the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character... |
71,901,925 | 71,901,992 | How to read binary data from file after read sucessfully the ascii header in the file | I am trying read the Netpbm image format, following the specification explained here. The ascii types for the format (which have P1, P2 and P3 as magic number), I can read without problems. But I have issues reading the binary data in these files (whose with P4, P5 and P6 as magic number) - the header for the file (whi... | while(getline(file, line_pixels)) {
std::getline reads from the input stream until a newline character is read.
A file is a file. It contains bytes. Whether you believe the file contains text, or binary, is purely a matter of interpretation.
Text lines are terminated by a newline character. That's what std::getline do... |
71,902,134 | 71,902,667 | Give an aggregate a converting constructor? | I'm writing a large fixed-size integer type that is made up of multiple uint64_ts, like in the (simplified) example below. I would like my type to behave like the built-in integer types, which means (among other things) that:
it should be uninitialized if you don't assign a value to it, and
it should accept widening ... | A constructor such as uint128_t() {} will leave your array uninitialized by default. Ability to leave members uninitalized has nothing to do with being an aggregate.
But there's a better option: uint128() = default;. It will cause uint128_t x; to be uninitialized, but uint128_t x{}; will be zeroed, just like with built... |
71,902,142 | 71,902,678 | Best way to optimize timer queue with concurrent_priority_queue C++ | I'm working on timer queue using concurrent_priority_queue right now..
I implemented basic logic of executing most urgent event in this queue.
Here's my code.
TimerEvent ev{};
while (timer.mLoop)
{
while (timer.mQueue.empty() == false)
{
if (timer.mQueue.try_pop(ev) == false)
continue;
... |
How can I optimize this timer without re-insert event into queue again?
By the looks of it, that'll be hard when using the implementation of concurrent_priority_queue you are currently using. It wouldn't be hard if you just used the standard std::priority_queue and added some locking where needed though.
Example:
#in... |
71,902,547 | 71,902,648 | Why is the move constructor not invoked when returning an rvalue? | I have created a class Animal:
class Animal {
public:
Animal() = default;
Animal(Animal&& a) = delete;
Animal(Animal& a) = delete;
Animal& operator=(Animal&& a) = delete;
Animal& operator=(Animal& a) = delete;
};
Animal func1() {
return Animal();
}
Animal func2() {
Animal a {};
return... | Case 1
Here we consider the statement:
Animal a1 = func1();
The call expression func1() is an rvlalue of type Animal. And from C++17 onwards, due to mandatory copy elison:
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move cons... |
71,902,558 | 71,902,646 | Does the return type of a deleted operator matter if the operator is deleted? | I am reading ‘C++ concurrency in action’, one page talks about copy-assignment operator =delete.
I have googled about it (Deleting copy constructors and copy assignment operators. Which of them are essential?) and tried some code by myself.
I want to know if there is a difference between
void operator= (const MyClass&)... | C++ allows you to have operators with whatever return type you want.
In all cases, you are overloading operator= with different semantics so they will all work.
But it's best to follow the widespread convention of returning a class reference so that assignment chains (a = b = c) and constructs such as (while ((a = b) =... |
71,902,815 | 72,248,756 | qemu-system-i386: Error loading uncompressed kernel without PVH ELF Note | Im trying to boot my OS to qemu with this code:
qemu-system-i386 -kernel MyOS/mykernel.elf
But I keep getting this error:
qemu-system-i386: Error loading uncompressed kernel without PVH ELF Note
Here is the code i use to build:
i686-elf-gcc -std=gnu99 -ffreestanding -g -c MyOS/start.s -o MyOS/start.o
i686-elf-gcc -st... | Try adding this to the command line
-machine type=pc-i440fx-3.1
Source: https://forum.osdev.org/viewtopic.php?f=1&t=33638
Alternatively have a look at this
How can I create a PVH "kernel" that will be run by qemu
Hope this helps
|
71,903,055 | 71,903,157 | Redundant string initialization warning when using initializer list in the default constructor | class person
{
private:
std::string name;
int hungerLevel;
std::string location;
int money;
public:
person() : name(""), hungerLevel(100), location(""), money(0) {}
};
When I initialize my string variables as empty strings in the default constructor using the Initializer list I get the warning "Red... | The gist of your question has been answered in the comments, but you can avoid a constructor altogether here by declaring your class like this:
class person
{
private:
std::string name;
int hungerLevel = 100;
std::string location;
int money = 0;
};
This (to me) has the huge advantage that you have the ... |
71,903,953 | 71,904,351 | Why is C++ slower than C when doing literaly nothing | C++ is almost 4 times slower than C at doing nothing (at least on my machine). When the following file is compiled by g++, it is 4 times slower than with gcc:
int main() {}
With time sh -c 'for i in $(seq 0 1000) ; do ./a.out ; done', I get 0.515s for the C version, and 2s for the C++ one. Why is that?
There isn't a s... | C++ standard library initial startup is heavier than the C runtime.
C++ ABI needs to initialize some structures for basic language features. Mutex locks for thread-safe initialization of data, exeptions, thread local storage, RTTI, etc.
This is why an empty executable created with a C++ compiler will start slower than ... |
71,904,320 | 71,904,405 | C++: Ambiguos function call even with unique function names at each inheritence level | Code -
#include<iostream>
using namespace std;
class P {
public:
void print() { cout <<" Inside P"; }
};
class Q : public P {
public:
void print() { cout <<" Inside Q"; }
};
class Q2: public P {
public:
void print2() { cout <<" Inside Q2... |
I expected class Q to hide the print() function of class P
This has nothing to do with Q hiding the superclass's print().
Q2 inherits from P, and therefore inherits print().
class R: public Q2, public Q { };
print() is inherited from both Q2 and from Q. Whether they turn out to be the same or different methods is im... |
71,904,533 | 71,904,597 | Problems reading/writing to binary file | I wrote the code below to save a vector of struct to a binary file. The problem is the reading stops before all the written data is read.
Changing the reinterpret_cast<const char*> with (char*) or (const char*) does not help or change the output.
Seeing as it does read the right number for the data it does read the cod... | binFile.open("test.bin", std::ios::binary);
The output file was opened in binary mode.
binFile.open("test.bin", std::ifstream::in);
The input file was not.
This only matters on operating systems that trace their lineage to MS-DOS, and if your binary file happens to have a 0x0D byte it will be gratuously deleted, when... |
71,904,940 | 71,904,978 | What is the following MACRO doing? | #define DEFINE_VECTOR_MEMBER_DATA_S(T,c,n,s) T c ## :: ## n[s]
I have it in the legacy code. It is compiled by MSVC 2022, but not with Clang.
I plan to replace it, but before it I need to know what does it do.
| It defines a vector which is a static member of a class.
Type T.
Class c.
Name of vector n.
Size of vector s.
## pastes 2 pieces together, but isn't needed anyway.
If the linker says it the vector's missing just add:
T c::n[s];
Into a .cpp file with the parts replaced accordingly.
|
71,905,148 | 71,905,334 | Stuck using an array in the constructor as a parameter | I am new to this and I am having a problem. I want to use an array as a parameter in the constructor, but when I want to initialize the parameter in the main() function and call the class, it seems I can't directly put the array values as I did with the name and surname. The simplified code looks like below. It shows a... | The only thing that needs to be changed is the constructor:
Student(string e, string b, int c, int (&&A)[5]) {
name = e;
surname = b;
age = c;
for (int i = 0; i < 5; i++)
grade[i] = A[i];
}
|
71,905,176 | 71,905,234 | Alias template doesn't work like class template | I am learning about C++ templates from C++ Primer 5th edition. For example, i learnt that we could do the following:
template<typename T>
struct Custom
{
};
template<>
struct Custom<int>
{
int a = 0;
};
Then i learnt that C++11 also added a feature of alias templates. So i tried the same with them as shown... | The problem is that we cannot specialize an alias templates.
From temp.decls 17.5.3:
Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.
|
71,905,195 | 71,905,543 | Wrap a function that takes std::function<double(doule)> in order to pass functions that take more arguments | Problem
I have a function double subs(std::function<double(double)> func), and I want to wrap it in a new function that looks like this
template<typename... Args> double subsWrap(std::function<double(Args... args)> func)
that applies subs to some function that takes more inputs as
subs( subs( subs( ... func(...) ) ) )... | What about using variadic lambdas together with std::is_invocable type trait to terminate recursion?
template<class Fn>
double subs_wrap(Fn func) {
if constexpr (std::is_invocable_v<Fn, double>)
return subs(func);
else
return subs([=](double x) {
return subs_wrap(
[=]... |
71,905,201 | 71,905,586 | Tesseract very low detection quality | Trying to read some data with tesseract but it's already strugling with date and time, so I created a minimal test case.
code:
#include <string>
#include <sstream>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <boost/algorithm/stri... | It looks like the main issue is setting bytes_per_pixel to 3 instead of 1 in api->SetImage.
The image after cv::adaptiveThreshold is 1 color channel (1 byte per pixel) and not 3.
Replace api->SetImage(image_final.data, image_final.cols, image_final.rows, 3, image_final.step); with:
api->SetImage(image_final.data, image... |
71,905,686 | 71,908,684 | Trigger stm32 timer on PWM | I'm new to stm32 timers and have a question concerning triggering.
I would like to generate four squarewaves two of each complements of each other. That is the trivial part.
Now I would like to introduce a variable phaseshift between each of the two complementary signalgroups. (Phaseshift PWM)
Now my question, can I tr... | A single advanced control timer (TIM1 or TIM8) can do all of this for you.
See the reference manual section 17.3.11 "Complementary outputs and dead-time insertion".
Alternatively you can chain timers, see section 13.3.15 of the same manual.
|
71,905,738 | 71,905,805 | C++, write from file into map | im just new at c++ and I try to read from a file and write the content into a map<string, float>.
But only the first element of my file gets mapped and i cant figuer out why.
The file looks like this:
E:16.93
N:10.53
I:8.02
...
And the code i got for this part so far:
std::map<char, float> frequenciesM;
fstream freque... | You are telling getline() to read until a '\0' (nul) character is encountered, but there is no such character in your file, so the entire file gets read into the string on the 1st call, and then you extract only the 1st set of values from the string, discarding the rest of the data.
To read the file line-by-line, you n... |
71,906,000 | 71,906,274 | By convention does Qt allow signals and slots to have different signatures? | I assumed from experience with Qt that all signals and slots required identical signatures. Recently I seen Qt code that connects totally different signatures, and the slot are called when the signal they were connected to is emitted. For example, a signal that emits a couple objects to a slot that takes no arguments.
... | From the documentation on Qt Signals and Slots:
The signature of a signal must match the signature of the receiving
slot. (In fact a slot may have a shorter signature than the signal it
receives because it can ignore extra arguments.)
Essentially, you can drop arguments from the end of your slot's signature (you can ... |
71,906,069 | 71,906,177 | What is the proper way of using a source generator in CMake | In my C++ project I'm using a source generator to embed some resources into the binary.
I use CMake to build my project and my code works but had some issues.
I am pretty sure that what I want to accomplish is possible but I didn't find any answer online.
The current problems I have are:
The generator runs every time,... | This one is interesting, because there are multiple errors and stylistic issues, which partially overlap each other.
First off:
file(GLOB_RECURSE SRC src/*.cpp src/*.hpp)
add_executable(${PROJECT_NAME} ${SRC})
While convenient in the beginning, globbing your sources is not a good idea. At some point you will have a te... |
71,906,265 | 71,907,938 | Get variables from gnuplot to c++ | I'm writing a code in c++ which plots a dataset using gnuplot, and I realized that I could simplify my code a lot if I could get variables from gnuplot to my c++ code. e.g. if I did a fit f and get his stats i.e.
f(x)=a*x+b
fit f 'data.txt' via a,b
stats 'data.txt' u (f($1)):2 name 'Sf'
Is there any way to get, for ex... | Assuming that you are communicating with gnuplot trougth a FIFO, you can order to gnuplot
print <variable>
and you can read this to your c++ program.
Eg. for reading a varirable:
double getVal(std::string val){
float ret;
std::string str;
str="print "; str+=val;str+="\n";
fprintf(gp, str.c_str());
f... |
71,906,301 | 71,906,701 | How can you pass an ifstream to thread? | I'm trying to implement multi-threading in my program. I'm trying to make my directory searcher run in a thread, and join for the rest of the function.
The file thread function searches my directory and finds each file, and I'm trying to use this in my file reader section within my main() function.
How should I pass an... | I suspect you actually want this, although its not at all clear why you are using a separate thread
void file_thread(std::ifstream& file){
//open csv file for reading
std::string path = "path/to/csv";
file.open(path);
}
If thats the path, why iterate over the directory
This code still wont help if you call... |
71,906,814 | 71,923,795 | fread/fwrite introduces garbage values | Data file data.dat:
5625010350032.36719 5627008621379.12591 5628763999478.55791 5630383772880.98831 5632384688238.96095 5633992371569.87936 5635830220975.76879 5637713568911.67183 5639436594135.51215 5641160625591.58400 5643072053703.23919 5644920788572.33232 5646668772882.99855 5648398453919.33759 5650178043246.84799 ... | Appearantly it does some rounding somewhere in the process and fread stores that 13th value as integer64 "integer64" (default) reads columns detected as containing integers larger than 2^31 as type bit64::integer64.
What you can do is force it to be interpretted as numeric, by adding colClasses = c("numeric") to your ... |
71,906,974 | 71,907,017 | Initialize a template class private static variable in C++ | I'm trying to compile a sample program in C++ using templates. The template class has a priavte static member variable which seems to be undefined when trying to compile. Going through other answers on SO, I realized that this variable needs to be defined as well. However my attempts at defining this variable have been... | pv_mem_ is defined as follows
constexpr static std::array<fruitGroup, sizeof...(TotalFruits)> pv_mem_
{
fruitGroup{TotalFruits, &FruitFunction<TotalFruits>}...
};
which uses & to take the address of FruitFunction<TotalFruits>, but since FruitFunction is only declared and not defined, it will generate an undefined r... |
71,907,008 | 71,907,476 | OpenCV Program that Allows User to Enter Image and Transformation Matrix and See Transformation Applied | So, the first problem I ran into was that OpenCV defines its origin about the top left corner rather than the center of the window. This was a problem because I want to just apply a transformation matrix to an image (say a reflection about the x-axis for example) and see it applied "in place", so it stays in the same s... | To avoid undesired cropping, transform once only (simultaneously).
Mat M = (Mat_<double>(3, 3) << 1, 0, -(src.rows / 2), 0, 1, -(src.cols / 2), 0,0,1);
Mat M2 = (Mat_<double>(3, 3) << 1, 0, 0, 0, -1, 0, 0,0,1);
Mat M3 = (Mat_<double>(3, 3) << 1, 0, (src.rows / 2), 0, 1, (src.cols / 2), 0,0,1);
Mat Composition = M3 * (... |
71,907,197 | 71,908,010 | Can I split my code into header and cpp files at the end of development? | I am coding a minesweeper game and I am currently splitting declarations and code between header and cpp files like you're supposed to, however, this is making it kind of convoluted to keep track of everything.
I know this is against best practices, but could I just declare and code everything on cpp files and then spl... | Declaring and coding everything on cpp files will cause error lnk2005. Putting it all in the header file won't cause the error, although this is also against best practices. But it all depends on personal writing style.In addition, code should be easier for others to read and understand. And It's a good choice to follo... |
71,907,603 | 71,907,747 | Why is my permutation code generating duplicates? | My code is generating duplicates (3) to be precise and I don't know why, could anyone help out?
I've tried searching for a problem, but to my eyes it seems the same as other premutation codes on the internet.
I was thinking it could've been a miss-use of the loop but I don't see why it's giving me 9 answers instead of ... | You are getting 9 combinations of string because, in permute(), the for loop variable i initialised with 0:
for (int i = 0; i < n; i++) {
^^^
Note that you are calling permute() function recursively to generate the permutations of string and, in every recursive call, the index is incremented by 1 while pas... |
71,907,657 | 71,907,786 | How to take 3 dimensional input for 3D vector? | I have to take input in a 3D vector, of dimension (n,m,4). I have written the following piece of code, which is not working don't know why, please lemme know what I am doing wrong.
cin>>n>>m;
vector<vector<vector<char>>> v3;
for(int i=0;i<n;i++){
vector<vector<char>> v2;
for(int k=0;k<m;k++){
vector<cha... | You haven't described the problem. Is it a compilation error? A runtime error?
Anyway - you're code compiles on MSVC (replaced int with char as already suggested).
But it is implemented in an inefficient way, because it involves a lot of copying around std::vectors and using push_back will cause reallocations of the ve... |
71,908,109 | 71,972,294 | BIts Per Sample / Pixel libtiff vs WIC | TIFF *TiffImage;
uint16 photo, bps, spp, fillorder;
uint32 width,height;
unsigned long stripSize;
unsigned long imageOffset, result;
int stripMax, stripCount;
unsigned char *buffer, tempbyte;
unsigned short *buffer16;
unsigned int *buffer32;
unsigned long bufferSize, count;
bool success = true;
int shiftCount = 0;
//... | The DirectXTex library has lots of examples of using WIC from C++.
You need something like:
using Microsoft::WRL::ComPtr;
ComPtr<IWICMetadataQueryReader> metareader;
hr = pIDecoderFrame->GetMetadataQueryReader(metareader.GetAddressOf());
if (SUCCEEDED(hr))
{
PROPVARIANT value;
PropVariantInit(&value);
if... |
71,908,718 | 71,908,920 | What does std::filesystem::is_regular_file(path) mean on Windows? | About std::filesystem::is_regular_file(path), cppreference.com says:
Checks if the given file status or path corresponds to a regular file […] Equivalent to s.type() == file_type::regular.
For example, in the Linux kernel, file types are declared in the header file sys/stat.h. The type name and symbolic name for each... | Since we are talking about Windows we can consider MS implementation of the standard library, and that's how they determine if the file is regular:
if (_Bitmask_includes(_Attrs, __std_fs_file_attr::_Reparse_point)) {
if (_Stats._Reparse_point_tag == __std_fs_reparse_tag::_Symlink) {
this->type(file_type::sy... |
71,909,245 | 72,134,309 | How to use grpc c++ ClientAsyncReader<Message> for server side streams | I am using a very simple proto where the Message contains only 1 string field. Like so:
service LongLivedConnection {
// Starts a grpc connection
rpc Connect(Connection) returns (stream Message) {}
}
message Connection{
string userId = 1;
}
message Message{
string serverMessage = 1;
}
The use case is that... | I figured out how to used the api. Looks like it is pretty flexible, but still a little bit weird given that I typically just expect the async api to receive some kind of lambda callback.
The code below is blocking, you'll have to run this in a different thread so it doesn't block your application.
I believe you can h... |
71,910,536 | 71,910,644 | error: no matching function for call to ‘Point::Point() | So i created the class Point and want to use it as the parameter of the constructor in the class Circle , but the error : There is no default constructor for class "Point" shows up and I dont know how to fix it. The code is represented below this text:
class Point {
private:
int x, y;
public:
Point(int X, int ... | The first problem is that when the constructor Circle::Cirlce(Point, int) is implicitly called by the compiler, before executing the body of that ctor, the data members centre and radius are default initialized. But since you've provided a user-defined ctor Point::Point(int, int) for class Point, the compiler will not ... |
71,911,012 | 71,925,416 | How to make StopWatch in QT c++? | I'm making an app on QT with UI. Also, I have a function. I want to display the running time of a function. I also want to pause the stopwatch. Any ideas on how to properly embed a stopwatch in my application?
Here is my code:
void SomeFunc()
{
while (1)
{
// Start Timer
// some code
// Stop Timer
// Start Timer2
// so... | Use QElapsedTimer for measuring the duration since starting the computation.
Judging from your previous questions on very related topics, you do have a MainWindow class that contains the on_push_button function. In that class, declare the QElapsedTimer member; then start it when your computation starts.
Use a QTimer to... |
71,911,323 | 71,975,395 | Questions regarding Red-Black Tree Deletion (z has 2 children) (pre-fixDelete) | Code Source - https://github.com/Bibeknam/algorithmtutorprograms/blob/master/data-structures/red-black-trees/RedBlackTree.cpp
y = z;
int y_original_color = y->color;
if (z->left == TNULL) {
x = z->right;
rbTransplant(z, z->right);
} else if (z->right == TNULL) {
x = z->left;
... | On your questions
Yes that can happen, TNull's parent is set and the authors remark that this is a deliberate design choice which they exploit.
y is moving to where z is and this just fixes y so its pointers are what z had. s
No. Essentially when the node to be deleted has 2 children, you find the successor or predece... |
71,911,487 | 71,911,784 | OpenCV output monochrome TIFF group 4 compression | Is there a way to output monochrome TIFF files in OpenCV with group 4 compression?
This is the command to do it with imagemagick/graphicsmagick
'gm convert '.$file.' -type bilevel -monochrome -compress group4 '.$output
OpenCV version 4.5.1
update
# g++ -Wall -O3 -std=c++17 main.cpp -o main `pkg-config opencv4 --cflags... | OpenCV uses libtiff (link). If you call cv.imwrite (link) you can pass additional parameters.
For group 4 compression the docs say that you have to pass the IMWRITE_TIFF_COMPRESSION flag (link) with value COMPRESSION_CCITTFAX4 (link).
Example:
#include <tiffio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using... |
71,911,501 | 71,911,564 | C++ return char* then delete it | So I have this function:
char * func()
{
char * temp = new char[length]; // Length is defined elsewhere
/*
Do some stuff with temp
*/
return temp
}
My problem is I'm not sure whether or not this leaks memory.
If so, I don't know how to make it not do that.
I thought I could delete it after return, but how would I do t... |
My problem is I'm not sure whether or not this leaks memory.
This doesn't leak memory, because the pointer to the allocation is returned and thus the ownership is transferred to the caller. If the caller loses the returned pointer value before deleting it, then the caller has leaked memory.
That said, this is a bad d... |
71,911,677 | 71,911,799 | Is there a performance difference between assigning before returning and directly returning in C++? | Is there a performance difference between the two following functions, or is it handled by the compiler the same?
double f1(double a, double b) {
return a + b;
}
double f2(double a, double b) {
double sum = a + b;
return sum;
}
Thanks.
|
Is there a performance difference between the two following functions
One function contains two statements and the other contains one statement.
or is it handled by the compiler the same?
They can be. Both functions have identical observable behaviour, so they may produce an identical program.
|
71,911,860 | 71,911,983 | Dereferencing std::vector passed by reference | I have a quick (and possibly stupid) question, but I couldn't find an answer online:
When I pass a struct by reference, I can nicely and cleanly access its fields via MyArray->Field1, MyArray->Field2 etc.
Is there a similar way to do this for the elements of a std::vector? The only way to do this I know, is something l... | Passing a std::vector by refernce allows you to access its public members, e.g.:
void f(std::vector<int> & v)
{
v.resize(1);
v[0] = 3;
}
However, the syntax you used your question actually looks like passing by pointer. You can do that as well with a std::vector but in C++ we usually prefer to pass by referenc... |
71,912,177 | 71,915,998 | pybind11 how to cast double pointer argument implicitly to long value? | I'm trying to expose c++ library with classes that have function members that receives double pointer argument (for initialization) to python via pybind11.
For example:
class IInitializer{
virtual bool CreateTexture(ITexture **out_pTex, UINT Width, UINT Height) = 0;
}
I know that pybind11 has no support out-of-the-... | I would write the glue code into a lambda:
IInitializerWrap.def("CreateTexture", [](const IInitializer& self, UINT Width, UINT Height) {
ITexture* rv;
self.CreateTexture(&rv, Width, Height);
return rv; // Or reinterpret_cast if you prefer to.
});
|
71,912,373 | 71,912,773 | How to store values from a normal array to a 2D array in C++? | I want to store the Values to the CustomValues array. How can I do this?
Any code and explanation would be great.
int main() {
int CustomValues[4][3];
int Values[3] = {234, 98, 0};
int Values1[3] = {21, 34, 5};
int Values2[3] = { 12, 6, 765 };
int Values3[3] = { 54, 67, 76 };
}
The CustomValues ar... | There's a few different ways you can do this. Since we already know your constraints, I've taken liberties to not do this dynamically.
The first is memcpy, which is in the <cstring> header:
memcpy(CustomValues[0], Values, sizeof(Values));
memcpy(CustomValues[1], Values1, sizeof(Values1));
memcpy(CustomValues[2], Values... |
71,912,427 | 71,913,202 | Why does this code with SFINAE compiles error, even though there is a template that can match | The code is as follows.
#include <tuple>
#include <array>
template <typename T, typename Type>
struct Vec {
using value_type = T;
static constexpr size_t size() { return Type::size; }
};
template <size_t Size>
struct Const {
static constexpr size_t size = Size;
};
template <class T, class Type, class = void>
... | SFINAE applies only if the invalid type or expression resulting from a use of a template parameter appears within:
a template parameter declaration within the same template parameter list
a default template argument which is used (or will be if overload resolution or class partial specialization matching selects the t... |
71,912,564 | 71,913,123 | Can ranges::equal be used as a predicate for a pair of transform_view ranges? | Example Program and Compiler Errors
The following code produces two compiler errors (MSVC++ 2022 compiling with /std:c++latest because <ranges> isn't yet enabled for /std:c++20 at time of writing this question):
error C2672: 'operator __surrogate_func': no matching overloaded function found
error C7602: 'std::ranges::_... |
Can ranges::equal be used as a predicate for a pair of transform_view ranges?
No, it cannot. This is because ranges::equal is colloquially referred to as a niebloid (cppref, blog).
In the standard, they are defined in [algorithms.requirements]/2:
The entities defined in the std::ranges namespace in this Clause are... |
71,912,594 | 71,913,133 | Threading returns unexpected result - c++ | I'm learning about threads for homework, and I've tried to implement threading on a simple program I've made. Without threading the program works perfectly, but when I thread the two random number generator functions, it returns incorrect results. The result always seems to be '42' for both number generators, not sure ... | Since you have several threads accessing a mutual resource, in this case the vector of readings, and some of them are modifying it, you need to make the accesses to that resource exclusive. There are many ways of synchronizing the access; one of them, simple enough and not going down to the use of mutexes, is a binary ... |
71,912,838 | 71,913,058 | Subtract extremely small number from one in C++ | I need to subtract extremely small double number x from 1 i.e. to calculate 1-x in C++ for 0<x<1e-16. Because of machine precision restrictions for small enoughf x I will always get 1-x=1. Simple solution is to switch from double to some more precise format like long. But because of some restrictions I can't switch to ... |
Simple solution is to switch from double to some more precise format like long [presumably, double]
In that case you have no solution. long double is an alias for double on all modern machines. I stand corrected, gcc and icc still support it, only cl has dropped support for it for a long time.
So you have two solutio... |
71,913,815 | 71,913,894 | How to improve operator overloading for my class? | I have started learning C++. My teacher gave an assignment. I completed it (some polishing work is left) and everything seems to work but there is redundancy. My major issue is overloading.
How to improve overloading in my class. Rather than writing all four functions (two for fstream and two for iostream), is it possi... | You only need two overloads here. ifstream and ofstream inherit from istream and ostream respectively so if you have
friend istream& operator >> (istream &is, book& obj);
friend ostream& operator << (ostream &os, const book& obj);
then those will work with cout and cin, and any fstream or stringstream objects as they... |
71,914,593 | 71,983,793 | Remotely debugging android NDK app using VSCode | I've tried a number of ways to get this to work but to no avail so far.
My requirements are as follows:
To be able to connect using visual studio code & gdb to a debug-enabled APK process running on an android device
The device should not have to be rooted
I expect full visual debugging of C++ NDK code on that device.... | In then end, I eschewed lldb in favour of gdb, which ndk-debug can use (for now, they're depreciating it, even though it works and lldb clearly either does not work or requires some setting that it doesn't advertise to work) if you include the 'no_lldb' flag or set 'use_lldb' to 'False' in ndk-gdb.py.
However, if you w... |
71,915,092 | 71,921,671 | ReadConsoleOutputAttribute function usage in c++ | I need to get background color by known coord in c++. I tried to use ReadConsoleOutputAttribute from windows.h, but i didn't work. Here is my code:
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD count;
COORD cursor = { this->X, this->Y };
LPWORD *lpAttr = new LPWORD;
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsole... | Color attributes are specified by TWO hex digits -- the first
corresponds to the background; the second the foreground. Each digit
can be any of the following values:
0 = Black 8 = Gray
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 ... |
71,915,138 | 71,915,540 | How do I fix this error in the algorithm header file? | I'm currently writing a code that receives a string as an input, checking whether or not it is comprised of only chars from the car_acc array and, if it isn't the case, requesting the input once again, using a do-while loop.
This is the code:
char car_acc [11] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':... | The algorithm std::all_of is intended to invoke a unary predicate on every element within an iteration sequence, reaping either 'true' or 'false' from each, and answering with one encompassing 'true' (everything reported true) or 'false' (at least one thing reported false). To do this, you supply three things:
A begin... |
71,915,181 | 71,915,730 | C++ omp for loop with conditional counter (not loop index, not a reduction) | I am parallelizing a code where elements of an array B are a function of elements of an array A. B is smaller than A (i know both sizes in advance) and B[n] is written only if A[n] satisfy a certain condition. A representation of the code would be copy A[n] to B[n] only if A[n] is even, like:
#include<omp.h>
#include<i... | You say that copying A into B is a "representation" of your code. If computing the B elements actually takes some amount of work, then you could let the A loop be done sequentially, and create tasks for the computation of the B elements.
|
71,915,275 | 71,955,385 | How to set up the Google Code Jam interactive judge for a C++ solution on Windows? | Here is the Code Jam Interactive problem that I'm trying to test locally. My solution is in C++, my IDE is Visual Studio 2019, and I'm on Windows 10. I have little to no experience with Linux, Bash, Python and I'm stuck.
Reading an answer from How to debug Google Code Jam interactive problems on VSCode using python? wa... | I figured it out. I'll try to explain everything from start.
First make sure that you have the compiled your solution and that you have the executable file somewhere.
There's an interactive_runner Python script which can be found in the FAQ of CodeJam. Create a Python file named interactive_runner in the same folder as... |
71,915,342 | 72,225,479 | LibTorch with OpenCV: version GOMP_5.0 not found | I'm trying to use OpenCV and LibTorch in the same project. Libtorch is installed in /usr/include/libtorch, downloaded from the PyTorch website. I'm using the cxx11 ABI version for CUDA 11.3.
Here's my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.23 FATAL_ERROR)
project(chess-rl VERSION 1.0)
find_package( Open... | I faced the same problem, and your thread contributed to one solution.
You need to add a shared library in your CMakelists.txt file.
add_library(libName SHARED IMPORTED)
set_property(TARGET libName PROPERTY IMPORTED_LOCATION "/usr/lib/libgomp.so")
target_link_libraries(PROJECT_NAME
libName)
I hope I could help you
Wit... |
71,915,764 | 71,915,931 | How does memory work in declaration of structure which uses self-referential structure pointer in C/C++? | In declaration of structure in C/C++, we have to use a self-referential structure pointer instead of a structure itself.
// compile error
struct stack {
int overflow;
stack p;
}
struct stack {
int overflow;
stack* p;
}
One brings about the error but the other doesn't under the same condition(declarat... | This
struct stack {
int overflow;
stack p;
}
Tries to contains itself , so how big should it be? With one copy of itself it would look line this
int ov;
{
int ov;
stack p;
}
but that stack p needs to be expanded - so we get
int ov;
{
int ov;
{
int ov;
stack p;
}
... |
71,915,860 | 71,916,553 | How initialize time points and set them to a falsy value afterward in C++? | I am new to C++ and I want to implement the following behavior.
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
int main(){
chrono::high_resolution_clock::time_point start_time_point;
while(true){
if(statement_1){
// check whether start_time_point is falsy
... |
I am used to javascript, so in JS I only would assign null to
start_time_point in the second if block but in C++ it is different.
How would I achieve the above-mentioned behavior?
A chrono::time_point has a min() member, returning the lowest possible time point. It is not identical, but could be used similar to the n... |
71,916,444 | 71,916,683 | Dynamic sized int list | I would like to create a int list in C++, but it just doesn't make sense at all.
Also I don't want it to have static size.
I tried this, but "array size must be specified in new expressions without an initializer", what should I do?
int* list = {};
int* list = new int[];
int list[];
Full code
#include <iostream>
usin... |
"array size must be specified in new expressions without an initializer", what should I do?
As per the error message, you should specify a size when you create an array. That size determines how many elements the array has. That said, you normally shouldn't use allocating new expressions at all. See end of the answer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.