question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
67,710,029
67,710,061
C++ Abstract class pointer in method
So I have a c++ project that I'm working on and I'm trying to understand an other guys code but all I get are errors and confusion about c++ abstract classes. So What I have is a header file a cpp file and a main program. I want to create an abstract class pointer and then pass it to a method that initializes it to a s...
In main you have uninitialized pointer a int main() { A* a; parse(a); a->foo(); } So this statement a->foo(); results in undefined behavior. As for the function parse void parse(A* a){ a = new B(); a->foo(); } then it deals with its local variable a. Changing the local variable does not affect the origin...
67,710,057
67,710,217
How exactly remove_if() works?
I have referred many resources but unable to understand the part about how exactly it modifies the elements in the container. I have written some code to try to understand, can anyone explain what is happening? #include<bits/stdc++.h> using namespace std; bool test(char c) { return (c=='a'); } int isPalindrome(s...
It's std::remove_if, not std::move_if. It simply removes all elements that return true from the test function. Now, why the extra bs? Well, you're not supposed to be seeing them. std::remove_if returns an iterator marking the new end of the sequence, and you're supposed to use the return value to resize the container a...
67,710,084
67,710,187
Shared global variable with DLL not working
I'm trying to get some code that works on the Mac to work on Windows. The code involves sharing data between a DLL, a static library and the main program. I suspect the problem arises because of the differences in the way that Unix and Windows handle global variables (see, for example, the answers here). However, I hav...
add export modifier to class definition and export the whole class. In dll and lib build define QUERY_DECLSPEC=export , in exe build as import : class QUERY_DECLSPEC Marina { public: static Marina* get_marina(); protected: static Marina* marina_instance; };
67,710,449
67,710,619
What is the problem about static pointer?
I've just started learning OOP. I want to create a LinkList of BookList and use Singleton design pattern to create a unique object "library" to manage this BookList, but there is problem when initializing BookList. class Library { public: static Library* library; static BookList* pHead; static int i; static int getNewI...
Seems like you didn't define pHead - you just declare it. Try to add the following code in your implementation file (.cpp / .cxx): BookList* Library::pHead = new BookList();
67,710,598
67,710,661
C++ recursion causing segfault?
I had my student write this code today and it segfaults and I dont quite understand why. The problem is counting letters for English pronouncation of numbers. Its one of earliest Project Euler problems. Is there a problem with recursion or something? #include<iostream> using namespace std; int dlugosc(int x) { if(...
The recursion does not exit for the input x=110. You can check this quickly via gdb or by hand: if(x < 1000) return dlugosc(x-x%100) + dlugosc(x-x%10) + dlugosc(x%10) + 3; Since x - x%10 is x if x is divisible by 10, the second term (dlugosc(x-x%10)) will recurse infinitely for x = 110.
67,710,899
67,739,012
how to extract the foreground from vtkWindowToImageFilter?
I'm integrating vtk with qt, i have vtkWindowToImageFilter with input set to vtkGenericOpenGLRenderWindow, how come i extract the image foreground only? vtkWindowToImageFilter *w2if = vtkWindowToImageFilter::New(); w2if->ReadFrontBufferOff(); w2if->SetInput(renderWindow); w2if->Update(); vtkImageData *img = w2if->GetOu...
My recommendation is to render everything again except for the background. Something like the following auto oldSB = renderWindow->GetSwapBuffers(); renderWindow->SwapBuffersOff(); // Hide the background (set visibility to false or whatever) ... auto windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New()...
67,711,234
67,711,370
Why class can be treated as std::function<float()> but shared_ptr cannot be treated as std::shared_ptr<std::function<float()>>
There was some code that was able to treat a class that implements operator() as an std::function. I then tried to do the same but using shared_ptr: #include <functional> #include <memory> class WhiteNoise { public: WhiteNoise() {} float operator() () { return 0; } }; int main() { //fails ...
Why I can treat WhiteNoise as std::function<float()> but not shared_ptr<WhiteNoise> as shared_ptr<std::function<float()>> For a similar reason why an int can be assigned to a double, but an int* can't be assigned to a double*. Because there is a defined conversion from int to double, but there is no defined conversi...
67,711,312
68,631,300
GoLang(cgp) http.Client get request hangs from Linux daemon process
I have written a simple GoLang function which makes HTTP GET request using http.Client and prints the response string. I then exported it as C function in .so file using following command. go build -o libapp.so -buildmode=c-shared libapp.go Then using this .SO and .h, called exported Go function from my C test program...
When using cgp shared library in your C/C++ program on linux and if you are calling these functions from forked process then make sure you should consider below points. Do not statically link the shared library, instead load it dynamically using dlopen, dlsym, dlclose. Make sure while doing above you are not providin...
67,711,319
67,713,870
C++ How do I add an integer into a variable from a array using a another array
I know, the question is really complicated. Believe me, I am too. But I think a better programmer than me should know the solution. I have the following: int cash[5] = {90000, 50000, 50000, 20000, 0}; int bankaccounts[3]; int dicenumberforeachplayer[3] = {6, 3, 9}; //Every indice is a player, so dicenumberforeachplayer...
Modern C++ approach. There are no Magic numbers. Every thing is governed by the size of its respective array. #include <algorithm> #include <iostream> int main() { int cash[5] = {90000, 50000, 50000, 20000, 0}; int bankaccounts[3] = {}; // added initializer to zero accounts int dicenumberforeachplayer[3] =...
67,711,456
67,711,532
How to initialize a reference member variable inside a member function & access it inside other member functions - C++
The usual method one'd use for normal variables (declaring outside the member functions & initializing inside a member function) doesn't work, as reference variables need to be initialized & declared in same line. #include <iostream> using namespace std; class abc { public: int& var; void fun1 (int& temp) {va...
I think this is the best you can do. #include <iostream> using namespace std; class abc { public: int& var; abc(int& temp) : var(temp) {} void fun2 () {cout << abc::var << endl;} }; int main() { int y=9; abc f(y); f.fun2(); return 0; } A reference is a constant thing — it refe...
67,711,481
67,723,562
Can a function template deduce a container's value type?
Suppose I define the following function template that removes an item from the given set if the specified function returns true for that item. template<typename TYPE> int removeItems( QSet<TYPE>& set, const std::function<bool (const TYPE&)>& shouldRemove) { int numRemoved = 0; auto iter = set.begin(); ...
I ended up going with something based on the answer provided by Frank and the comment posted by StoryTeller - Unslander Monica. The former provided a solution that handled more than just QSet, while the latter provided a solution that was simpler overall. template<typename ContainerT, typename Pred> int removeItems(Con...
67,712,341
67,712,732
Is it legal to have a C++ struct member point to another member inside it
Say I have a struct like this. Is it legal C++ to have a member of the struct point to another member inside it? How are these stored? struct Foo { int m1{}; int m2{}; int* pint{}; std::string str{}; const char* pstr{}; }; I'm setting the members first, and then the pointers. Is this legal? Foo a {...
Based on the comment no, the members always point to other members, if at all. I would suggest changing the member variables pint and pstr from being pointers to objects to pointers to member variables. struct Foo { int m1{}; int m2{}; std::string str{}; int Foo::* pint{nullptr}; std::string Foo::...
67,712,610
67,712,709
How to pass a value from a thread to main in c++
I am a complete beginner in OS. The problem I am having is that I want to receive a value from a thread into the main process. A garbage value is printed in the main. Please elaborate so I can know my mistake. Here is my code: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <iostream> #include<strin...
Try: void *thread_1(void *arg) { int value = *((int *)arg); cout<<"Value in thread: "<<value<<endl; int new_val = 345; pthread_exit(&new_val ); } int main(int argc, char* argv[]) { int *temp=15; void *return_val; pthread_t t1; pthread_create(&t1, NULL,thread_1,(void *)temp); pt...
67,712,888
67,713,497
Walk over variants that share the same member and get it?
In the example below, is it possible to create a function getX that walks over the variant cases and get the x variable? #include <variant> class A { int x = 0; }; class B { int x = 1; }; class C { int x = 1; }; std::variant<A, B, C> variant; One obvious solution would be: int getX(std::variant<A, B, C...
That's a "visit". You can do this: #include <variant> struct A { int x = 0; }; struct B { int x = 1; }; struct C { int x = 1; }; std::variant<A, B, C> var = A{}; int main() { int n = std::visit([](auto & obj) {return obj.x;}, var); } Note, passing visit a generic lambda (taking an auto parameter)...
67,712,928
70,537,118
A template constructor that never can be called GCC
In the following snippet GCC decides to call the default constructor instead of the copy constructor. The constructor has a template argument, which is not used, therefore the template argument type can not be deduced. Yes the compiler generates a default copy constructor and calls it but it seems like a better behavio...
The text Default constructor comes from the line: Test1< Test< int > > mm;. It's not "instead of" anything. The line Test1< Test< int > > mm1( mm ); calls the copy-constructor, which is implicitly defined since you did not define one or do anything to suppress generation of such. The implicitly defined copy constructo...
67,713,028
67,713,706
C++ vector push_back empty braces
I've seen code like struct A { int m; }; vector<A> vec; vec.push_back({}); My question is: What's the difference between vec.push_back({}); and vec.push_back(A{})? Why can we omit A in A{}?
What's the difference between vec.push_back({}); and vec.push_back(A{})? There isn't any, in this case. Why can we omit A in A{}? You are instantiating a vector to hold A elements. Thus its overloaded push_back() methods will accept const A& and A&& input parameters. Modern C++ standards provide initialization ru...
67,713,034
67,721,921
Accessing a nested class member from another nested class (C++)
I have a class Enclosing, that contains PImpl class. The declaration of the Enclosing is in all_includes.h file and it's definition is in enclosing.cpp. I can not change that. PImpl is defined in enclosing.h. I want to add a Nested class into the Enclosing and I want to be able to access from it a member of a PImpl. Is...
While compiling main(), compiler can't figure out the details of class Nested. This is because there is only a forward declaration of class available. How will the function signature be verified? Try including the other header file. This is what I get: ./main PImpl constr: 34 Enclosing constr: 17 Nested constr: 22
67,713,327
67,714,073
segmentation fault python main.py
I wrote a c++ module witch should be imported into Python. Below are both Codes, the C++ part and the Python part. The C++ function method_sum should return the double of a value to python. module.cpp: #define PY_SSIZE_T_CLEAN #include <Python.h> static PyObject *method_sum(PyObject *self, PyObject *args) { const in...
I changed method_sum to the following and main.py prints 36 instead of segfaulting. static PyObject *method_sum(PyObject *self, PyObject *args) { int prop; if (!PyArg_ParseTuple(args, "i", &prop)) return NULL; int result = prop + prop; return Py_BuildValue("i", result); } The following also works and prop is...
67,713,527
67,713,628
Converting an iterative function to a recursive function without changing parameters
I want to convert the iterative template function getSmallest into a recursive function without changing anything in main (no changing function parameters etc.) because in class we are being taught to always keep the public interfaces of our functions the same (so if we work in a big project, we don't start changing th...
There are three conditions: The array has no elements. The array has 1 element. The array has more than 1 element The first condition we can return -1, for the second condition we return the index of the first element, and for the third condition we compare the current minimum with the minimum element found from the ...
67,713,792
67,714,138
How to return a member that is defined in all alternatives of a std::variant, even if the members are different types?
Is it possible to get a variant's member called x even if it has a different type in each alternative? #include <variant> class A { int x = 0; }; class B { int x = 1; }; class C { bool x = false; }; std::variant<A, B, C> variant = A{}; template<typename R> R getValue(std::variant<A, B, C>& variant ) { ...
With the signature and template of your getValue function, you would actually need to manually decide the type of R when calling it. So in main, you would call it like: std::cout << getValue<int>(variant); // prints 0; And if that is what you intended, then you can simply cast the .x to type R: template<typename R> R ...
67,713,901
67,713,932
How to check during compilation that GCC has at least C++17 running?
How do I check during compilation that GCC (or any other compiler) has at least C++17 running? Can you give a minimal preprocessor snippet that emits an error if the version is below C++17? I presume this can be built from __cplusplus and the #error directive.
#if __cplusplus < 201703L #error "C++17 or later is required!" #endif
67,714,027
67,714,040
How to display a dynamic array with a for loop in c++
I am trying to display a dynamic array to check my inputs using a for loop and without any vector (I'm still a beginner so I don't know what it means yet and it's a class assignment). I am also trying to implement classes and objects. Here's my code: #include <iostream> using namespace std; class Set { private: in...
You are allocating arr before you initialise size. As a result, size has an indeterminate value at that point which explains your program's unpredicatable behaviour. Solution: allocate arr after reading size. Better yet, use std::vector.
67,714,498
67,714,539
Why type deduction of function parameters are prioritized over the types from template?
Lets have a look at the simple example of enable_if usages template <bool, typename T = void> struct enable_if { }; template <typename T> struct enable_if<true, T> { typedef T type; }; Here it is expected that y would be int, since T is our "enabled" type. template <typename T, typename Y = typename std::enable...
Default template argument is used only when template argument isn't specified explicitly and template parameter can't be deduced. For this case, Y could be deduced from 14.3 as double, then default argument won't be used. Similarly, in the 1st sample you can also bypass the check of std::enable_if by specifying templat...
67,715,025
67,731,956
How to calculate the area of two circles' intersection?
The topic link: https://codeforces.com/problemset/problem/600/D For the question, I'm wrong answer on test28, which could look like this: correct answer:119256.95877838134765625000 my answer: 120502.639190673828125 I guess it is caused by calculation accuracy, but I don't have evidence. Maybe algorithm itself is faulty...
I used Wolfram Alpha to check your formula, so I think you're seeing catastrophic cancellation rather than an accumulation of small errors. I'd use William Kahan's formula to compute the triangle area, like so: #include <algorithm> #include <cmath> #include <iostream> #include <limits> typedef long double ld; struct C...
67,716,196
67,724,464
best practice for getting polymoprhic behavior for one data member of an abstract base class
I would like to know what would be a good approach, from a software design standpoint, to a situation where each derived class should have a different type of polymorphic data member. In more detail: I'm writing a library that has an abstract base class Base that users of the library will inherit from. for one member o...
EDIT Following the suggestions of the OP, I replaced the example with a fully runnable one I would make the interface difficult to be misused: #include <memory> #include <list> #include <iostream> struct BaseMember { virtual void do_stuff() { std::cout << "BaseMember::do_stuff" << std::endl; } ...
67,716,395
67,717,362
Issue with NULL and 0 behaving the same way
I was working on a class : #include <iostream> #include <list> using namespace std; class Int{ list <int64_t> data; bool sign; public: Int(int64_t val = 0) : sign(false) { cout << "Int(int) called\n"; } Int(const char* str): sign(false) { cout << "Int(const char* called)\n"; } }...
As an alternative to the other answer, you can make a template constructor that accepts any integral type. This would resolve the ambiguity and additionally work for any integral type or literal. #include <iostream> #include <list> using namespace std; class Int{ list <int64_t> data; bool sign; public: tem...
67,716,933
67,719,762
how to set an event callback for a domain lifecycle
I'm following this document and I'm using qt to implement this event #include <QCoreApplication> #include <QDebug> #include <libvirt/libvirt.h> void domainLifecycleCb(virConnectPtr conn, virDomainPtr dom, void * opaque) { qDebug() << "test"; } int main(int argc, char *argv[]) {...
There is a function that needs to be called in a loop to keep the connection alive #include <QCoreApplication> #include <QDebug> #include <libvirt/libvirt.h> #include <QThread> void domainLifecycleCb(virConnectPtr conn, virDomainPtr dom, void * opaque) { qDebug() << "test"; } i...
67,717,188
67,717,219
__thread c++ memory leak
I have a class A like this: class A { static __thread Arena * arena; } if one thread is destroyed or just quit , will the memory which arena take will be released?
The memory used by arena will be released but whatever it is pointing to won't be freed. Use c++11's thread_local with a smart pointer instead e.g. class A { thread_local std::unique_ptr<Arena> arena; }
67,717,517
69,840,096
Why doesn't `static_pointer_cast` work with ADL, but requires explicit `std::`?
Consider // https://godbolt.org/z/z5M9b9jzx #include <memory> #include <cassert> struct B {}; struct D : B {}; int main() { std::shared_ptr<B> b = std::make_shared<D>(); auto d = static_pointer_cast<D>(b); assert(d); } I'd've expected the unqualified call to static_pointer_cast to resolve to std::static_...
https://en.cppreference.com/w/cpp/language/adl Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a function template with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is ...
67,717,779
67,717,850
error: no matching function for call to ‘ope::ope()
#include <iostream> using namespace std; class ope { private: int real, imag; public: ope(int r, int i){ real=r; imag=i; } ope operator + (ope const &obj) //operator overloading { ope temp...
The line ope temp; requires a parameterless constructor (a.k.a default constructor), but ope has only a constructor that requires two parameters. You might as well use the parameterized constructor here: ope operator + (ope const &obj) //operator overloading { ope temp(real + obj.real, imag + obj.imag); re...
67,717,801
67,718,408
Count Leaf Nodes In a Generic Tree (Recursively)
I am trying to make a C++ program to count the number of Leaf Nodes in a generic tree using a Recurisve approach. here is my code: int countLeafNodes(TreeNode<int> *root) { if (root = NULL) { return 0; } int total = 0; if (root->children.size() == 0) { return 1; } for (in...
There is a problem in your countLeafNodes function. if (root = NULL) { return 0; } Hope you find the error.
67,717,803
67,717,965
Program accepting input from stdin but not from terminal
Here is my program #include <iostream> using namespace std; class Student { string name; public: Student(string input) { name = input; } Student() { name = "Unknown"; } void get_name() { char c; while (getline(cin, name)) { for (int i ...
Change this line: while (getline(cin, name)) Into if (getline(cin, name)) May works as you expected. You haven't broken out the loop, so it's always waiting for console input. Or you can send an EOF in the console, see this question. Full program: #include <iostream> using namespace std; class Student { string nam...
67,717,951
67,718,827
C++ Syntax error in header using class from another header
EDIT: My IDE was giving me a bad error message and because I was going through a major refactor, there were so many error messages on compile that I didn't read through them all, naively assuming that my IDE would know the problem. The problem was that the Font and Text headers referenced each other, and the compiler t...
You have a problem because the headers include each other, not despite it. Remember that #include is a very primitive mechanism that literally only inserts the contents of a file in a certain place. Take this simplified example: A.h: #ifndef A_H #define A_H #include "B.h" class A { B* b; }; #endif B.h: #ifndef B_H #...
67,718,093
67,718,511
Move constructor for a list of Person objects
I am writing a simple code, in which I have a list of objects of class Person. The Person class class Person { private: std::string name; std::string surname; int year; public: Person(const std::string& personName, const std::string& personSurname, ...
inside the move constructors, is the use of std::move correct? Yes. Particularly in the first line of code of list::insert This is correct, too. Note, however, that there are two minor things I would like to point out. First, there is no need to manually define the move constructor for Person. If your class doesn't...
67,718,420
67,718,443
Pass by reference and global variables
I am learning about functions, references and global variables. I have the following code: #include <iostream> using namespace std; int x; void f(){ x = 2;} void g(int &x){ f(); } int main() { int x=5; g(x); cout<<x; } Why don't I get 2 as output? Since x chan...
The function void f() acts on the global x. The parameter passed to void g(int&) is not used. That global x is shadowed by the automatic x defined in main(). Write std::cout << "local " << x << " global " << ::x; to see what happens to the two variables.
67,718,661
67,735,469
Sort string array with sort, error reported
Both problems are solved when I change "<=" to "<": it worked! I don't know why, can someone answer me? Thanks!!! The first problem code: #include <bits/stdc++.h> using namespace std; int main(){ string s[30]; int n = 20; for(int i = 0; i < n; i++){ s[i] = "3"; } sort(s, s + n, [](string a...
You should use '<' for ascending sort, but you can use <=. The key is: comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second. std::sort So <= will satisfy the requirement, (if and only if there ...
67,718,918
67,718,934
How can I make float numbers display -0 also as 0?
If I divide a float 0 by a negative value I get displayed -0 which is inconvenient. How can I get rid of this issue? float a = 0; std::cout << a / (-1); I've tried to check if a number is equal with -0 and if that condition were true, to multiply the variable by -1. This doesn't work because 0 is equal to -0.
Writing a + 0.0f gets rid of the signed zero for a float type a. (This is defined by IEEE754 and is a standard trick well-known to numericists.) So if you have an expression that might yield a signed zero, append 0.0f to the end: std::cout << a / (-1) + 0.0f;
67,719,578
67,848,102
How can I change the number of errors GCC displays without invaliding the CMake cache?
I have a C++ project that I build using GCC and CMake. Generally I like to compile with -fmax-errors=1. My normal workflow is to fix the first error and then rebuild since subsequent errors are often caused by the first one. But unfortunately, with C++20, an error involving a constraint failure is often treated as mul...
At the advice of Marc Glisse, I gave the approach that I hypothesized in parentheses at the end of the question a try. This in fact works quite well. I now have a Python script called invoke_compiler.py in the top-level directory of my project. I point CMake to the script in the usual way in which one specifies a C++...
67,719,924
67,719,948
How to make a function that takes in a std::string parameter that will return the amount of anything surrounded by whitespace
I want to create a function that takes in a std::string parameter and returns an int of the amount of words in it. Like this: int countWords(std::string){ // code... return amountOfWords; }
Write a function stub: int stub(const std::string& s/*don't deep copy the string*/) { return function_you_found_online(s.c_str()); } The function c_str() returns a const char* to the first character in s. Using function stubs to wrap third party resources also has the advantage that you can switch out the resource...
67,720,158
67,720,532
TLE whileusing hashmap but not while using map[256]={}
I am doing this code and when I am trying to solve this using a hashmap like unordered_map<char,int> m I am getting TLE (Time Limit exceeded), but whenever I am using the hashamp like this map[256]={0} then my code runs fine. Why is this happening? Isn't the unordered_map works the same way as an array does with O(1) a...
unordered_map is asymptotically O(1) but in real time it is often much slower than an array. This is for several reasons. Hash functions take some time to compute which are not needed for an array and you need to handle hash collisions which can be very expensive in comparison. An array is contiguous memory which reduc...
67,720,198
67,720,809
How to upgrade libstdc++.so on Colab runtime?
I would like to run on Colab a C++ library which requires a version of libstdc++.so which is newer than the one provided by the default g++ 7.x installed on Colab. Such requirement is due to C++17 features not supported by g++ 7.x. In order to do so, I install a recent g++ compiler (and corresponding libstdc++.so) from...
To install and use recent libstdc++ do: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt install libstdc++-9-dev. Installed include files are inside /usr/include/c++/9/ and /usr/include/x86_64-linux-gnu/c++/9/. Installed binary library files (.a/.so) are in /usr/lib/gcc/x86_64-linux-gnu/9/. You can list i...
67,721,164
67,721,402
Replacement for lookbehind in std::regex
I need a regex to match tokens for a syntax highlighter, which should match full words when surrounded by non-alphanumeric characters or string boundaries. The regex I initially came up with is: (?<=[^\w]|^)TOKEN(?=[^\w]|$) Where TOKEN is the token I'm searching for. This works in regex testers, but c++'s regex doesn'...
The pattern is missing a closing ] at the end, and \w also matches \d You might use an alternation asserting either the start of the string, or a position where \b does not match and assert not a word char to the right. (?:^|\B)TOKEN(?!\w) Regex demo After the update of the question, you can write (?<=[^\w]|^)TOKEN(?=...
67,721,174
67,721,278
How do I understand how std::make_shared works?
I came across an elegant line of reading a binary file into a vector like this (that works): std::ifstream ifs("myfile.bin", std::ios::binary); std::vector<char> buffer(std::istreambuf_iterator<char>(ifs), {}); Instead since I want my vector to be a shared pointer I write: std::ifstream ifs("my...
This will work: std::ifstream ifs("myfile.bin", std::ios::binary); auto sp = std::make_shared<std::vector<char>>(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>{}); This is because you are using this variadic template: template<class T, class... Args> shared_ptr<T> make_shared( Args&&... args )...
67,721,761
67,721,813
How do you compare strings as arguments?
I am trying to write a programm that reads the surname introduce and gives back the info of the student (birthdate, group, etc). The compiler does not recongize the == operator, I guess it doesnt know what to compare, either the address or the value?(I would appriciate an explanation) I read similar cases and they sugg...
If you have a struct like this for example struct st { std::string name; int age; }; Then you would want to compare the fam to that member of your struct if (student[i].name == fam) So now .name is the corresponding std::string that you are trying to compare. Otherwise you are trying to compare a std::string ...
67,721,800
67,721,934
2D Vector initialization fails for values greater than 41260 in C++
I noticed that when I increase the dimension of a square 2D vector array, I start to get Process finished with exit code 137 (interrupted by signal 9: SIGKILL) I was curious as to why that might happen and whether the first number of rows and columns which fails may give me more information (one would be expecting a p...
actually you are allocating very big vector(at least 42161 * 42161 * 4 byte=7.1 GB) in stack which is cause you receive sigkill(i think more like std::bad_alloc) because you don't have enough memory i think it will also fail if you allocate on top of the heap. you should allocate memory exactly the size what you need. ...
67,721,962
67,722,988
why is std::terminate not called when throwing in my destructor
I'm trying to "see" the call to std::terminate() when throwing from a destructor with the following code: #include <stdexcept> struct boom { ~boom() { throw std::logic_error("something went wrong"); } }; int main() { boom(); } compiled with g++ and run the code: # ./a.out terminate called afte...
You are running into the as-if rule. C++ compilers are allowed to essentially rewrite your entire program as they see fit as long as the side effects remain the same. What a side effect is very well defined, and "a certain function gets called" is not part of that. So the compiler is perfectly allowed to just call abor...
67,721,983
67,724,163
Proper Cleanup when using chained WndProcs
When building a chain of WndProcs using SetWindowLongPtr, we store the parent WndProc (the one that has less importance in the chain), so we are able to restore it and call it, like so: LONG_PTR oldProc = SetWindowLongPtr(hWnd, GWL_WNDPROC, &myWndProc); WndProc myWndProc(HANDLE hWnd, ...) { return CallWndProc(oldPro...
Is there something else where the WinAPI can help fixing this problem? Yes, actually. This is exactly the kind of situation that SetWindowSubclass() was introduced to address. Let it handle the chaining and unchaining for you. Don't use SetWindowLongPtr(GWLP_WNDPROC) at all anymore. See Safer subclassing and Subclass...
67,722,189
67,722,259
What happens after C++ references are compiled?
After compilation, what does the reference become, an address, or a constant pointer? I know the difference between pointers and references, but I want to know the difference between the underlying implementations. int main() { int a = 1; int &b = a; int *ptr = &a; cout << b << " " << *ptr << endl; // ...
The pedantic answer is: Whatever the compiler feels like, all that matters is that it works as specified by the language's semantics. To get the actual answer, you have to look at resulting assembly, or make heavy usage of Undefined Behavior. At that point, it becomes a compiler-specific question, not a "C++ in general...
67,722,327
67,722,918
pugixml - iterating over specific nodes
I have a xml document with a node which has children nodes but I want to iterate over specific nodes which names are stored in the array, for example: const char* childrenNodes[]={"childNodeA", "childNodeC", "childNodeK"}; I can use next_sibling function which takes as an argument the element of the above array. Do yo...
There are two overrides of next_sibling xml_node next_sibling() const; xml_node next_sibling(const char_t* name) const; You're concentrating on the second one. Rather use the first one that doesn't take a parameter, and then just check if the node name is in the array pugi::xml_node node = root.first_child(); for (; n...
67,722,527
67,723,199
Why [[no_unique_address]] attribute doesn't work in some cases?
I'm playing around with [[no_unique_address]] attribute introduced in C++20. As far as I understood from cppreference article and dcl.attr.nouniqueaddr chapter of the Standard, this attribute indicates that the field need not have an address distinct from all other non-static data members of the class. Therefore the co...
The behavior of [[no_unique_address]] is always at the discretion of the compiler; it is never required to do anything. A compiler can ignore it in all cases, respect it in some and ignore it in others, or respect it all the time. So long as the compiler is not doing it at random (ie: it's consistent), it can do whatev...
67,722,611
67,726,166
What information can I get from a socket connected to a server using c++ and windows?
I have a server and when a client connects to the server, I want to take all the information from the client and make a struct with it. What information can I get? I know that I can get the ipv4 and port from the client, there is anything left that I can get? This is a short way of doing it: #undef UNICODE #define WIN...
There is a whole lot of information available from getsockopt. It is a superset of what the other answer claims, for example SO_BSP_STATE Returns the local address, local port, remote address, remote port, socket type, and protocol used by a socket. Since you have a TCP socket you will be particularly interested in ...
67,722,879
71,051,115
ld from other source cannot find a library
First of all by "other source" in title i mean not /usr/bin/ld Then I am so sorry for this long thread of question. I also would like to say here that any help would be appreciated peacefully. I have encountered an error during make test according to https://github.com/cliffordwolf/picorv32. I have opened an issue on g...
I had riscv32-unknown-elf- but then i installed make -j$(nproc) build-riscv32i-tools and the issue went away. Thanks @KamilCuk
67,722,938
67,726,378
C++ Gmock - WillOnce - Can you do anything aside from return a value?
I am learning gmock and wondering how I can make my mock object do something when one of the mocked methods is called. I need to mock some interfaces that make use of Qt and I am trying to get Qt and Gmock to work together. For example, I mocked a network socket interface class, gave it to a network client class via co...
You should be able to use InvokeWithoutArgs to achieve the result that you are looking for, assuming that you are using Qt 5 or greater. Your mock object should be defined as follows: class MockMySocketInterface : public MySocketInterface { Q_OBJECT public: MockMySocketInterface() { } virtual ~MockMySocket...
67,723,479
67,723,877
Best way to store large number of outputs from numerical simulations
I am developing an application in C++ where I will run a numerical simulation and somehow store the simulation results. Each simulation point will be associated with many fields (i.e. floating point numbers), and each field has to be stored with many decimals. So far, I am writing the data to a simple text file (one ro...
It's a bit orthogonal, but based on how context-dependant any answer to your question has to be, I think this is appropriate here. Considering your hesitation, I would strongly recommend adding a layer of indirection so that you can easily support various formats and/or stuff like having a dedicated file output thread ...
67,724,498
67,749,078
How does System.Net.Sockets.Socket.Disconnect disconnect from the socket?
My DLL gets injected into a program and then hooks to connect, send, recv and closesocket functions using Detours. The point is to stop the program from connecting to some server and instead communicate with my DLL directly. My recv function uses an infinite loop, just waiting for any data to send to the program. When ...
System.Net.Sockets.Socket.Disconnect calls DisconnectEx. And as the remarks say: Note The function pointer for the DisconnectEx function must be obtained at run time by making a call to the WSAIoctl function with the SIO_GET_EXTENSION_FUNCTION_POINTER opcode specified. The input buffer passed to the WSAIoctl function...
67,724,559
67,725,101
passing an unnamed object as an argument when making a new object in C++
I want to use unnamed object as an argument in constructor, but it generates the following error. I guess object name 'b2' is interpreted as function prototype or something. class AAA { private: int m_val; public: AAA(int a) : m_val(a) {} }; class BBB { private: AAA a; public: BBB(AAA &a_) : a(a_) {} }...
Firstly, this does not mean what you think it means: BBB b2( AAA() ); b2 is actually interpreted by the compiler as a declaration of a function called b2 which takes a function pointer which returns an AAA as a parameter, and which returns a BBB. For my compiler, look at the signature: So then this fails: b = b2; be...
67,725,183
67,725,302
Find an element in a binary tree
How can I search for an element in a binary tree that is not a bst? This is an example of how my tree looks 1 / \ 2 3 / \ / \ 4 5 6 7 This is what I'm doing: treeNode * find(treeNode *T, int x) { if(T == NULL) return NULL; if(x == T -> element) { return T; } find(T -> le...
You're ignoring the return values from your recursive calls: treeNode * find(treeNode *T, int x) { if(T == NULL) return NULL; if(x == T -> element) { return T; } treeNode *result = find(T -> left, x); if ( result ) // if the return value was found, this will not be NULL, so return the node ...
67,725,265
67,725,565
c++ object type array contains subobject
I have Java code using interfaces and objects. However I cannot write it with C++. Can you help me about it? There is an interface named Operation.java Here is the code. public interface Operation { int evaluation(int x, int y); } There is a class implement Operation class named Multiply.java Here is the code. pu...
First you should know that in c++ we dont have interface keyword or other thing. but interface in java it similar to c++ class with pure virtual function class Operation { public: virtual int eval(int x, int y) = 0; } which is very like interface now every class that inherit Operation must implement evaluation. in ...
67,725,541
67,725,982
Overloading functions with concepts
(I'm learning concepts and templates so correct me if I'm very wrong with something.) I have a function that takes a concept as parameter. I'm now trying to overload this function that takes a more specific concept. That would do "something more specific" or call the less specific function. template<typename T> concept...
The usual workaround for that would be a separated helper function: void somefunc(const Concept1 auto& x) { // general stuff } void somefuncSpecific(const Concept1 auto& x) { somefunc(x); } void someFuncSpecific(const MoreSpecificConcept auto& x) { if(...) { //do specific stuff } else { //do the...
67,726,019
67,732,198
Singly Linked List in C++ is not reading more than 2 nodes
Below is a simple program for insertion in a linked list, however, whenever I run the program, it reads only two input values for the list and stops further execution. Why is that? I am unable to catch the issue. /**** Defining structure of node *****/ class Node{ public: int data; Node* next; ...
The insertAtEnd needs an early return with the first node, or it will ran into a infinite loop. Node* insertAtEnd(int val) { Node* n = new Node(val); if (head == NULL) { head = n; return head; } Node* tmp = head; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = ...
67,726,208
67,726,329
Why does this compiler warning only show for int but not for string? "type qualifiers ignored on function return type"
I am a bit confused about some warnings I get when compiling my C++11 code using mingw64. This is my MWE: class A{ const string name; const int ID; public: A(string name_, int ID_) : name(name_), ID(ID_){ // initialize non-const members } const string getName() const{ret...
std::string is a class that has member functions that can be constant. If you have a constant object of the class you may apply only constant member functions. As for fundamental types like for example int then the qualifier const does not make a sense for a return value because in any case you can not change the retur...
67,726,469
67,726,779
Allocate small struct to 32 bit aligned in 64 bit system
The problem: I'm implementing a non-blocking data structure, where threads alter a shared pointer using a CAS operation. As pointers can be recycled, we have the ABA issue. To avoid this, I want to attach a version to each pointer. This is called a versioned pointer. A CAS128 is considered more expensive than a CAS64, ...
First off, a non-portable solution that limits the code complexity creep to the point of allocation (see below for another approach that makes point of use more complicated, but should be portable); it only works on POSIX systems (not Windows), but you could reduce your overhead to the size of a page (not 8 bytes, but ...
67,726,812
67,728,048
How to combine constexpr and vectorized code?
I am working on a C++ intrinsic wrapper for x64 and neon. I want my functions to be constexpr. My motivation is similar to Constexpr and SSE intrinsics, but #pragma omp simd and intrinsics may not be supported by the compiler (GCC) in a constexpr function. The following code is just a demonstration (auto-vectorization ...
Using std::is_constant_evaluated, you can get exactly what you want: #include <type_traits> struct FA{ float c[4]; }; // Just for the sake of the example. Makes for nice-looking assembly. extern FA add_parallel(FA a, FA b); constexpr FA add(FA a, FA b) { if (std::is_constant_evaluated()) { // do it i...
67,726,842
67,726,959
Passing address of a variable by reference in C++
void test(const int*& in){} int main(){ int a = 5; test(&a); return 0; } Above code does not compile saying cannot bind non-const lvalue reference of type 'const int*&' to an rvalue of type 'const int*'. It does work as expected if I make this change: int a = 5; const int *b = &a; // `const` has to be specified...
1- Why doesn't my first example work? The parameter is a reference to a pointer to const. &a - which is the argument - is a pointer to non-const. Pointer to const and pointer to non-const are different types. The argument could be implicitly converted to a pointer to const type. However, the result of that conversion...
67,727,393
67,727,443
What is __N() in this statement std::__throw_out_of_range(__N("array::at"))?
I was looking at the definition of at() function from array header file to clear some doubts. Here's the definition- reference //typedef for &value_type of array at(size_type __n) //size_type is typedef for size_t { if (__n >= _Nm) //_Nm is typedef for size of array std::_...
From their source code // This marks string literals in header files to be extracted for eventual // translation. It is primarily used for messages in thrown exceptions; see // src/functexcept.cc. We use __N because the more traditional _N is used // for something else under certain OSes (see BADNAMES). #define __N(m...
67,727,400
67,727,546
no instance of overloaded function AddSnapshotListener matches the argument list
i am trying to use Firebase cpp SDK in my win32 application. i used code from documentation db->Collection("cities") .WhereEqualTo("state", FieldValue::String("CA")) .AddSnapshotListener([](const QuerySnapshot& snapshot, Error error) { if (error == Error::kErrorOk) { for (const DocumentChange& dc : snapshot.Docum...
The documentation says the callback for Query::AddSnapshotListener takes 3 arguments, whereas your implementation accepts only two. The proper signature would be: .AddSnapshotListener([](const QuerySnapshot& snapshot, Error error, const std::string& error_msg) { // ... }); Edit: The inconsistency between the code in ...
67,728,233
67,728,666
templating a primitive in C++
I have some code with fairly complicated logic that passing around angles in both radians and degrees. All of the variables are doubles. It would be helpful to add some additional guards to prevent passing a radians to a function that requires the value in degrees. The code below uses a struct and does work but require...
A somewhat common way to do this is provide a conversion operator. Example: #include <iostream> #include <math.h> template<int N, typename T> struct AngleType { T value; AngleType(T val) : value(val) {} operator T() const noexcept { return value; } }; using AngleRadians = AngleType<0, dou...
67,728,340
67,729,616
SFML - Weird RenderTexture behaviour when resizing window
I am currently trying to recreate Chess in SFML. Generating the board normally works as intended but when I am resizing the window I get weird white borders. Before Resize: After Resize: It looks like the view is not aligned with the window properly so I think my problem is not in the board generation but how I am ha...
The problem is that you don't only need to resize the view, but also recenter it. As right now you are not doing it, the center remains where the smaller board was and the bigger view takes a chunk from the outside in the top left corner. So just change your code like this: ... else if (event.type == sf::Event::Resized...
67,728,394
67,728,655
In which situations std::dynamic_pointer_cast fails?
I'm having a problem that's driving me crazy. I made a minimum verifiable example, but it does not show the error. Let's first think about this code: class WhiteNoise: public ApplicableEffect { }; std::shared_ptr<ApplicableEffect> mod; //... std::shared_ptr<WhiteNoise> d = std::dynamic_pointer_cast<WhiteN...
Summary of the facts... WhiteNoise derives from Applicable DelayLine contains a pointer to an Applicable WhiteChorus derives from DelayLine and constructs the base class with a pointer to a WhiteNoise (not an Applicable, but derived from it) WhiteChorus.do_something() tries to cast the base class's pointer to a pointe...
67,728,456
67,728,685
Iterate over parameter pack of types
I'm trying to simplify usage of pybind11 when binding templates. For now I have a parameter pack of types and I need to call a function cl.def() (look at the code below) with each type from that parameter pack. Also there is a vector of names and each name corresponds to parameter's pack type. Here is an example: #incl...
Don't use a macro for this. Visiting a list of types is fairly straightforward with basic-ish partial specialization: #include <iostream> // This will only ever be used for Visitor<> because of the next specialization. // So it serves as the "recursion" stop condition. template<typename... Ts> struct Visitor { tem...
67,728,500
67,728,624
How to programmatically obtain adapter's IPv4/6 interface metric on Windows using C/C++ APIs?
On Win10 I can run get-netinterface in powershell to display InterfaceMetric for each interface. Is there a C/C++ Win API that would let me retrieve it programmatically? The metric can be set in adapter's TCP/IP settings:
Is there a C/C++ Win API that would let me retrieve [InterfaceMetric] programmatically? Use GetAdaptersAddresses(). See the Ipv4Metric and Ipv6Metric members of the IP_ADAPTER_ADDRESSES struct.
67,728,573
67,729,060
My insert function won't read a part of my struct
#include <iostream> #include <stdlib.h> #include <string> using namespace std; struct CourseNode { int CNumber; //course number string CName; //course name string IName; // instructor name struct CourseNode* Next; }; struct CourseNode* Start = NULL; here is where the problem starts, if i write cout<...
Welcome to Stackoverflow :D Your struct has std::string. Which is a C++ class that has a constructor. When you use malloc(), you grab memory. But that memory is not guaranteed to be initialized to any meaningful values. It will be just garbage. That means that your std::string objects' internal state will be messed up....
67,729,204
67,729,466
What is the life time of a in "auto&& a= f();" where f() returns an object by value?
#include <iostream> #include <typeinfo> class A {}; A f() { return A(); } int main() { auto &&a = f(); std::cout << typeid(f()).name() << std::endl; std::cout << typeid(a).name() << std::endl; std::cout << typeid(A{}).name() << std::endl; return 0; } It outputs 1A 1A 1A Questions are, what doe...
what does 1A mean here? (GCC on a linux box) It means that the length of the name is 1 followed by the letter. There are many rules on how to mangle a type, but it encodes its namespace, template parameter value and other things. auto && should be a forwarding reference, and in this case since f() returns an A objec...
67,729,233
67,729,726
c++ how to align output with for loop
i am dealing with a school project and when i run the program,it needs to give a organized output .i tried to align it to the right side but it clearly didn't work as it can be seen. how can i reach the expected output? code: for (int i = 0; i < 5; i++) { std::cout << i + 1 << "." << "\t" << std::setw(20) << s...
Check this out and compare it with your code. I've just added and removed few endl, added one setw(36) in else block and re-modified some space sequence for (int i = 0; i < 5; i++) { std::cout << i + 1 << "." << "\t" << std::setw(15) << std::right << "White Knight" << std::setw(15); if (i < 3) { std::...
67,730,512
67,730,626
Multiple definition with 2 header files
I am using CodeBlocks. In C++, I have 3 header files and 3 cpp files like below. Base.h class Base { public: virtual int funky(int x, int y); }; Base.cpp int funky(int x, int y) { return x+y; } FirstClass.h class FirstClass: public Base { public: virtual int funky(int x, int y); }; FirstClass.cpp int funk...
In the above code sample, you defining funky in two different cpp files but have declared in your class. So following should be the correct format: FirstClass.cpp int FirstClass::funky(int x, int y) { return x+y; } SecondClass.cpp int SecondClass::funky(int x, int y) { return x+y; } main.cpp FirstClass a; SecondC...
67,730,548
67,744,857
GNU MP: Cannot allocate memory (size=4294959136)
GMP cannot seem to allocate memory larger than this amount, despite being compiled in 64bit. I have a simple program that you can test this on, and whilst running it only seems to use up to 1500mb memory and no more. This should be able to calculate the number for even 32bit applications, however since it is 64bit, it ...
This situation is typical for using a primarily UNIX-oriented library on Windows: YMMV. Sure enough, a quick inspection reveals extensive use of the long data type (example). It's unsurprising that it doesn't work on Win32, where long is 32-bit. Win32 uses the LLP64 model, and MinGW follows that (source). Even the erro...
67,730,549
67,735,292
C++ armadillo linear algebra library linker error with GCC
I'm getting the following error with GCC >=9 and std>=11 merely by adding the header (MacOSX on MacBook Pro 2020 and armadillo installed with Homebrew and the code is compiled with standard CMake configuration) #include <armadillo> to my project. Undefined symbols for architecture x86_64: "___emutls_v._ZN4arma19mt19937...
The preprocessor directive ARMA_DONT_USE_WRAPPER disables code that uses thread_local which depends on emutls in gcc on macOS. This appears unsupported on macOS 11 (Big Sur) according to the maintainers of Armadillo. As shown here CMakeLists.txt. A related workaround is provided by the maintainers Commit 83e48f8c in fi...
67,730,750
67,730,808
Operator() crashing program on MSVC C++17 (2019)
The following code doesn't work with MSVC++ 2019, but it works on GCC compiler. #include <set> #include <string> #include <iostream> struct MyData { MyData() {} MyData(std::string keyA, std::string keyB) :keyA(keyA), keyB(keyB) {} std::string keyA; std::string keyB; }; struct Compare { bool op...
Your comparator fails to adhere to the rules for strict weak ordering, that is to say it is possible to have the following situation: a < b b < c a >= c MSVC has evidently detected this and raised an assertion failure. To fix this, you can change your comparator as follows: bool operator() (const MyData& lhs, const My...
67,731,063
67,731,275
is deleting a variable allocated in heap using void pointer a bad thing?
is there a problem with this code? I mean the delete statement. int *x = new int; *x = 13; void *ptr = x; delete (int *)ptr;
Even though you are using an explicit type conversion, the rules for static_cast apply. The relevant rule is in point 10 of the static_cast page @ cppreference.com: Conversion of any pointer to pointer to void and back to pointer to the original (or more cv-qualified) type preserves its original value. In your case, ...
67,731,116
67,732,332
How to find if there is more than one shortest path in a weighted graph?
I have an undirected weighted graph. I am using Dijkstra's algorithm to find the shortest path from the source node to the destination node. But I also want to make a bool function that can tell me if there is more than one shortest path. The code I have written till now #include<bits/stdc++.h> using namespace std; in...
You can do it with a modified Dijkstra's that keeps track of whether a node can be reached by multiple shortest paths. The simplest way is with a container of bool: vector<bool> multipath(n, false); and some logic to manage these bits: if( distTo[next] == distTo[prev] + nextDist){ multipath[next] = true; } if( dist...
67,731,445
67,734,140
I have tried to implement mergesort and am unable to find the exact problem of my code. The program shows no errors but I do not get a desired output
Tried implementing mergesort, below is code. Let me know if anything is wrong. Is there any any error in my merge function? unable to point to the exact problem in my code. Any help regarding the same would be highly appreciated. #include <iostream> using namespace std; Merge function to merge the two sorted arrays vo...
There are 2 bugs is the code: computing the mid point as int mid = start + (end - 1) / 2; is incorrect. You should instead write: int mid = start + (end - start) / 2; in the last loop in merge you increment i instead of j. Note that this loop is redundant as the remaining elements of arr2 are already at the end of...
67,731,463
67,731,840
Can't do insert in multimap
Part of the class with multimap and his parameters class cl_base { string object_name; cl_base* p_parent = 0; struct o_sh { cl_base* p_cl_base; void (cl_base::*p_hendler) (cl_base* p_ob, string&); }; multimap<void(cl_base::*) (string&), o_sh*> connects; multimap<void(cl_base::*...
Comparing two pointer-to-member-functions is harder than might at first appear. They are typically larger than normal pointers and cannot (for example) be cast to a long. Here is a custom comparator that ought to work. I have to question the validity of doing this (and maybe there are some hidden gotchas), but I gues...
67,731,839
67,732,620
Different input format for an object in C++
I have recently learned how to use cin with objects of a class. istream& operator>>(istream& aliasCin, RationalNumber& r) { double temp; aliasCin >> temp; r = RationalNumber(temp); return aliasCin; } This is my class RationalNumber, As you can see that I am taking in a double and passing it to my non-...
Yes. you can read multiple values by chaining cin >> a >> b >> c. I'm not sure how to handle the slash, this seems ok: #include <iostream> using namespace std; int main(){ int a; char separator; int b; cout << "Enter a fraction (e.g. 3/4): "; cin >> a >> separator >> b; ...
67,732,556
67,732,658
Why don't reference members refer the assigned variable on nested vectors? What's a proper way to declare an alternative way to access a class member?
I would like to declare an alternative way to access a class member (an array position specifically), as in class Foo { int a[2]; int &a_first = a[0]; }; such that any access to a_first in a Foo instance is for all purposes equivalent to accessing a[0] of that same instance. The code above works as I expected ...
The code above works as I expected Actually it doesn't: class A { public: int m{}; int &mref = m; }; int main() { A a; A a2 = a; std::cout << (&a2.m == &a2.mref) << '\n'; // output: 0 }; A reference can be bound only on initialization. Copying will copy the value, not re-bind the reference. So ...
67,732,915
67,734,306
i can't find error in this 'Inserting node at begining of list' using singaly linked list
I did this code with the help of code on Youtube/freeCodeCamp.org/data structure -using C and C++. Same code worked for tutor ,but in my PC it is not working. #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; struct Node *head; void Insert(int x) { struct No...
please add the data type struct in the 12th line, i.e. struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); Thank you for this question.
67,733,097
67,733,191
Why heap allocation uses a lot of memory than stack allocation?
I wonder why stack allocation use less memory than heap allocation? The gap between this allocation is really huge. When I use stack. It consumes around ~77MB, but when I use heap allocation. It consumes ~880MB. There is no memory leak (I guess), because after I delete this object the memory return completely (back to ...
Heap allocations are all aligned to some minimal value (see _STDCPP_DEFAULT_NEW_ALIGNMENT__). For instance, with glibc on x86_64, it is typically 16. This basically means that the heap always allocates at least 16 bytes, even if you ask for a single one. There are generally some bytes wasted. Consequently, when you all...
67,733,434
67,733,647
How to safely and properly use threads in C++?
I have a logging system for my application Now this is what i do: static void Background() { while(IsAlive){ while(!logs.empty()){ ShowLog(log.front()); log.pop(); } while(logs.empty()){ Sleep(200); } } } static void Init(){ // Som...
namespace { // Anonymous namespace instead of static functions. std::mutex log_mutex; void Background() { while(IsAlive){ std::queue<std::string> log_records; { // Exchange data for minimizing lock time. std::unique_lock lock(log_mutex); logs.swap(log_records);...
67,733,982
67,734,006
Segmentation fault while using vector<pair<int,int>>
Why this code of mine is giving segmentation fault? I am not able to get where I am going wrong, to me it seems fine. Any help will be great, thank you. #include<bits/stdc++.h> using namespace std; int main() { vector <pair<int,int>> v; int arr[5]={1,2,3,4,5}; for(int i=0;i<5;i++) { v...
vector <pair<int,int>> v; initializes v as an empty vector, it contains no elements. Then in for loops v[i]={arr[i],i}; and v[i].first lead to UB. You could use push_back or emplace_back instead. for(int i=0;i<5;i++) { v.push_back({arr[i],i}); // add element to v // or // v.emplace_back(arr[i],i); } Or mak...
67,734,233
67,734,389
Compile C++ on Windows
I'm trying to compile C++ on Windows. The command needed to compile on Linux is: g++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` EO_functions_bipartite.cpp -o extremal_bi.so I installed MinGW but when I try to compile I get the following error: g++.exe: error: python: No such file or directory g...
Assuming you have python in your path. The backtick escape thing that embeds the python -m pybind11 --includes command within the g++ doesn't work on cmd.exe in Windows. Run the python -m pybind11 --includes command on its own line in the cmd shell. Take the output of that command and substitute in into the g++ comman...
67,734,242
67,734,352
Delete list element using element pointer
I'd like to create a method that takes two arguments: List of string and pointer to list element. Next, I would like to delete the list item pointed to by the pointer. Firstly i create simple list: list<string> list_ptr = { "1", "2", "3", "4", "5", "6", "7", "8"}; I suppose that i first should check element exist: aut...
std::list has its own interface for deleting, sorting, etc: #include <stdio.h> #include <list> #include <string> int main() { std::list<std::string> strlist = {"1", "2", "3", "4", "5", "6", "7", "8"}; strlist.remove("4"); for (auto const& elm : strlist) puts(elm.c_str()); } If you want to use the iterators li...
67,734,419
67,834,156
Parameter boundaries using Eigen's Levenberg-Marquardt
I'm using Eigen's Levenberg-Marquardt implementation and wondering how to set some boundaries on the parameters which should be optimized. As I'm migrating some GNU octave programs to Eigen I expected that there might be some boundaries which can be easily provided as parameters to the module. The layout of my implemen...
I found a solution which is at least working for me. The idea is to increase the error vector once the parameters are leaving their sanity boundaries. This can be achieved by the following function: penalize(x1, x2) = 1 + (exp(x1-x1max)*b1) + exp((x1min-x1)*b1) + exp((x2-x2max)*b2) + exp((x2min-x2)*b2) b1/b2/... must ...
67,734,805
67,827,977
Using Armadillo C++ library in Swift 5
I'm trying to use Armadillo C++ library in my swift code to create sinusoidal curved arrow. Earlier it worked well with Objective C. But when I'm trying to do the same implementation in Swift, it's showing 'armadillo' file not found error. I've downloaded the file from https://github.com/gadomski/armadillo/tree/master/...
Finally I found the solution to it. Sharing the steps which I followed. We need to install the pre-built Armadillo packages to macOS which can be installed via MacPorts or HomeBrew I installed using HomeBrew. $ brew install armadillo Once it is completed, please keep a note on the installed path from the last line. ...
67,735,065
67,735,297
Vector of array fails to compile
This simple program #include <vector> int main() { using int3 = int[3]; std::vector<int3> vec( 2 ); } does not compile in the latest Visual Studio 2019 16.10.0 with stdcpplatest switch, producing the error: >C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xutili...
From cppreference: T - The type of the elements. (until C++11) T must meet the requirements of CopyAssignable and CopyConstructible. (since C++11) (until C++17) The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element typ...
67,735,112
67,735,608
algorithm in STL to sweep 2 ranges and call a function
Is there a algorithm in STL that will sweep two (equally sized) ranges and call a function for each pair of entries? std::equal() and std::transform() seem to follow this notion, but they are not that expressive when the intention is to, say, calculate the sum of difference squares of two vectors: vector<double> a = { ...
The standard library has both inner_product and transform_reduce that'll do this for you. The latter is C++17. #include <numeric> int main() { std::vector<double> a = { 1.1, 1.0, 5.5 }; std::vector<double> b = { 1.4, 1.1, 5.3 }; auto func = [](double a, double b) { return std::pow(a - b, 2...
67,735,454
67,735,617
Unknown characters while printing map of two char pointer in set
Here Is My Code set<map<char*, char*>> AllRows; static int callback(void* data, int argc, char** argv, char** azColName) { map<char*, char*> abc; for (int i = 0; i < argc; i++) { abc.insert(pair<char*, char*>(azColName[i], argv[i])); } AllRows.insert(abc); for (auto row : AllRows) { ...
The strings that the pointers in the callback function are pointing to is managed by the SQLite code, not by your program. SQLite can reuse the memory or simply free it (if it was dynamically allocated). If you need to use that data outside of the callback function you must copy them. For example by using std::string f...
67,735,459
67,735,563
Assignen a template function with Variadic arguments to a function pointer
In C++ I am trying to make forwarding wrapper that takes the first argument and calls a method on it. This ended up in the wrapper method in the given code. This works fine when calling it. However I want to assign this templated wrapper to function pointer. In my use-case the function pointer is a given and I can not ...
The problem is wrapper taking args as forwarding reference, its type would always be reference: lvalue-reference or rvalue-reference. But serialize is declared as function pointer taking i and j by-value with type int, they can't match reference type, which makes template argument deduction on Params fails in serialize...
67,735,910
67,736,268
return reference in [] operator of std::vector
Please consider this scenario. I'm creating a function for [] operator as in the std::vector whose inner body is like this: int temp; if(argument >= 0 && argument < size) { return &my_vector[i]; } else { cout << "out of bounds" << endl; //i need to return here something but this gives me an error: local var...
First of all, you are not returning a reference, but a pointer, which makes the method not very useful. Instead of vector[100] = 1; int answer = vector[100]; You would have to write *vector[100] = 1; int answer = *vector[100]; To get what you want you should return a reference not a pointer. Ie return type should be ...
67,736,066
67,737,468
Trigger checkbutton hover event from another widget
I made a custom Right-to-Left check button widget using a Gtk::CheckButton without the label and a Gtk::Label inside Gtk::EventBox. The reason I went this way instead of simply calling set_direction(Gtk::TEXT_DIR_RTL) is that I want to manually specify the alignment for these widgets. I've figured out activating/deacti...
One way is to use set_state_flags() and trick the visual output of your Right-to-Left checkbutton when the label is being hovered. First, you need to enable these two masks for eventbox to capture enter and leave event: Gdk::ENTER_NOTIFY_MASK Gdk::LEAVE_NOTIFY_MASK eventbox.add_events(Gdk::ENTER_NOTIFY_MASK | Gdk::LE...
67,736,146
67,736,471
static vector much slower than global in recursive function
I want to use static variables instead of global variables, found it was much slower than before. The original code took less than 0.01 seconds, now it takes about 1.6 seconds. I am not familiar with vector. Is there a simple way to get the same performance as before? #include <cstdio> #include <cmath> #include <ctime>...
There are two factors, The minor factor is that every time the function enters, the program checks whether the variable has been initialized (and this must be thread safe) The major factor is that you're returning a copy of the vector from every call, even though you ignore almost all of them. (There are 21,845 vector...
67,736,200
67,736,255
How can I allow both floating-point and integer types but disallow bool in a template
Say I have some numerical class, with a constructor that allows a "number" (quotes on purpose). Inside, it is stored as a floating-point value, so I want only a number as argument, so I denied instanciation on other types than floating-points: template<typename T> struct MyClass { MyClass( T value ) : _v(value) {...
You can check bool with std::is_same. E.g. MyClass( T value ) : _v(value) { static_assert( ( std::is_floating_point<T>::value || std::is_integral<T>::value ) && !std::is_same<T, bool>::value, "only numbers!" ); }