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
64,995,447
64,995,475
How do i make a class with same constructor with different name?
I have a code here which creates a moveknight class object. I have two object with same name called knight, but each of these knight have different string name: int main() { int x; //Tree tree(1000, 1000); // Node start(3,3); //Node end(2,2); moveknight knight("Sigma"); moveknight knight("Lamda"); ...
I have two object with same name called knight That won't work. You can't have multiple variables with the same name in the same scope. You need to rename them, eg: #include <iostream> int main() { int x; //Tree tree(1000, 1000); // Node start(3,3); //Node end(2,2); moveknight Sigma("Sigma"); ...
64,995,724
64,995,897
Additional steps required for including header files using VC++?
I've recently moved my project to a new home, but(of course) the build is failing. In the picture below 1 represents the old directory that these files were located in and 2 represents the new include directory I've added. I've also copied and pasted the files into their new home... Are there additional steps that ne...
You are building Debug configuration, but show properties for Release. Make sure the additional include is the same. Also, you masked the path to the Documents folder; is the path the same?
64,995,728
65,002,733
Exception *read access violation* How should I properly delete array of lists of pointers?
so I have this problem with my hashtable whenever i try to delete all elements from my hashtable and then after that again add new elements to it, there will pop some exception read access violation and its caused when i add new elements to hashtable, and am pretty sure cause am clearing it wrong.My clear method looks ...
changed clear() into this : void clear() { delete[] this->arr; this->maxSize = 256; this->arr = new list<T>[maxSize](); this->currentSize = 0; } now is way faster and no exceptions thank you all for feedback.
64,995,771
64,995,914
C++ Difficulty with class objects
I am brand new to C++ and pretty new to programming overall. I am working on a class assignment in C++ to manage a DVD store with 10 DVDs. The goal is to print out information about each DVD by using abstract data types and using an array of ten DVD instances by pulling from a text file. So far, I have been able to imp...
You want to have either: Dvd myDvds[10]; or std::vector<Dvd> dvdVect(10); Then you can access them with myDvds[i] or dvdVect[i].
64,996,274
65,002,881
How do I change the appearance of messages in OMNeT++?
In the manual it says the following: To customize the appearance of messages in the graphical runtime environment, override the getDisplayString() method of cMessage or cPacket to return a display string. I don't understand what this means. I have custom images and I was able to change the icon of nodes with the line...
Add this to your .msg file. This will enforce the generation of the getDisplayString() function in the *_msg.h file. const string displayString @override = "i=misc/train";
64,996,400
64,996,482
How do I implement a begin() member function in my custom data structure?
I'm trying to create my own data-structure that can determine if a value is an element within it in O(1) time with a hash-map. I'm working on adding more member functions so that it's more similar to the STL containers. Here's what I currently have that's relevant to the problem: template <class T> class setfind { pri...
I see several issues with your code. You don't need the _size member at all, get rid of it and use _set.size() when needed. In your constructor, while (*beg != *en) needs to be while (beg != en) instead. Or better, just geet rid of the manual loop altogether and use the std::unordered_map constructor that takes an ite...
64,996,619
64,996,835
How to kill a process with kill function in c++?
I'm learning processes in Linux. I need to write a task which operates processes(Create, kill, change nicety, and suspend). I've already written that program, but kill and suspend are not working. To fix that I launched that program as a superuser, but this didn't help me. What do I need to do to fix that bug? #include...
I eliminated the unrelated "stuff" and came up with this: #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <cstring> #include <unistd.h> #include <sys/resource.h> #include <stdlib.h> #include <string> int main(int argc, char **argv) { if (argc != 2) { std::cerr << "Usage: kil <pr...
64,996,840
64,996,871
C++ : Headers Including each others causes an Error "class has not been declared"
I'm relatively new to C++ and I'm facing this issue the whole day and it is really annoying . Assuming I have these 2 classes in seperate files a.hpp : #ifndef A_H #define A_H #include "d.hpp" #include <iostream> class CPlay { public: CPlay() = default; CPlay(int m_money) { money = m_money;} void gameOn(in...
To break the circular dependency, you need to add a forward declaration of the depended-on classes to each of your header files, like this: #ifndef A_H #define A_H #include <iostream> class CRoom; class CPlay { ... and: #ifndef D_H #define D_H #include <iostream> class CPlay; class CRoom { ... Note that this allo...
64,996,845
64,996,895
Remove elements from adjacency list C++
This is the way that I define my adjacency list: vector<vector<int>> adj; I want to iterate through the entire adjacency list and find if a certain value exists. If that value exists in the adjacency list, I want to delete it. I have tried 2 approaches: Approach 1: for(auto elem: adj){ for(auto ind: elem){ ...
This: auto it=elem.find(num); doesn't work because std::vector doesn't have a member function named find. To find an item in a vector, you can use std::find instead: auto it=std::find(elem.begin(), elem.end(), num); if (it!=elem.end()) elem.erase(it); Two points: if the elements in the adjacency list aren't in any...
64,997,028
64,997,149
Why is returning None when of return type option<T> not return the null pointer when T is not a reference
The FFI section in the nomicon states that The most common type that takes advantage of the nullable pointer optimization is Option<T>, where None corresponds to null. So Option<extern "C" fn(c_int) -> c_int> is a correct way to represent a nullable function pointer using the C ABI (corresponding to the C type int (*)...
nullable pointer optimization. If the Option contains a pointer type, such as Box then the optimisation can be applied. A u8 cannot be null and is not a pointer, but a Box<u8> is an owned pointer to a u8, so the optimisation works there. More generally, this optimisation is called "niche-filling" which also applies t...
64,997,030
64,997,237
Compute binomial coefficient module prime p in C++
Problem statement: Compute the binonimal coefficient C(n,k) mod p. Here p is a prime. I've done a bit of research online but I still don't understand why the following code works for this problem: factorial[0] = 1; for (int i = 1; i <= MAXN; i++) {//compute factorial factorial[i] = factorial[i - 1] * i % m; } long ...
The factorial formula C(n, k) = n! / (k! (n-k)!) can be rewritten as C(n, k) k! (n-k)! = n!. Then: taking mod p on both sides:  C(n, k) k! (n-k)! ≡ n! mod p; multiplying by the modular inverse:  C(n, k) k! (n-k)! inverse(k! (n-k)!) ≡ n! inverse(k! (n-k)!) mod p; simplifying a inv(a) = 1:  C(n, k) ≡ n! inverse(k! (n-...
64,997,208
65,000,762
/bin/sh: cc: command not found
I am running MingW32 on Windows 10. When I try to compile my programme using the command: $ make -f Makefile cc -g -Wall -o runScript.exe abc.o def.o ghi.o -lgdi32 -lcomdlg32 #-mwindows I get an error: /bin/sh: cc: command not found make: ***[runScript.exe] Error 127 Will appreciate a solution to this.
The trick with Makefile not finding cc when using gcc is usually setting CC=gcc.exe (and if needed CXX=g++.exe, you can also specify the full path if you like) either as environment variables or on the make command line like this: make CC=gcc.exe (you shouldn't really need to add -f Makefile as that's the default).
64,997,959
64,999,018
Warp an image from given coordinates - OpenCV Python
Im learning OpenCV at the moment. The goal of this exercise is to take the 4 corner points of a Pokercard from a laying perspective and warping it flat in front of you. As you can see I have the coordinates mapped out in pts1/ corners assigned correctly (It seems like that at least, after checking). After outputting im...
I have used your code with my own image to regenerate the error, but it worked fine. You can either post to us your input image, or make sure the point you select is not larger than your image it self, coz I can see that you are hard coding the points
64,998,297
64,999,574
Why does an empty C++ project in VS 2019 have additional dependencies?
I tried creating an empty C++ project in VS 2019 and I opened Project Properties where I found that there was a list of import libraries that VS was adding as "Additional Dependencies" kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp3...
Here's a quick rundown of what thes libs are for: kernel32 : Process and thread management, file and device I/O, memory allocation (keep this, the C and C++ runtime libraries and compiler-generated code uses it) user32 : Window and menu management (keep this if using GUI, can remove for console apps) The base set of w...
64,998,733
64,998,761
dynamic memory allocation using new operator , issue in type cast
uint8_t hello = 50; uint8_t *data; data = new uint8_t(hello); //issue when using "new" data = (uint8_t*)malloc(hello); //worked fine I want to allocate memory like above mentioned code. If I delete this data ptr at the end of the scope, there is some sort of memory leak. Moreover, have I allocated the memory corr...
If you're looking to make a buffer of some particular size: uint8_t *data = new uint8_t[hello]; Where hello is your size argument. Note the use of [...] instead of (...). The second form is for constructor arguments when building one of something. The original form creates an allocation for one uint8_t and populates t...
64,999,087
64,999,130
How many implicit conversions can C++ do to convert one user-defined type to another when initializing class types?
#include <iostream> struct Gadget { Gadget() { puts("Gadget default"); } Gadget(char const *a) { puts("Gadget-const char* constructor"); } Gadget(Gadget const &other) { puts("Gadget copy"); } ~Gadget() { puts("\nGadget destruction"); } }; struct Work { Work() { puts("default"); } Work(const Gadget &a) { p...
Only one user-defined conversion is allowed in implicit conversion sequence. (BTW standard conversions don't have such limits.) Work w = "std"; performs copy initialization, it requires two user-defined conversions, one from char const * to Gadget, and one from Gadget to Work. Work w("std"); performs direct initializat...
64,999,436
65,069,453
C++ Google test aborts on Ubuntu calling Notify() multiple times on Notification object
i use google test and google mock. There is a mock object on which i expect a method call OnConnectionError() which notifies the absl::Notification object done 3 times. absl::Notification done; EXPECT_CALL(*client, OnConnectionError(::testing::_)).Times(3) .WillRepeatedly(Notify(&done)); bool result = client...
I found the answer by my self: I reviewed the relevant source of google abseil. In notification.cc i found the relevant error message. The respective source part is surrounded by a #ifndef NDEBUG I edited the CMakeLists file in order to rebuild it in Release mode by adding the line set(CMAKE_BUILD_TYPE Release), so th...
64,999,518
65,058,063
How to download, compile and link a library as external project in CMake?
I am trying to use the ExternalProject_Add framework in CMake to automatically download, compile and link a static library. You can find the library here, however the question can be applied to any external CMake project. Here are the boundary conditions of my question: The external project is CMake compatible The ext...
Thanks to the comments from Tsyvarev, I was able to achieve the same goal with a much cleaner and more robust code: root/CMakeList.txt set(INIH_PROJECT inih_project) set(INIH_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/external/inih-install) set(INIH_LIB_DIR ${INIH_INSTALL_DIR}/lib) set(INIH_INC_DIR ${INIH_INSTALL_DIR}/i...
64,999,672
64,999,770
The alternative rule in P1787 for whether a set of non-static member functions can be overloaded
After reading P1787, I have a confusion about the comment in this example. That is: struct X { static void f(); void f() const; // error: redeclaration void g(); void g() const; // OK void g() &; // error: redeclaration }; Obviously, they're invalid overload declarations if per over.load in the curren...
The ref-qualifier only needs to be the same "(if both have one)". If only one declaration has a ref-qualifier and the other doesn't, the wording implies that the two declarations correspond, assuming all other conditions are satisfied. In the provided example, that means void g() &; is a redeclaration of void g();.
64,999,675
64,999,973
SetupDiGetDriverInfoDetail fails. Size of SP_DRVINFO_DETAIL_DATA too small?
I'm calling the Setup API function SetupDiGetDriverInfoDetail like this: SP_DRVINFO_DETAIL_DATA_W driverDetailData = SP_DRVINFO_DETAIL_DATA_W(); driverDetailData.cbSize = sizeof(SP_DRVINFO_DETAIL_DATA_W); DWORD reqSize = 0; ok = SetupDiGetDriverInfoDetailW(deviceList, nullptr, &driverData, &driverDetailData, size...
SP_DRVINFO_DETAIL_DATA is a variable length structure because of the HardwareID[ANYSIZE_ARRAY]; buffer at the end. Once the required size is known, it can be allocated dynamically. DWORD reqSize = 0; SetupDiGetDriverInfoDetailW(deviceList, nullptr, &driverData, NULL, 0, &reqSize); SP_DRVINFO_DETAIL_DATA_W *driverDetai...
64,999,845
64,999,896
Do I have to return `NULL` for thread function when I use the detached pthread in linux?
For example: void* thread(void *arg) { return NULL; } int main() { pthread_attr_t attr; pthread_t th; pthread_attr_setdetachstate(pthread_attr_t &attr, PTHREAD_CREATE_DETACHED); pthread_create(&th, &attr, thread, NULL); } Because of it's a detached thread, I can not receive the funtion retrun by p...
should I return NULL? You can return nullptr or any other value whether the thread is detached or not. If I don't return NULL, will it cause some bug? If you don't return anything then the behaviour of the program will be undefined. P.S. The C++ standard library has portable wrappers for threads which allow you to ...
64,999,847
65,000,037
How to specialize a variadic template function in c++?
Let the function foo be given with the following "signature": template<typename ...Ts> void foo(Ts ...args) This is a bit overdone since I need foo to proccess doubles only. How can I modify foo so it accepts doubles only? The original code has been Godbolted: #include <tuple> #include <iostream> template<typename .....
You can constrain your template like this: template<typename ...Ts> requires std::conjunction_v<std::is_same<double, Ts>...> void foo(Ts ...args) { // ... } Here's a demo As pointed out by HolyBlackCat, you can write the template much more conveniently like this: void foo(std::same_as<double> auto ...args) { (st...
65,000,186
65,000,296
how do I call the function from the upper class? the class is not inherited
class a{ private: class b* b = new b; int getSomeWhatValue(){ } }; class b{ private: void bFunc(){ //I want to call an getsomewhatvalue() here } }; I made the code really simply. How do I call an a's function at b? I tried to use thispointer, but ...
Your scenario will cause a cyclic calling (i.e. never ending loop of A creating an instance of B which in tern creates an instance of A and the loop continues), so its not permissible. You have two options: Declare "int getSomeWhatValue()" as static, and call it through the class (instead through an instance). Pass a ...
65,000,322
65,013,686
Creating raw_ostream object in LLVM
What is the correct way to create a raw_ostream object and use it for printing? I read various articles and the only example I can find is (How to redirect llvm::outs() to file?) raw_ostream *output = &outs(); which made use of llvm::outs. Sorry for asking this because I am not too familiar with C++ but had to underst...
llvm::raw_ostream is an abstract class with two important pure virtual functions implemented by subclasses; write_impl() which holds the logic for writing data to the underlying stream and current_pos() which returns the position currently being written to in the stream. llvm provides the following output stream implem...
65,000,486
65,000,581
Redefinition of noinline attribute using macros
Is it possible to redefine attributes such as [[gnu::noinline]] and __attribute__((noinline)) using #define? I am trying to accomplish this #define noinline __attribute__((noinline)) \ noinline void my_function(); // Turns into __attribute__((noinline)) void my_function(); // or [[gnu::noinline]] void my_function();...
Is it possible to redefine attributes such as [[gnu::noinline]] and attribute((noinline)) using #define? You cannot "redefine" them i.e. you cannot make them mean something else. You can however define macro aliases for them which is the goal that you accomplished with your example.
65,000,968
65,001,074
Expression "void()" and its validity with ternary conditional
I'm trying to find out whether the following code is valid (even if dubious in appearence)? void hello(int, int) {} int main() { int a = 1; int b = 2; a == b ? hello(a, b) : void(); return 0; } I have not found anything suggesting this would be invalid, and it compiles fine on c...
What exactly does void() evaluate, if it does that at all, to? Here, void() is in a context where the grammar expects an expression rather than a type. As such, it has the same meaning as in the linked question What does the void() in decltype(void()) mean exactly? i.e. it is a prvalue expression of type void. Why i...
65,001,042
65,001,206
How do I access from template class A a struct declared as private field in template B class in c++?
There is following c++ raw code: template<typename T> class A { private: // here I want to access B::SomeStruct to create SomeStruct field in class A }; template<typename T> class B { private: template<typename Tp> friend class A; struct SomeStruct { void some_field; }; }; In class A I want to create...
This would be one way. All B:s befriends all A:s and A<T> has a B<T>::SomeStruct member: template<typename T> class B { private: template<typename Tp> friend class A; struct SomeStruct {}; }; template<typename T> class A { private: // 'typename' prior to dependent type name 'B<T>::SomeStruct': typ...
65,001,304
65,001,484
Multiply two 2d array of different sizes
I have two 2d arrays and they must be arrays, not vectors. They are declared: double x[4][6]; //size can be any value but the row and column double y[6][4]; //must be the opposite of the other array I need to be able to multiply the rows of x by the rows of y but the first row of x must be ignored and the first colu...
Here is the correct loop for (int i = 1; i < 4; i++) { for (int j = 0; j < 6; j++) { cout << "(" << x[i][j] << " * " << y[j][i] << ") "; } cout << endl; } Output (5.5 * 6.6) (6.7 * 1.2) (3.3 * 5.6) (47 * 2.3) (1.2 * 8.5) (0.5 * 5.2) (1.2 * 3.2) (34.3 * 1.1) (66.7 * 4.3) (0.2 * 4.1) (2 * 1.9) (3.7 ...
65,001,447
65,001,597
Getting a certain range of memory in C++ without doing a memory copy
Suppose I have a pointer of some type say a char pointer for example. const char * somePtr = "hello"; I want to get and store the value of a certain memory range say I only want to get the word "ell" from "hello" without doing a memory copy. I can get the word "ell" by using the code below but it is using a memcpy: co...
If you're using a recent version of C++, you have tools to handle read-only spans of memory. Since C++17, mainly for character strings: std::string_view Since C++20, for arbitrary memory: std::span If not, you could implement a poor's man version of those tools in C++98.
65,001,492
65,031,761
Visual Studio specific project not being built when build Solution
In vs2015 a specific project under solution is not being built when building the solution (the build is not called). In the configuration manager the project is checked-in all the configurations (Release, build and etc..) In options "Require source files to exactly match the original version" is checked. Changes made ...
Please try the following steps: 1) reset all vs settings under Tools-->Import and Reset Settings-->Reset all settings 2) disable any third party vs installed extensions under Tools-->Extensions and Updates 3) delete all caches files under C:\Users\xxx(current user)\.nuget\packages and C:\Users\xxx(current user)\AppData...
65,001,553
65,001,712
Class vector initialisation
I want to create a class which has an array attribute. The class looks like: class MyVector { private: int m_vector[]; public: /* Here I would have a constructor and other functions*/ } Can I initialise an object of the class in the following manner? MyVector vec={1,2,3,4};
Modify your code this way: #include <initializer_list> class MyVector { private: int m_vector[5]; // if you use a static array you need specify its size public: MyVector(std::initializer_list<int> l) { int i = 0; for (auto value : l) { if (i - 1 >= 5) break; m_vector[i...
65,001,660
65,002,673
I'm not getting any output from this code in the screen
i was trying to solve this question and i am not getting any output on the screen after giving input Given an array of integers representing measurements in inches, write a program to calculate the total measurements in feet. Ignore the measurements those are less than a feet (e.g. 10) Example Finding the total measure...
The number of times you are taking the input is one more than size. Also x=0 is redundant. #include <iostream> using namespace std; int total = 0; int main() { int arr[1000]; //int arr1[1000]; int size; cin >> size; int x; for (int i = 0; i < size; i++) { cin >> arr[i]; x = arr[i] / 12; total = x + total;...
65,001,923
65,002,109
Can I forbid calling private member of derived class from base?
I has this code: struct A { virtual void f() {} }; struct B: A { private: void f() override {} }; ... B b; A& a = b; a.f(); And ofcourse it will call f() from B cause private is checked on the compilation time but choosing virtual function version are in the runtime. Can I forbid f() calling in this case?
No. As you call f() on an A reference, the access rules are checked on A. You can't expect the compiler to check the rules for B, because it does not necessarily know that a is of type B. From cppreference: Access rules for the names of virtual functions are checked at the call point using the type of the expression u...
65,002,876
65,003,047
Reading temperature from files in /sys/class/thermal/ with fscanf keeps returning the same value forever
Whilst I am having better results using fgets, I am really puzzled by why the following code would always give the same value (from the second read onwards). The following is a minimal temperature reader. It seems to read correctly the first time but outputs the same value forever, despite the system temperature change...
You should call fflush() before your fseek(). Fseek will correctly handle updates from within your program but it does not know about external changes.
65,002,950
65,005,381
Is using a pointer to an elements in an vector dangerous?
I have an vector, filled with objects: std::vector<MyClass> vec; vec.push_back(MyClass("Hi", 10)); //example, could be any class Later, when it is filled, I want to access it: for(unsigned int i = 0; i < vec.size(); i++) { MyClass *c = & vec.at(i); // <--- HERE if(c) // <--- AND HERE { c...
Is using c more dangerous than using vec.at(i) directly? Not in the example. It is unnecessarily complex however. Can c be nullptr? Not in the example. Do I need the protection with if(c)? No; see above. Is using a pointer to an elements in an vector dangerous? Using pointer - or any other form of indirection -...
65,004,041
65,004,181
How I can Fix ( no matching function for call to 'Hospital::Hospital()'| )
This code is for Hospital record homework and I tried to solve it but there is a compilation error. error line is : ( Hospital hs [3]; ) and I wrote error text at the last . #include <iostream> using namespace std; class Hospital { private: string name ; int beds ; int patients ; public : Hospital(st...
This is one way Hospital hs [3] = { Hospital("King Salman" , 3 , 0), Hospital("King Saud" , 3 , 4), Hospital("Alhabib" , -8 , 4 ) }; or you could add a default constructor to your class.
65,004,291
65,004,523
Passing two std::array elements as function arguments in non sequence order
I'm trying to figured out how to pass elements of two std::arrays as function arguments in mixed order. It's quite simple task if the order of arguments does not matter or it's sequential (when elements of one array should be passed right after elements of another array). We can simply use fold expression like this #in...
You might do template <std::size_t ...Is> void foo(const std::index_sequence<Is...>&) { std::array<const char*, 3> values = {"one", "two", "three"}; std::array<int, 3> keys = {1, 2, 3}; foo_impl(std::get<Is%2>(std::tie(keys, values))[Is / 2]...); } int main() { foo(std::make_index_sequence<6>{}); } D...
65,004,760
65,004,901
How to fix(avoid) "no debug info" warning?
Each time when I built my solution I get such warning notification. As far as I understand it means that my solution uses any libs that don't have files with debug symbols. 9>strmbasd.lib(amfilter.obj) : warning LNK4099: PDB 'BaseClasses.pdb' was not found with 'strmbasd.lib(amfilter.obj)' or at 'D:\Tier\x64\Debug\Base...
Go to Build->Properties->Linker->Command Line and add /ignore:4099
65,005,203
65,005,385
shared library error about "undefined symbol" when using `dlopen`
First thing first, here's my minimum reproducible program: CMakeLists.txt: cmake_minimum_required(VERSION 3.17) project(untitled4) set(CMAKE_CXX_STANDARD 17) add_library(lib1 SHARED lib1.cpp) add_executable(untitled4 main.cpp) target_link_libraries(untitled4 PRIVATE dl) main.cpp: #include "iostream" #include <dlfcn...
With the addition of the linker option -rdynamic your code does not fail with "undefined symbol". You can set that with set_target_properties(untitled4 PROPERTIES ENABLE_EXPORTS 1) or target_link_options(untitled4 BEFORE PRIVATE "-rdynamic"). Example: cmake_minimum_required(VERSION 3.17) project(untitled4) set(CMAKE_C...
65,005,244
65,103,758
online-compiled code is throwing segmentation error
I am running this code on online compiler: #include <iostream> using namespace std; int main () { int x_coordinate = 0, y_coordinate = 0; int numberOfMoves; cin >> numberOfMoves; // cout << "i went here" << x_coordinate << numberOfMoves; string direction[numberOfMoves] = {"right", "up", "left...
Changing from an illegal variable-length-array to a C++ std::vector container is so highly likely to fix all your segmentation fault problems that I won't go into details.
65,005,327
65,007,163
Static const member initialization outside class
how can i initialize static const int member outside class ? class C { public: C(); private: static const int a; static const std::string b; }; // const int C::a = 4; // i know it // const std::string C::b = "ba"; // this one too
This is how to initialize static class members outside of the class: C.cpp #include <string> class C { public: C(); private: static const int a; static const std::string b; }; C::C() = default; const int C::a = 4; const std::string C::b = "ba"; There is no other option to initialize a static class memb...
65,005,932
65,006,081
Doubly Linked List Triplets
Stuck in C++.Hi, I am trying to find the consecutive sum of triplets in a Doubly linked list and here's my program. But while running it on the IDE (VS code) I am getting Segmentation Core Dumped error. I am trying It using pointers who will traverse the list and given total count of such tripletes Program:-> #include<...
Check this code: head=head->next; nx = head->next; pr = head->prev; You are setting head before accesing head->next. Therefore, you end up dereferencing a null pointer. I mean, at the beginning head->next wasn't null but now it might. You should also check for prev, which can be null the first time. In fact, ...
65,006,023
65,006,083
Catch vector.erase()
When I try to erase elements, from vector and catch it, program stops with code -1073741819. This is my code: try { vec.erase(it); //it is invalid iterator } catch (...) { cout << "caught" } I don't see caught in console. Is there some way to catch exceptions in vector.erase() and why my code does not work?
The behaviour of attempting to erase an invalid iterator from a std::vector is undefined. Assuming an exception is thrown in such circumstances (and therefore catchable) is a common misconception.
65,006,177
65,009,196
Cocos2d-x tilmap black screen
I am a beginner with cocos2d-x and try to use it with Tiled to create maps. I created a TileMap, and here is my code, in LevelOne::init() in level_one.cpp : if (!CCLayer::init()) { return false; } _tileMap = new CCTMXTiledMap(); _tileMap->initWithTMXFile("levelone.tmx"); this->addChild(_tileMap); return true; The...
I figure it out: Tiles folder should be on th same disk than .tmx file to have relative path and both should be in Ressource folder.
65,006,493
65,007,741
Understanding segfault information
I'm trying to debug a segfault that happens when I run my program written in C++. I am getting an error of this sort when I run my program: [1] 24926 segmentation fault (core dumped) ./program What I would like to know is what do the numbers written before the segfault indicate, i.e., what is [1] and what is 2492...
[1] is the job ID number, and 24926 is the PID (process ID) of the program which crashed. I'm assuming you're on a Unix-based system right now, as far as I know they're the only ones to use this format. This isn't very meaningful information to help you solve your problem though, so you'd be better off opening another ...
65,006,732
65,008,743
Why is my while loop not working when I do nothing inside of it (do-nothing loop)?
I'm simply trying to use a while loop to help control the frames per second of my program that displays a live camera feed along with data corresponding to what that camera is looking at. The reason this is not trivial is because the loop that is calling getFramesAfterCapture() is running much faster than the camera ca...
I was able to figure out a more elegant solution using a binary semaphore instead of a mutex or a static member boolean. The difference between using a mutex and a binary semaphore is that a binary semaphore does not require me to release the semaphore at the end of getFrameCapture(). Basically when a semaphore is rele...
65,007,049
65,007,589
Are there any downsides to using `std::reference_wrapper<T>` as an always-valid member variable instead of a pointer?
I am having a quite common problem. I have a class that must store a non-owning pointer to a different class object. I know that: The lifetime of the reference object is guaranteed to outlive the instance. The referenced object is passed in a constructor and does not change with the exception of moves or assignment. I...
Since Foo is a struct you need to invoke get() every time you access any member or field of Foo. With reference or pointer you could use '.' or '->' respectively for member access. So reference_wrapper is not "transparent" in that regard. (There is currently also no way of making it "transparent" in C++, which would be...
65,007,298
65,051,683
Operate prefixed expression from input
I want to operate expression of the following kind without using stacks, only recursion: + - 8 m 4 + 5 7 9 This should equal 4, because −8 + max3(4, 5 + 7, 9), being m a ternary operator that finds the maximum. I know how to crack this kind of operations for a simpler expressions, but however trying to adapt my code fo...
When your code gets the minus sign - it substract eight to the next number, which is m (61). int operate() { char op; cin >> op; int val = op - '0'; std::cout << "Call with " << val << " " << op << std::endl; if (val < 0) { std::cout << "In if" << std::endl; if (op == 'm') { ...
65,007,574
65,008,100
clang compiling to which version of c++ in macOS?
#include <iostream> #include <vector> using namespace std; int main() { if (__cplusplus == 201703L) std::cout << "C++17\n"; else if (__cplusplus == 201402L) std::cout << "C++14\n"; else if (__cplusplus == 201103L) std::cout << "C++11\n"; else if (__cplusplus == 199711L) std::cou...
The default version my clang is compiling too is c++98, and the move() function is present in c++98 as well, but apparently it does not perform move semantics(i.e. create Rvalue Reference), but just deep copying. The following link gives answer to finding out to which version of c++ the compiler is compiling to: https:...
65,007,634
65,008,145
Access violation reading location 0xFFFFFFF8 on second usage of method
so I have exception while I try to rehash hashtable second time here is my rehash Method. void ReHash() { if (currentSize >= maxSize * 0.8) { int tempSize = maxSize * 2; cout << "rehash" << endl; list<T>* tempArr = new list<T>[tempSize]; Node<T>* temp = NULL; int index = 0; ...
You're both creating and deleting something wrong. First, you create one array, list<T>* tempArr = new list<T>[tempSize] then you create another one, arr = new list<T>[maxSize]; which you immediately throw away (leak) by pointing to the first array you created instead, arr = tempArr; and lastly, you make sure that a...
65,007,892
65,011,460
c++ visual studio compiler OpenMP
I'm trying to compile a source code on Windows that works great on Linux. Now, I'm facing the following issue: The code relies on OpenMP and in there, the scheduling approach should be stored in a string and the chunk size in an integer. The following code does extract the necessary information. omp_sched_t omp_sched; ...
You are using features introduced in OpenMP 3.0 but Microsoft VisualC++ only supports OpenMP 2.0. And, AFAIK, even that support is deprecated though it's still there. If you want support for modern OpenMP, you simply need a different compiler. Visual Studio comes with optional Clang, which has the required support, but...
65,007,935
65,008,288
"Integer constant is so large that it is unsigned" compiler warning rationale
The following C/C++ code: long long foo = -9223372036854775808LL; // -2^63 compiles (g++) with the warning integer constant is so large that it is unsigned. clang++ gives a similar warning. Thanks to this bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661. I now understand why GCC gives this warning....
This has to do with how the type of integer constants is defined. First, as mentioned in the gcc bug report, -9223372036854775808LL is actually two tokens: the unary - operator and the integer constant 9223372036854775808LL. So the warning applies only to the latter. Section 6.4.4.1p5 of the C standard states: The ty...
65,008,359
65,008,391
Difference between using parenthesis and sqaure brackets for creating dynamic array in C++
Dynamic arrays are allocated in C++ like this. int *arr = new int(5); int *arr = new int[5]; What is the difference between these ways? Or Are they exactly same?
An array is only created when you use []. If you are not using [], then you are not creating an array. int *arr = new int(5); allocates a single int and gives it the value of 5. int *arr = new int[5]; allocates an array of 5 int's with no specified value in each element.
65,009,092
65,026,062
How to integrate C++ library when its package is not named
C++ and CMake newbie question regarding how to integrate a third-party library into my own code. I'm trying to add Datadog metrics to C++ application. The officially-endorsed library doesn't state how it can be integrated. I imagine it should tell me how to import it like this: find_package(<PACKAGE> REQUIRED) add_exec...
Easy solution is to fetch this library directly and do add_subdirectory. But this requires cmake >= 3.11. Create dir cmake and file cmake/cpp-datadogstatsd.cmake cpp-datadogstatsd.cmake: FetchContent_Declare( datadogstatsd GIT_REPOSITORY https://github.com/BoardiesITSolutions/cpp-datadogstatsd #...
65,009,198
65,010,079
What is move() in c++98?
#include <iostream> #include <vector> using namespace std; int main(void){ vector<int> a; a.push_back(3); vector<int> b = move(a); cout<<"b: "<<b.data()<<endl; cout<<"a: "<<a.data()<<endl; return 0; } Output (in c++98): b: 0x7f9a82405730 a: 0x7f9a82405720 Output (in c++11): b: 0x7f9a82405730 a: 0x0 I am usi...
The reason that you can call std::move at all pre-C++11 is that libc++ doesn't wrap its implementation of it in #if _LIBCPP_STD_VER >= 11. This doesn't work in libstdc++ (which Linux uses by default) because it guards std::move with #if __cplusplus >= 201103L. As for why using it doesn't make a.data() be null, it's bec...
65,009,487
65,009,815
Why are the returning and non-returning std::functions castable?
Why does this work? std::function<int(int)> ret_func = [](int x) { return x; }; std::function<std::string(int)> ret_func1 = [](int x) { return std::to_string(x); }; std::function<void(int)> func = ret_func; std::function<void(int)> func1 = ret_func1; Because of type erasure of the functor in the std::function? This ca...
Don't think of it as casting, think of it as the std::function<int(int)> being assigned to the std::function<void(int)> as a value. std::function<void(int)> can be assigned any function-like object fun that can be invoked like static_cast<void>(fun(v)) (v being an int). std::function<int(int)> easily fits that criter...
65,009,898
65,010,001
Incompatible function prototypes between glew.h and glext.h
I'm trying to compile some code using glew.h and glext.h. Here's a minimal example: #include <GL/glew.h> //#include <GL/gl.h> // commenting it doesn't change anything #include <GL/glext.h> int main(){ return 0; } I have 6 compile-time errors because of different function prototypes. The first one is: In file incl...
I'm trying to compile some code using glew.h and glext.h. Don't do that. These are two different tools that both do the same thing. They are not intended to be compatible with each other, and neither is expected to work in the presence of the other (in the same source file). You are either using GLEW or you're manual...
65,010,523
65,013,512
Fastest way to find the largest frequency of a period at the end of a vector?
Say I have the vector { 1, 1, 2, 1, 1, 2 }, I want to find out the largest frequency of a period at the end of the vector. In this case, the frequency (curl) is 2, since 112 is repeated twice. And since any period that is repeated at least twice is at most half the vector length, I only need to scan through half the ve...
Now (as you no longer make copies of sub-vectors), almost all the time is spent in comparing values. I see two independent ways to speed this up: vectorize the compare operation (if your compiler doesn't do it) and parallelize processing of different length. I implemented the multi-threading. Used a vector with 1,000,0...
65,010,758
65,010,785
c++ program return "0 0" instead of returning prime numbers. Why does it not get the correct output from the "prime" function?
My function "prime" takes a dynamic array and returns a dynamically allotted array consisting of only prime numbers. But when it is returned to main, it gives the wrong output and print Output: 0 0 Expected Output: 2 3 My Code: #include<stdio.h> #include<math.h> #include <cstdio> #include<iostream> using namespace st...
int lenghtOfArray=sizeof(primeArray)/sizeof(int); is an wrong way to get the length of dynamically allocated array. sizeof(primeArray) is not the allocated size but the size of pointer. You already have the number of elements of the array, so use that to get the length of the array: int lenghtOfArray=capacity...
65,010,852
65,010,928
Strange behaviour where initialised map being reported as empty
I have the three following files: test.h #pragma once #include <iostream> class Test{ public: Test(std::string string); }; test.cpp #include "test.h" #include <map> std::map<int, int> HEY = { {1, 45}, {2, 2} }; Test::Test(std::string string) { std::cout << "hello" << std::endl; if (HEY.empty()...
Your HEY and test objects are both being created in global memory at program startup before main() is called. The test object is simply being created first, that is why the map is still empty when test's constructor is run (technically, the map hasn't even been created yet). See Static Initialization Order Fiasco. Mo...
65,010,860
65,012,840
C++ a class using other class
I'm trying to define Node into NodeList class, And store it. Whay I've tried is: In Try() function, I defined a node like Node *node = malloc... This works fine. But if I use the node that I defined in class like node = malloc... this line gives runtime error. I don't understand what is the difference between these two...
You code has many problems: In Main.cpp you are dereferencing a NULL pointer: node->DosyaOku();, but node is NULL. This is an undefined behavior. You have the same problem in NodeList.cpp You are using a malloc in Node.cpp and you should probably want to use a new instead (read here), and you should think how to free/...
65,011,578
65,011,607
Why isn't my code working properly when looping this array
if I have the array N[12] and I have the code: float N[12]; for (int X = 1; X < 12; X++) { N[X] = N[X] + 2; cout << N[X] << endl; } what else do I need to get this to display odd numbers starting at 1 and increasing until I have 12?? (so until 23) Its outputting a really weird slew of numbers I'm pretty new to...
Your array is not initialized to any values, so depending on how your compiler does it, it most likely will be filled with random values. This would explain why you are seeing weird numbers. Since you want to start with a initial value of 1, you can initialize your array like this: float N[12] = { 1 }; This will set ...
65,012,526
65,012,907
Cast from double to size_t yields wrong result?
The following code works. My question is, should 2) not lead to a result very close to 1) ? Why is 2) casted to such a small amount ? Whereby, maybe worth to note 2) is exactly half of 1): std::cout << "1) " << std::pow(2, 8 * sizeof(size_t)) << std::endl; std::cout << "2) " << static_cast<size_t>(std::pow(2, 8 * siz...
It is due to that part of the specification: 7.3.10 Floating-integral conversions [conv.fpint] A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented...
65,012,811
65,012,955
C++ dll and name mangling issue
I am trying out a simple test DLL project. Under my solution, I have two projects - first C++ Dll (library) and second C++ exe (driver). Below I've attached a snapshot of the basic project setup: dllmain.h #ifndef DLLMAIN_H_ #define DLLMAIN_H_ #ifdef FFMPEGLIB_EXPORTS #define FFMPEGLIB_API __declspec(dllexport) #else...
Why the function name of dllmain.h getting mangled in spite being marked as extern "C"? Because __declspec(dllimport). Why can I not create instance of test class A from extern methods? What would be good way of doing it? I think that's fine, but you didn't provide any class A code. Just do this: class __declspec(d...
65,013,024
65,013,214
Converting from abstract data type to generic type
I am trying to figure out how to convert from an abstract templated class to a generic data type as seen below. Specifically, A::m_data will hold class B<T> as a data type. Eventually I want to be able to convert A::m_data to whatever data type B::m_data is holding. In this case, to an integer. Currently, I get the err...
The error is because foo.m_data is a B<int> and bar.m_data is an int, and you have not defined an operator= for B that takes a T as input, eg: template <typename T> class B { public: T m_data; B& operator=(const T &value) { m_data = value; return *this; } }; Live Demo It is not really clea...
65,013,025
65,028,541
How do I convert a 2d Python list to a 2d C++ vector?
I'm giving my function a 2d Python list and would like to convert it to a 2d C++ Vector. But I don't understand how I can do that. The input is a list of n-dimensional coordinate points. Each of these coordinate points is a list itself. The individual point values are doubles. This is my code so far: PyObject* foo(PyOb...
Thanks to @YiFei I looked into PyList_Check and other Py_Check functions and found a working solution. Here is the code: PyObject* foo(PyObject* self, PyObject* args) { PyObject* polyList; // Verify that argument is a list if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &polyList)) { return NULL; ...
65,013,036
65,014,422
grid not showing at all when I try to on it
I am trying to make an option pop-up menu to be able to choose if I want the grid on or off as an option to add to the game I am trying to make. I have been able to display the pop-up menu which has two options called "grid on" and "grid off", however when I click on it, the grid doesn't show at all for me which I am s...
Toggle global (or window-specific, up to you) boolean in menu callback Issue a glutPostRedisplay() in menu callback Use global boolean to draw/don't draw grid in display callback
65,013,152
65,013,968
Qt retrieve additional data created during request when QNetworkAccessManager finished
I would like to create an HTTP request and retrieve in the response some variables create during the request. However, QNetworkAccessManager reponse is asynchronous and use SIGNAL/SLOT functionality, so variable are no more accessible. Here is an example : void makeRequest() { manager = new QNetworkAccessManager(th...
One way to do it is to capture the locals in a lambda instead of using a separate function for the slot. void makeRequest() { manager = new QNetworkAccessManager(this); // here is the datas I want to get in the reply // objectdata and objectdata2 are created just before the http request MyClass objectd...
65,013,345
65,019,262
How to get char string from PyObject str?
Hi i'm learning how to use python in c++ and am wondering how I convert the returned python value to something I can use in c++. Here's my code: CPyInstance pyInstance; PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); CPyObject pName = PyUnicode_FromString("Info"); CP...
You can use functions from section UTF-8 Codecs. For example, PyUnicode_AsUTF8AndSize: CPyObject pValue = PyObject_CallObject(pFunc, NULL); Py_ssize_t size; const char* data = PyUnicode_AsUTF8AndSize(pValue.getObject(), &size); std::cout << std::string(data, size) << std::endl; Or PyUnicode_AsUTF8 const char* data = P...
65,013,901
65,029,754
unresolved external using fmt::format to return std::wstring
I am using fmt 7.1.3 with Visual Studio 2019. I take the fmt src files and make a static lib. When I link this lib into an exe project that does: std::wstring out = fmt::format(L"Answer {}", 42); It compiles but fails with a linker error: unresolved external symbol "class std::basic_string<wchar_t,struct std::char_tra...
Make sure to include fmt/format.h where this function is defined. Quoting the docs: fmt/format.h: the full format API providing compile-time format string checks, wide string, output iterator and user-defined type support Here is a working example on godbolt.
65,014,007
65,014,189
C++ Primer Chapter 14 readStr example won't compile in Visual Studio 2019
The example code for the book C++ Primer has an example in chapter 14 named readStr.cpp which has compilation errors when I use cl. I'm on windows 10 and have installed Visual Studio 2019. I've also tried compiling using g++ and get similar compilation errors. I've also tried compiling this on my macbook pro and get a ...
As you can see from the reference, from C++11 the bool operator becomes explicit. You have two choice: Compile with the previous standard (in gcc add the flag -std=c++98) Make the operator explicit in this way: bool operator()(string &s) const { return !getline(is, s).fail(); }
65,015,006
65,015,087
Binding Variadic Functions C++
Suppose I have a function like this: template <typename... T> void sum(int start, T... next); And I wanted to bind this. How would I do this? To be more precise, if the function had a fixed amount of arguments, it would look something like: void sum(int start, int next); // function signature // ... auto binded_sum...
Worth mentioning that C++20 also provides std::bind_front for exactly this purpose: auto bound_sum = std::bind_front(sum, 0); (This has a number of potential advantages over the naïve lambda implementation; see the paper proposing the feature for details if you are so concerned.)
65,015,631
65,036,898
How do I transmit multiple messages simultaneously during simulation in omnett++
I want to have multiple messages move in the simulation at the same time. My network has multiple active messages but only one message moves at any given time. The other messages seem to pause and wait until none are moving before they move. They take turns moving as if they are in a queue. Is there any way to have all...
There is a difference between concurrently in animation time or concurrently in simulation time. Check the simulation time value in the upper right corner. Even if messages are animated sequentially the simulation time may or may not advance, so effectively those messages are sent in parallel if the simulation time did...
65,015,858
65,015,933
CUDA kernel do I need to put const in all pass-by-value parameters?
__global__ void diff2D(int top, int left, (const int windowSize or int windowSize), float* a1, float* a2) { (const int mid or int mid) = windowsize / 2; ... // templateSize, windowSize are all const. } My question is that do I need to explicitly use "const int windowSize" keyword to make the compiler put mid...
All kernel parameters of any type whatsoever are passed via constant memory. See here. The type or decoration of the parameters is irrelevant for this feature. No other constants of any type are placed in constant memory automatically, unless you use an appropriate __constant__ decoration/usage. Outside of kernel par...
65,016,345
65,016,669
simplify reading from file with comma using extraction operator?
I want to read from a file that consists of entries in each line that look like this: BA,1355,SIN,3316,MEL,3339,Y,0,744 BA,1355,SIN,3316,LHR,507,,0,744 777 I want to store the first 6 columns and save them to string and int respectively. At the moment, I have use getline to handle the comma, as shown below. But the dr...
If you're sure the first six fields are going to be filled, what you could do is replace every comma in a line to spaces, so that you can then use operator<< to get objects nicely. This doesn't work if any of the important fields are empty. for (int i = 0; i < temp.size(); ++i) { if (temp[i] == ',') temp[i] = ' '; ...
65,016,505
65,016,564
Overloading the Assignment operator for character Array in c++
It can be the worse questions I am going to ask but I want to overload the Assignment Operator for character Array so basically, I can use it as a string. This is what I wanted to do. char c1[]="This"; char c2[10]; c2 = c1; This is what I have tried so far and yes it didn't work out. #include<iostream> using namespac...
I want to overload the Assignment Operator for character Array This is not possible. The C++ language does not allow defining operator overloads to anything other than classes. Some alternatives: Wrap the array as a member of a class and define assignment operator for that class. This is what std::array is, although...
65,016,556
65,026,357
msvc and gcc different behavior
#include <iostream> template<typename T> const T unit{ 1 }; template<typename T> struct data { typename T::value_type val; }; struct decimal_def { using value_type = int; static const value_type unit_val() { return 10; } }; template<typename T> const data<T> unit<data<T>> { T::unit_val() }; ...
Dynamic initialization of templated non-local variables is always unordered, even relative to other variables defined in the same translation unit (in part because templated variables might also be defined in other translation units). In this simple case, you can avoid the issue by using constant initialization instea...
65,017,097
65,017,694
Can I assign a value to argv?
When I use vscode for c and c++ debugging, sometimes some command line parameters are needed(./runFile args1 args2). If I directly click to run, it will display argv[2] out of range. This is because I did not enter parameters. But if I enter the parameters through the command line, it seems that I cannot step through v...
When vscode runs your program, it uses parameters found in a file named launch.json to do it. If you got to: Run -> Open Configurations, that'll open the launch.json for that project. By default it'll look something like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptio...
65,017,807
65,264,546
How to process output: trim_with_solid
trim_with_solid is called: // Trim mesh A (m_VA and m_FA) with solid B (m_VB and m_FB) igl::copyleft::cgal::trim_with_solid( m_VA, m_FA // input: mesh A , m_VB, m_FB // input: solid B , m_V, ...
Previously, I was using Qt3DExtras::QCylinderMesh as solid B (VB and FB). But it was NOT watertight. I replaced it with the following code which creates watertight cylinders. Header: // Create a cylinder mesh which is exactly solid // without any open boundary // Down facing cylinder in Z direction with arg...
65,018,038
65,029,854
Removing the wrong surface after running Poisson Reconstruction in PCL
I have a similar problem like link. But I used the Poisson Reconstruction algorithm in PCL instead of MeshLab to reconstruct a box. I got a mesh with some extened surface as shown in this image.I want to remove the extened surface now. I do not understand the answer to the above question,and I don't want to modify the...
As the answer in your link mentions, this artifact is the results of the Neumann boundary condition. PCL however doesn't allow you to specify the boundary condition. The original PossionRecon library (on which PCL implementation is based on) does allow you to specify the boundary condition - and has binary executable a...
65,018,075
65,018,222
Problem with add value to registry with cpp
I am trying to add value to the registry in order to run my program on system startup and after execution in Regedit. HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run is only the first letter of the path "C" int start_with_os() { long result; HKEY hkey; result = RegOpenKeyEx(HKEY_CURRENT_USE...
From the code you provided, I guess your project is using the Unicode character set. Microsoft documentation says that the last parameter of RegSetValueEx is in bytes. cbData The size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData ...
65,018,127
65,018,511
What does str[i]!='\0' mean?
This is the code: for (int i = 0; str[i]!='\0'; ++i) This is the full code I got online: #include<iostream> #include<string.h> using namespace std; int main () { char str[50]; int v = 0, c = 0, n = 0, s = 0; cout << "Enter a string : "; gets(str); //The line for (int i = 0; str[i]!='\0'; ++i) ...
if (str[i] != '\0') means "if not at end of the string" The last char in a C string (char array) is a null ('\0') value.
65,018,186
65,018,298
Why do I need to redeclare overloaded virtual functions?
I have a base class with two overloaded functions f(void) and f(int). The class Derived implements f(int) by calling f(void). Derived2 implements f(void) only. The compiler rejects the implementation Derived::f(int) because it wants to call f(int) but I provided no arguments because I want to call f(void). Why does the...
Derived::f hides Base::fs. Given return f(); in the body of Derived::f(int), the name f is found in the scope of Derived, then name lookup stops. The names in Base won't be found and participate in overload resolution. name lookup examines the scopes as described below, until it finds at least one declaration of any k...
65,018,404
65,018,873
Guaranteed locales on different platforms
Are there any locales besides the default C Locale that are guaranteed to exist or at least installed by default on the end-users computer on windows Linux or macOSX? I use boost property tree which can read XML from a file and takes a locale as a parameter. If I want to write a cross-platform application and the file ...
There is not guarantee locale, but C (and this just in POSIX). Various Linux distributions allow you to choose the locale to install, and usually it install just the country (and region) locale (now the UTF8 variant). So no, there is not way. And I would not expect anything useful on that: locale names are not so stand...
65,018,509
65,018,761
checking if all digits in an array element are 0 or 1 [c++]
I need to check if all digits in the one element in array = 0 or 1. I have functions for this: bool checkIfBin(int okt) { while (okt > 0) { int digit = okt % 10; if (digit > 1) return false; okt /= 10; } return true; } and calling this function looks like: for (int...
The problem stems from the fact that You are checking the input before reading it. for (int j = 0; j < 4; j++) { cout << "Enter" << j+1 << " octet in binary system: "; cin >> okt[j]; if (!checkIfBin(okt[j])) break; } should work beautifully.
65,018,650
65,021,217
Adding -fno-exceptions flag in visual studio 2019
I need to add this flag to the compiler in visual studio but I don't know how to do this. I have already tried some solutions but none worked. Someone that has the same issue or knows the solution?
Noone of the 2 solutions worked unfortunately but i found an easier way: just define JSON_NOEXCEPTION #define JSON_NOEXCEPTION
65,018,766
65,023,952
Why in asio's example the tcp acceptor pattern uses shared_pointer model wrapping heap socket, while udp use stack socket?
Source code: https://think-async.com/Asio/asio-1.18.0/doc/asio/tutorial/tutdaytime7/src.html tcp_server shows an intention to use socket on the heap, wrapped by a type called tcp_connection. class tcp_server { private: void start_accept() { tcp_connection::pointer new_connection = tcp_connection::create(i...
The shared pointer is there to manage the lifetime of the connection. In the case of TCP it is more common to have multiple connections which leads to a situation where you will likely have multiple connections instances with unrelated lifetimes. UDP is connection-less and many times is used for one-shot messages. In f...
65,018,864
65,019,074
How to get a number in a line after a certain sequence of characters which can vary in number of delimeters?
I am reading input txt file line by line and trying to get a certain line and extract a number from it. The line can look like this: "; Max: 144" "; Max: 28292" "; Max: 283829" ";Max: 12" So basically it can have any number of delimeters before "Max: ". I was trying to do it using line.find(...); which tells me if ...
Here there is an intelligent solution. Use find_first_of to detect the first digit and then extract the rest of the line. auto found = line.find_first_of("123456789"); if (found != std::string::npos) { procs = std::stoi(line.substr(found)); } It is supposed that there are not other numbers in the line.
65,019,055
65,019,090
changing a value of a class pointer in const Class function gives an error in some compiler but not others
I have below code and It gives an error as "segmentation fault" in some compiler but for other compilers it gives "40" as output. Why is there difference? #include <stdio.h> class A{ int *ptr; public: void set(int val) const; }; void A::set(int val) const{ *ptr = val; printf("%d", *ptr); } int ma...
ptr is an uninitialized pointer. When you deference an unitialized pointer, it's undefined behaviour, anything can happen. You should initialize ptr in the constructor class A{ int *ptr; public: A(); void set(int val) const; }; A:A() { ptr = new int(); } A:~A() { delete ptr; }
65,019,087
65,019,307
'nmake' is not recognized as an internal or external command
i want to build c ++ library "botan" according to this instruction: https://botan.randombit.net/handbook/building.html (for Windows) the second command is this: nmake. in the result I get 'nmake' is not recognized as an internal or external command After i tried to open nmake.exe, ended up getting this result: cl /DBOT...
The build instructions assume nmake is somewhere on the PATH. If you run a random cmd shell, this probably won't be the case. Furthermore, nmake assumes the other executables will also be on the PATH. With Visual Studio, there's a Visual Studio Command Prompt. This is a batch file in the installation folder. Running th...
65,019,299
65,023,960
row times column is not a scalar, with custom scalar type
I am trying to use the CppAD scalar type with Eigen. The following fails to compile: #include <Eigen/Dense> #include <cppad/cppad.hpp> #include <cppad/example/cppad_eigen.hpp> int main() { using Scalar = CppAD::AD<double>; //using Scalar = double; Eigen::Matrix<Scalar, 1,4> row; Eigen::Matrix<Scalar, ...
While it is mathematically true that a (1x1) matrix is a scalar, C++ is a different story: The return type of operator* in row * col is not a scalar and neither a (1x1) matrix but a product expression. This product expression is implicitly convertible to the scalar type of its operands, in this case CppAD::AD<double>....
65,019,442
65,021,186
How to prevent my JNI folder from rebuilding?
Anytime I clear build folder in flutter (either with flutter clean or manually), my jni folder rebuilds (~40 mins). Is that possible to compile library to some binary, and use it from android without breaking any interfaces and functionality? P.S. My library consists of many folders and contains .mk, .c, .cpp, .h files...
Is that possible to compile library to some binary, and use it from android without breaking any interfaces and functionality? Of course yes. Build you libraries like shared .so or static .a and use them like prebuilts. Here the example how to use native prebuilt libraries: How to link .a to .so and create new .so fo...
65,019,635
65,022,031
Default Initialization of a Union within a Class
I'm in the process of updating some legacy c++ code from Visual Studio 2013 to VS2019 and came across an interesting problem: The code in question uses a class called Attrib.h to represent any possible unit of data in a table's cell. This data could be a bool, int, double, Guid/Uuid, various types of geometry data, tex...
To start with, since Guid has a constructor, the union containing such a Guid is an "Unrestricted union". In C++98, this was not even allowed. Also, the union is anonymous. This is a problematic combination: unrestricted unions typically require special member functions, but anonymous unions can't have those special me...
65,019,769
65,019,991
How to restrict a child type in parent type?
I have a class type like this: struct permanent_runnable { static std::vector<permanent_runnable*> instants; protected: permanent_runnable() { instants.push_back(this); } public: virtual ~permanent_runnable() {} virtual void start() = 0; virtual void stop() = 0; }; I hope that all types...
You cannot prevent a user to do something undesired. They will find a way if they try hard enough. Having said this, making the base non-assignable and non-copy constructible is a good indication that derived classes should also not provide those: struct base { base() = default; base& operator=(const base&) = ...
65,020,253
65,020,738
Using a pointer by reference variable in linked lists
How do I refer to the tail variable inside the take_input() function so that it reflects in the main ? Below are the main() and take_input() functions Here I've tried to pass by reference [ **tail ] How do I refer to this inside the take_input() function for the linked list { *tail is causing an error } Any help would ...
As answered by Thomas Sabnik in the comments: -> has higher precedence than *. You have to use parenthesis: Change *tail->next = new_node; to (*tail)->next = new_node; and *tail = *tail->next; to *tail = (*tail)->next;.
65,020,449
65,021,104
I don't understand why I get this warning about conversion between signed and unsigned, is my compiler wrong?
I have this code: #include <cstdint> #include <deque> #include <iostream> int main() { std::deque<uint8_t> receivedBytes; int nbExpectedBytes = 1; if (receivedBytes.size() >= static_cast<size_t>(nbExpectedBytes)) { std::cout << "here" << std::endl; } return 0; } With -Wsign-conversion...
This is undoubtedly a bug/error in the embedded compiler. Separating the static_cast from the >= comparison removes the warning, as can be seen from testing the following code on Compiler Explorer, with ARM64 gcc 6.3.0 (linux) selected: #include <deque> #include <cstddef> #include <cstdint> int main() { std::deque...
65,020,697
65,020,851
How to sort all members with a value of false to the end of a vector?
I want to sort a vector of bools by their value. This is the list: std::vector<bool> bolis {true true false true false false true true}; Is there some kind of function that would make this list equal to this: {true,true,true,true,true,false,false,false} I saw the std::sort function but it seems the only real use of i...
First Method: This can be achieved by defining the custom comparator function and passing it to the sort function. Have a look at the implementation as follows: #include <iostream> #include <vector> #include <algorithm> //define the function: bool comparator(bool lhs, bool rhs) { return rhs < lhs; } int main() { ...
65,020,753
65,032,788
graphics.h gives no output
#include <graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd,&gm, ""); for (int i=200;i<400;i=i+25) { for (int j=200;j<400;j=j+25) { circle(i,j,100); } } getch(); closegraph(); return 0; } I download http://winbgim.cod...
Your code is perfect. You just forget to give path for BGI folder. In my machine BGI path is "C:\TurboC++\Disk\TurboC3\BGI". Since I am running it on DOSBox. So path becomes "C:\\TurboC3\\BGI" Here is the working code. #include <graphics.h> int main() { int gd = DETECT, gm, i, j; initgraph(&gd,&gm, "c:\\TurboC3...
65,020,824
65,021,612
what needs doing if including cstdlib doesn't let me use rand()?
So, I'm trying to replicate a simple dice roll using cstdlib and rand(), but visual studio code seems to have a problem with rand, claiming it's not defined, despite me having included cstdlib, any thoughts? i'll paste the code, as bare bones as it is atm, perhaps someone could figure it out? FYI, I'm using Visual Stu...
so the issue was in that in /usr/include/c++/10/tr1/cstdlib the file contents didn't use rand, srand etc... there was a decent copy in /usr/include/c++/10/cstdlib, which had references to rand and srand. i probably have to copy all the files from /include to /include/tr1, since that's where VSC seems to be looking, ot...
65,020,909
65,029,602
Problems linking some libraries with riscv linker
I am trying to compile a set of files with the compiler created here (riscv64-linux). However, I am having some problems that I assume are the result of my misunderstanding with the libraries. I am including the library libgcc in the Makefile with the flag -lgcc in the LINKER_FLAGS part. However, I get the following ou...
The problem is the linker is looking for libgcc.so or libgcc.a but in your folder you have libgcc_s.so which is not the same. You can give a SEARCH_DIR in a linker script or you can use he option -L which is easier. All the undefined references are functions from libc. However there is no libc in your folder. You will...