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,216,205
64,216,581
How can I retrieve heap memory for string objects and allocated string values in V8/Node app?
I come from web dev, and my understanding of embedding V8 in C++ is limited (null). So I'm coming here, hoping for some assistance. My task is to peak into V8's heap as my Node appis executing insecure user code using Node's VM api. Currently I am calling[getHeapStatistics()][1] api directly from my Node app to access ...
my Node app is executing insecure user code using Node's VM api The first paragraph on https://nodejs.org/api/vm.html says, in bold: The vm module is not a security mechanism. Do not use it to run untrusted code. Code running on Node can e.g. delete or corrupt or infect your files, or steal your passwords and secur...
64,216,778
64,230,330
Add Window Close Button To Menu Bar -- C++
I am trying to write an application that does not have a title/caption bar (a gross waste of screen real estate). So, I wish to add a close button ("X") to the end of the menu bar. Here is the code that I have tried: mII.cbSize = sizeof(MENUITEMINFO); mII.fMask = MIIM_FTYPE | MIIM_BITMAP; mII.fType = MFT_BITMAP | MFT...
Thanks Remy. I eliminated the MFT_BITMAP flag, and now, it works. The MS documentation did not make this clear. For those who might be reading this, asking the same question, I should note, that the above code only displays the button. Functionality must be added, just like any other button or menu item. A unique i...
64,216,886
64,217,081
Timing C++ program on Mac
I want to time my threading program on my mac and knew that for Linux environments, you can time it by doing: "time ./a.out". I tried this on my mac terminal and it seems to be working but gives a little different output. The one on Linux will give output in the format: (random times btw) real 0m0.792s user 0m0.0...
This is well explained in the man pages, in both Linux and macOS. Linux These statistics consist of (i) the elapsed real time between invocation and termination, (ii) the user CPU time and (iii) the system CPU time. macOS time writes the total time elapsed, the time consumed by system overhead, and the time used to ...
64,217,026
64,217,617
When is the destructor of an object that is being moved to called in C++?
I have some class A, which I can either construct using nothing, or an std::function. On destruction that given function should be called (in case there is one). My problem is that the object gets destroyed right after it is created and returned by my getSomeA() function which calls the std::function before it is suppo...
In the first version the object gets destroyed for the first time as part of returning the object constructed in getSomeA. Its return statement effectively constructs a temporary object, which then gets assigned to main's b1. If you ignore the process of returning from a function, the sequence of events is: A <temporar...
64,217,035
64,217,309
Rcpp produces different output when not printing blank line
I’m trying to write a function that takes in a vector of 0's and 1's (input), and returns a vector equal to the first, but with each element overwritten by 0 if any previous element was 0 (res). The first element is 1 by default. To do this, for each i, I return the minimum of the ith element of the input vector and t...
You're using the variable prev_res uninitialized, which is undefined behavior and can be anything. Every iteration of your for loop re-declares prev_res and if i != 0 you then take the minimum of input[i] and prev_res (any value). A simple fix is to take prev_res outside of the for loop: cppFunction( 'NumericVector a...
64,217,225
64,217,357
Calling a default constuctor for a stack using linked list getting error C2760
okay running into a block when it comes to inner class default constructors. in this assignment I have to make a stack utilizing linked list, I got the functions all set I am just having trouble trying to properly set a default constructor for the inner class StackNode at least that is what the compiler is telling me. ...
You are trying to define the body of the StackNode constructor inside the body definition of the StackLinked constructor. That will not work. They need to be defined separately. But you already have a definition for the StackNode constructor inline in the declaration of the StackNode class, so there is no need to de...
64,217,814
64,220,259
Any significant advantages to using column vectors instead of 1D column matrices in Armadillo?
I'm exclusively using Armadillo matrices in my C++ code for both 2D and 1D arrays for the sake of simplicity and ease of maintenance. For instance, I make use of the vector initializer list but immediately convert it to a matrix before it is actually used: mat bArray = mat(colvec({0.1, 0.2, 0.3})); Most of my code con...
An arma::vec is the same as arma::colvec and they are just typedefs for Col<double>. You can see this in the typedef_mat.hpp file in armadillo source code. Also, arma::Col<T> inherits from Mat<T>, as can been seem in the Col_bones.hpp file. Essentially, a colvec is just a matrix with a single column. You wouldn't gain ...
64,218,082
64,218,954
Visual Studio 2019: Linking to folder
I am trying to link to a folder that is not inside the project directory. To give an example, If my project is in C:\project and I have a folder C:\shared, how can I manage to link C:\shared into the project (and being able to edit/view the files in Solution Explorer) without making a copy of the directory and placing ...
Shared Projects are the key here.. I just found out they existed. After creating one, drop the folder/files in the same directory that has .vcxitems file. Now in the project you want to include the shared folder, right click your solution, Add -> Existing Project and select your .vcxitems file.
64,218,118
64,218,227
Strange behaviour while adding string to another string in C++
one is 2, and ans is "000000". string ans = "000000"; ans += string("1", one); cout<<ans<<endl; The output is: 0000001� But I want the output: 00000011 What am I doing wrong?
string("1", one) does not do what you think it does. It does not duplicate the "1" string one number of times. It instead copies the 1st one number of chars from "1", which in this case is the '1' character and the '\0' null-terminator that follows it, which is where the � is coming from in the output. That is not w...
64,218,169
64,220,914
How to execute a program within my program in C++ in Ubuntu?
I am writing a C++ program and I would like to execute a fortune telling program inside of the one I am writing. My program will run the fortune telling program and return a fortune to the user. How do I go about doing this in Ubuntu?
Function system allows you to call another program with arguments. system is defined in stdlib.h as: int system(const char *command); system take a shell command with arguments as const char* and returns the code returned by the command. As you are using C++, you should include C++ header of stdlib.h , cstdlib and use...
64,218,396
64,218,663
Trying to figure out how cmath.h calculates the value of Trancedental functions.But function calling seems to be recursive in header files
I am using Visual Studio 2019. I have written a bare bones code to calculate and print the value of sine when I enter a number as an argument. When I right click the call of sin() using math.h and cmath.h as the headers.It first takes me to the defination of sin in the cmath.h header on line 234.Which lookes something ...
Question is broad, but the answer highlights: Argument reduction to a sub-range like 0 to pi/4. Evaluating using a Minimax approximation e.g. a crafted polynomial divided by another polynomial.
64,218,789
64,218,836
c++ member function argument is not used in the function body, what is this case?
I see this code, it's a class member function definition. But the argument is just std::tuple<> and it is not being used in the function body. What does this mean? (from dlib.net dlib/dnn/core.h) add_layer ( std::tuple<> ) : add_layer() {}
the argument is just std::tuple<> and it is not being used in the function body. There's nothing that std::tuple<> can be used for in the function body. It is an empty class. What does this mean? It is a constructor. It delegates to the default constructor.
64,219,053
64,221,797
How to count HTML tags in C++?
I am new to learning C++ and for a class I am tasked with an assignment to create a parser for HTML files in C++. The program is to input a file name, and output that file's contents, how many lines, character, tags, links, comments, and what percent of characters are in tags. I have most of the program complete, I am ...
Under the assumption that you are dealing with valid HTML5, we can distinguish five cases when you see a < character outside of a comment: either it is the start of a comment and is followed by !--, or either it is the start of a DOCTYPE and is followed by !DOCTYPE, or either it is the start of a CDATA and is followed...
64,219,073
64,219,729
What's the good way to pass data to a thread in c++?
I'm learning multi-thread coding using c++. What I need to do is continuously read word from keyboard, and pass it to a data thread for data processing. I used global variable word[] to pass the data. When word[0] != 0 means a new input from keyboard. And the data thread will set word[0] to 0 once it read the data. It ...
In modern CPP multithreading, u should be using condition_variable, mutex, and queue to handle this. the mutex prevents mutual reach to the queue and the condition variable makes the reader thread sleep until the writer writes what it write. the following is an example static void data_thread (std::queue<char> & dataTo...
64,219,318
64,219,364
Call constructor using args in another function using placement new
I have a class that isn't allowed to have a copy constructor for various reasons (one is because the struct has a pointer to an array that I don't want to delete several times nor do I want to copy/clone it). I'd like to construct the object in a push function. Like to push onto an array. I have the following test code...
Your call to Push() should only be Push(5, 1) instead.
64,219,466
64,219,609
How to hash system time in c++ using SHA1 hashing algorithm?
I was trying to hash system time in c++. I calculated the system time using the chrono library this way. #include<iostream> #include<chrono> #include<ctime> int main() { auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); std::cout<<"The time is "<<ctime(&timenow)<<std::endl; retur...
You probably want #include <openssl/sha.h> for all the available secure hash algorithms. That will give you access to all these functions: int SHA1_Init(SHA_CTX *c); int SHA1_Update(SHA_CTX *c, const void *data, size_t len); int SHA1_Final(unsigned char *md, SHA_CTX *c); unsigned char *SHA1(const unsigned char *d, ...
64,220,138
64,224,350
Accessing tokenization of a C++ source file
My understanding is that one step of the compilation of a program (irrespective of the language, I guess) is parsing the source file into some kind of space separated tokens (this tokenization would be made by what's referred to as scanner in this answer. For instance I understand that at some point in the compilation ...
With the restriction mentioned in the comment (tokenization keeping __DATE__) it seems rather manageable. You need the preprocessing tokens. The Boost::Wave preprocessor necessarily creates a token list, because it has to work on those tokens. Basile correctly points out that it's hard to assign a meaning to those toke...
64,220,141
64,220,178
C++ templates: "type/value mismatch at argument" and "expected a constant type of int, got int"
I'm new to templates so bear with me... I am creating a template called "LookUpTable" which takes 2 parameters 'int' and 'class T'. template<int, class T> class LookupTable{ public: LookupTable<int, T> & begin(); //gives both "errors" //some more code }; and my definition of the function is: LookupTable <in...
The problem is you're specifying the type int as the 1st template argument, but the 1st template parameter is a non-type parameter; which expects some constant expressions with type int. I suppose what you want is to specify the name of the 1st template parameter, then use it as template<int I, class T> class LookupTab...
64,220,242
64,220,299
How do I inherit a constructor from base class in CPP?
I am trying to do an inheritance problem. I have a base class Animal with parameters int height, age, and weight. I also have a default constructor and a constructor with parameters. I have a derived class Dog with the parameter dogType and a constructor with the parameters from Animal and the new parameter, dogType. M...
The correct syntax for inheriting is Dog::Dog() : Animal() { } Dog::Dog(int h, int a, int w, const std::string& dt) : Animal(h, a, w), dogtype{dt} { } Since Dog() is an empty constructor you could define with Dog::Dog() = default The proper way to define the Animal constructor instead is: Animal::Animal() : A...
64,220,243
64,221,323
std::abs can be used in constexpr function, but only if it's templated. Why?
Supposedly std::abs is not constexpr in the standard (even in C++20). But in practice I found out that I can compile it as constexpr under the very peculiar condition that the function is templated. See this completely working example: template<class T> constexpr T f(const T input) { return std::abs(input); } int m...
For a regular function the compiler may know, based on the type of the function parameters, if the inner code can be potentially evaluated in compile time. This is why you get an error for calling std::abs in MSVC and clang. The behavior of gcc is based on its decision to implement std::abs as constexpr which is by the...
64,220,374
64,220,745
Find all differences in an array in O(nlogn) where n is the max range of elements
Question: Given a sorted array A find all possible difference of elements from A, where each element is an integer in the range [1, ..., n]. Also, you can assume there are no duplicates. So max size of the array will be <= n. Note: Total possible differences will be in the range of [1, ..., n-1] because of the above co...
This answer linked by OP suggest the following steps: Assume an array with non-repeating elements in the range [0, n-1].* Create an array of length n, where elements whose index matches an element of the input are set to 1, other elements are set to 0. This can be created in O(n). For example, given in input array [1,...
64,220,414
64,220,485
C++: How to implement private helper function that requires access to protected members of a class without altering header file?
I'm trying to declare and use a generic helper function to do recursion. The issue is, I cannot touch the default header file. We are allowed to linked the default header file and add implementation to another header file, however, I don't know how to add more functions to the class Node declared in the default without...
According to the language rules you cannot add a member helper function without modifying the header file. What you could do: Either create standalone helper function (non-member) and work with the public interface of Node or Create a wrapper, for ex. class NodeWrapper : public Node and work with the wrapper class: ...
64,221,297
64,222,951
C++ Win32api output Unicode from user's input
I realize there may be similar questions, but I have been really stuck for a while now. I'm operating on Windows 10 using C++ and the Win32 API. I need to read a user textbox for a hexadecimal code, something like Ѱ or U+0470, although the 'U+' is not going to be present. After receiving this value, I need to take the ...
You'll need to convert the string L"0470" into a number. It's a base-16 number, so you'd use std::wcstoul from <cwchar>. You can then cast this number to a WCHAR. I assume you know how to turn a single character into a string.
64,221,324
64,221,497
Is eliminating construction of unused object allowed in standard even if constructor has observable side-effects?
Consider the following code: #include <iostream> struct M { M() { std::cout << "M\n"; } }; template <class T> struct Test { Test() { std::cout << "Test\n"; } inline static auto m = M{}; }; int main() { Test<int> t1; //Test t; //(void)&t1.m; } Using the latest GCC or Clang the only "Test" is p...
Yes, it's spelled out in the standard. [temp.inst] (emphasis mine) 4 Unless a member of a class template or a member template is a declared specialization, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist or if t...
64,221,358
64,221,770
Import a C++ DLL into C#
I try to implement a C++ DLL into my C# project. I've given the following header file: #ifdef EBEXPORT const long EBDECL #else const long EBDECL __declspec(dllimport) #endif const long EBCALL __stdcall #if defined (__cplusplus) extern "C" { #endif EBDECL long EBCALL EbInitTcp(long nUnit, const char* pIP, long nIPS...
The imbalance can be caused by a mismatch calling convention (cdecl vs. stdcall) or mismatch function arguments, both in size and type. The C++ calling convention definition is little unusual, it is normally defined with a #define. #ifdef EBEXPORT #define EBDECL __declspec(dllexport) #else #define EBDECL __declspec...
64,221,633
64,221,944
Constructing a vector of string_views from an initializer_list
I'm trying to construct a vector of string_views from an initializer_list< const char * > which worked okay on GCC 9, but after updating to GCC 10 it crashes during runtime. #include <vector> #include <string_view> #include <cstdio> int main() { std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." ...
In this variable definition std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } }; you accidentally used this new C++20 string_view constructor: template<class It, class End> constexpr basic_string_view(It first, End last); So, you only construct one string_view using the start of "Afterrrrrr." as ...
64,221,847
64,222,475
How do I find the letter with the most occurence? c++
I have to make a program where I need to find the most occurrence of a letter string sen; int counter = 0; char letter = '\0'; for(int i = 0; i < 100; i--){ cin >> sen; if(sen == "quit"){ i = 101; }else{ for(int x = 0; x<sen.length(); x++){ if(sen[x] == lett...
You can use simple array map (if working with char strings): #include <algorithm> #include <iostream> using namespace std; int main() { int count[256] = { 0 }; string sen; for (int i = 0; i < 100; ++i) { cin >> sen; if (sen == "quit") { i = 101; } else { ...
64,221,903
64,222,014
Declaring an instance of another class in other class function of the same compilation unit
I get these errors each time I try to declare an instance of another object Hand as a parameter of a method of another class on the same header and source files. Even though the declaration and implementation statements are the same. Errors: Severity Code Description Project File Line Suppression State Err...
You can forward declare Hand before the definition of the Deck class: class Hand; //<-- here class Deck{ private: list<Card> allCards; list<Card*> deckCards; void generateCard(int numberOfCounteries); public: Deck(); ~Deck(); Deck(int numberOfCounteries); void draw(Hand& hand); frie...
64,221,984
64,222,048
Merge two sorts in one
Consider having following array (or c++ vector): vector<int> a {1,3,6,5,41,8,13}; stable_sort(a.begin(), a.end(), [](int a, int b) {return a<b;}); stable_sort(a.begin(), a.end(), [](int a, int b) {return a%2 < b%2;}); This code first sorts vector by value, then it puts all even in first elements. The result is: {e1, e...
Combine the two conditions with the OR operator. Make sure the second clause does not trigger when a % 2 > b % 2: stable_sort(a.begin(), a.end(), [](int a, int b) { return (a % 2 < b % 2) || ((a % 2 == b % 2) && a < b); }); You can make this a bit nicer by making use of the fact that tuples are sorted field by field...
64,222,123
64,239,262
C++ Implementing a timeout function template for class methods
The goal that I want to achieve is for the program to stop the process and return a timeout error if the process exceeds the timeout time. I got a timeout function from the second most voted answer to this question. I ran into an error which says that std::result_of_t is deprecated in c++17, so I re-created it using th...
As the name suggests, std::invoke_result_t is the result type of applying std::invoke. I highlighted the case that applies to you here: INVOKE(f, t1, t2, ..., tN) is defined as follows: ... If f is a pointer to member function of class T: If std::is_base_of<T, std::decay_t<decltype(t1)>>::value is true, then INVOKE(f...
64,222,169
64,222,612
Compiler does not recognize member initializer for std::vector
I want to initialize a std::vector to have a specific length. in the .hpp file I use #include <vector> class foo { foo(){}; ~foo(){}; std::vector<double> pressure (4,0); //vector 4 elements = 0 void readPressure() { pressure.at(0) = 1; pressure.at(1) = 2; pressure.at(2) = 3; pressure.at(3) = 4; } ... ...
Default member initializer (since C++11) only supports brace and equal-sign initializer. E.g. class foo { std::vector<double> pressure = std::vector<double>(4,0); //vector 4 elements = 0 ... }; BTW: We can't use braced-initializer as std::vector<double> pressure{4,0};, because it would initialize the vector co...
64,223,072
64,223,262
Create Link List from variadic arguments
I want to create a link list by taking the variable arguments given at compile time Description below: I have a node something like given below: template<typename T> struct Node { Node(const T& data, Node* next = nullptr ) : m_data(data), m_next(next) {} ...
Do not make this over complicated and just use std::initializer_list. Use of variadic arguments here will be an overkill. Also Node should be an implementation detail of a list. So create a template class List which will be the only thing which uses Node. template<typename T> struct Node { T m_data; Node *m_nex...
64,223,658
64,230,894
How to stop while loop by pressing a button in MFC dialog
I'm working on a dialog based MFC application on Visual Studio 2017 in C++. In my app I have a window which shows text. I'm using an infinite while loop to write numbers to it when I press "Start" button, and I want to stop this process when I press "Stop" button. The window looks like this: For this purpose, In the S...
Every GUI program has a message loop somewhere, that checks for incoming messages from the OS and reacts to them. By creating an endless loop yourself, you block that from happening - that's why you need Task Manager to shut down the program. It also blocks things like window repainting. MFC provides an OnIdle functi...
64,223,712
64,223,775
c++ initialization of const field via initializer-list ":" section
In below code, how can i declare vv to be const: vector<vector<float>> const vv;? Eg. is there any c++0x version that will let me loop in the : ... "initializer-list" section, before the {}? #include <vector> using std::vector; struct ST { vector<int> const x; // simple constructor, initializ. via ": x(x)" vec...
std::vector has a constructor that takes a initializer list, you do not need the loop: struct ST { vector<int> const x; vector<vector<float>> const vv; ST(vector<int> x, std::initializer_list<vector<float>> lv) : x(x), vv{lv} {} }; In case your example is oversimplified and you really...
64,223,720
64,297,973
How to debug crashdump without having dependency to symbol files?
The application which I am debugging crash dumps from the customer has various release cycles. So the PDBs are not maintained for all the releases. whenever we get a crashdump from customers the PDB files are not available. Due to this, it's difficult to analyze crash dumps. I use Windbg to analyze the crash dumps. Win...
TL;DR: if you delete the PDBs, don't complain. Disk space is cheap. A 1 TB hard disk is at 40 €. If PDBs save you an hour of work, it's worth buying one. Turn on NTFS compression, because PDBs compress quite well. whenever we get a crashdump from customers the PDB files are not available Obviously, that's the wrong s...
64,223,754
64,224,643
C++ STL reverse string search, down to a bounding index
Consider std::string reasonStr and a call reasonStr.find(").", sepIndex) which finds the first occurrence of ")." in reasonStr, but earliest at sepIndex. I want to find the last such occurence, earliest at sepIndex. But a call reasonStr.rfind(").", sepIndex) instead seems to start its right-to-left search at sepInde...
To find the last occurence starting earlist at sepIndex, you can create a std::string_view and search that in reverse. It doesn't allocate (copy) anything, it just points to the original data. This is an important note as you must ensure that the string_view refers to an existing object - if the string_view outlives th...
64,223,863
64,227,326
Does an extern variable declaration also declare an (object) entity?
(All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS, with emphasis mine in the standard quotations) Background I'm trying to answer the question whether or not the named variable arr below extern int arr[]; // declaration; type is int[] int arr[10]; // definition; type i...
Unfortunately, confusion between “variable” and “object” exists throughout the standard (consider that [basic.stc.auto] completely neglects the possibility of recursion), including which of those is an “entity”. However, [basic.types]/6 addresses this pretty directly: The declared type of an array object might be an ...
64,223,961
64,224,016
Configure SourceTrail to accept embedded c/c++ header files with @ syntax
I'm attempting to use Sourcetrail (https://www.sourcetrail.com/) to quickly get into some old embedded c/c++ source code for the pic18 series of microcontrollers. I get errors when importing the hardware include files, which uses an exotic method to define the hardware address of the bit addressable hardware registers,...
@ is not a valid token in C, so you cannot use it as a macro identifier either. The easiest solution would be to handle the @ address with a macro, i.e. #ifdef somethingsomething #define AT(address) @ address #else #define AT(address) #endif extern volatile ANSELAbits_t ANSELAbits AT(0xF38); The first definition shou...
64,224,211
64,226,331
no convert function c++
I have this problem constantly I have defined cours class as an object in a student class and now I cannot save it in an array Screenshot of error as presented by IDE list<student> listStudents; FILE* f; f= fopen("s.t.h.txt", "r"); for (int i=0;i<cont;i++) { string arr[4]; fscanf(...
You can't convert something from a datatype that you've made into a string just by willing it to be so. What you can do is initialize the array into a parent datatype, and then add any of the inheritance tree into the array, because it is an "is a" relationship. Another option is to create a "getter". This means adding...
64,224,460
64,224,619
unknown construct/variable declaration in c++
I am fairly new to c++. I have some experience with programming in general and in C in particular though. I have a c++ project written by someone else which I am trying to comprehend at the moment, and it includes several variable declarations in this format: uint64_t(*const col_timestamp)(const uint8_t* col_buf); I ...
This uint64_t(*const col_timestamp)(const uint8_t* col_buf); is a declaration of a constant pointer to function that has the return type uint64_t and one parameter of the type const uint8_t *. For example if you have a function declared like uint64_t func_col_timestamp( const uint8_t *col_buf ); You could declare an...
64,224,750
64,228,629
BGRA to YUV420 FFmpeg giving bad output
My purpose is a screen recorder. I am using the Windows DXGI API to receive screenshots and I'm encoding the screenshots into a video using libx264. Feeding BGRA images directly to libx264 is producing weird colors in the output video. So, to get correct colors, I am trying to convert the BGRA to YUV420p. To speed up e...
Change BGRA.linesize[0] to be 1920*4. You see this 3 images pattern because 1240*3 == 1920*2
64,226,096
64,226,923
Why type alias is allowed as name of variable?
What rule makes the following code compile without error: using integer = int; struct Foo { int integer; }; int main() { Foo f; int integer; f.integer; } using is of course not a simple replacement for #define integer int, but what makes this code apparently well-formed while int int; would make it i...
While it's a little surprising that one can access a name declared in an outer scope, and then later hide that name , it's just a straightforward application of the rules for scoping: A name declared in a block (9.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6....
64,226,152
64,226,372
C++ built-in fixed-width types with no additional includes
According to this: https://en.cppreference.com/w/cpp/types/integer, such types like int32_t are Defined in header <cstdint>. VS2019/C++17 doesn't compile int32_t i = 5; until I #include <cstdint>. Is it normal that I need including some headers to use the built-in types? Are there other fixed-width types/typedefs/macro...
Is it normal that I need including some headers to use built-in types? int32_t is not a "built-in" (or fundamental, as the standard calls them) type. It is a type alias defined in the standard library. Yes, it is normal to need to include headers in order to use the standard library. Note that <cstdint> is not guaran...
64,226,730
64,226,756
Cannot execute the else statement it gives out an error
** I wanted to print each integer (n) between b and c such that if n>9 else statement executes and prints out each integers in the form of even or odd.The if statements executes if the following condition of the variables of c and b are true.So there is no problem if i input c and b both <9. ** #include <iostream> #inc...
The condition 1<= c <= 9 won't work as you expected. 1<= c <= 9 is treated as (1 <= c) <= 9. 1 <= c here will be treated as 0 or 1, so the condition (1 <= c) <= 9 will always be true. You should use 1 <= c && c <= 9 instead.
64,226,739
64,230,530
Box2D Collision Issues
Very new at Box2D, would appreciate help. I've got a simple function that takes in a b2World and b2Body*, where the body is supposed to fall until it collides with a ground box (already created in main()) The code is essentially as follows: void snake::update(b2World world, b2Body* snake) { bool running = true; ...
Basically the way you had your parameter set before you were passing the b2World object by value in your original function head. void snake::update(b2World world, b2Body* snake) This means you are creating a copy and if this copy is being modified, the original object that was passed to the function remains the same. ...
64,226,901
64,227,401
Default initialization of unused constant variable template
The following program: template<typename = void> const int n; is compiled successfully by gcc, but clang gives an error: # error: default initialization of an object of const type 'const int' const int n; ^ = 0 which makes sense. gcc does give an error if n is used, but is a diagnostic required...
is a diagnostic required even if n is unused? No. The applicable rule is [temp.res.general]/8: The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic required, if: no valid specialization can be generated for a template or a substatement of a constexpr if stat...
64,226,910
64,226,954
Is it possible to use std::visit without lambdas (just a simple class)?
I'm trying to experiment with making a visitor with just a simple class, with overloads of operator() for each type in the variant. I expected this to work (as it's how I assumed it worked for lamdba functions): #include <variant> #include <iostream> using Example = std::variant<int, float, bool>; class ExampleVisito...
Yes, it's certainly possible. The issue is, your overload set inside ExampleVisitor is private, so std::visit doesn't find an appropriate operator() to use (as far as it can tell, no operator()s exist at all). You can fix this by just making the overload set public: class ExampleVisitor { public: // ... all ove...
64,227,135
64,227,177
Delete few first zeros in a string
This is what I have been working on: Giving input as 2 positive integers (at most, 100 digits). Compare the two integers. Note: The 2 integers can contain leading zeros. (that means you have to remove zeros first) Because 100 digits is too long, I use a string datatype. But in my program below, it just returns '=' I de...
The lines while (str1[0] != 0) str1.erase(0, 1); while (str2[0] != 0) str2.erase(0, 1); will erase all characters in the strings because the value 0 is used as the end mark of strings. To compare with character zero, you should use character literal '0' (character surrounded with ''). Also the loop should be "loop whi...
64,227,352
64,227,701
Recommended way to perform a cast to a smaller type on micro controller in C++
I am programming for the Arduino Due, which is based on a 32-bits micro controller. I want to read an ADC result register (it has width 32 bits if I am right, but it has a true maximum width of 12 bits, which is the resolution of the ADC), and write it at a given location in an array of integers with width 16 bits. Thi...
A 'safe' way to do the cast is to first dereference the pointer to the 32-bit data, then mask out the upper 16 bits of that data item, then static_cast the result to your 16-bit destination data: Buf[i] = static_cast<volatile uint16_t>( *(ADC->ADC_CDR + channels[i]) & 0x0FFFF ); It is always best to use the 'simpl...
64,228,197
64,228,354
Range concept for a specific type
Is there an already defined concept for specifying a range of a specific type, in C++20 or in the ranges-TS? Something like: template < class T, class InnerType > concept RangeOf = requires(T&& t) { requires std::same_as< std::remove_cvref_t<decltype(*std::ranges::begin(t))>, InnerType ...
No there isn't. The way to spell that particular concept would be: template <typename R, typename V> concept RangeOf = range<R> && same_as<range_value_t<R>, V>; But then it turns out there's a bunch of very closely related things you might want to check as well. You might actually want to look at the reference type ra...
64,228,393
64,228,715
Lambda capture scope
I'm struggling to understand the scope and ownership of lambda captures, why does the following code work?: #include <iostream> struct Foo { void setCallback(std::function<void()> f) { callback = std::move(f); } void trigger() { callback(); } private: std::function<void()> callback; }; struct Bar { ...
Hello Your code does not work because bar is descoped before the lambda that captured it is executed. The lambda uses a dangling reference. Here is an updated sample that will convince you, that if it works in your example it is simply because nothing else has been allocated at the address where bar was initially store...
64,228,413
64,228,734
Consecutive layout of member variables in memory?
Is it a universal rule that C++ stores variables in memory in the same order as are in the source? So if I define a lot of 4-byte member variables consecutively with different privacy in 32-bit ordering and 32-bit architecture compiler puts them to consecutive words in memory?
Is it a universal rule that C++ stores variables in memory in the same order as are in the source? No. Such rule does not exist in C++ for variables in general. However, member variables with same access control are stored in the same order as declared, yes. The order between members with different access control is ...
64,228,468
67,401,859
Add custom header in CMAKE project Visual Studio
I've installed a cross-compiler in a docker image. I've deployed some custom libraries in the cross-compiler folder. Visual Studio 2019 can compile my code, but is not able to open the custom folder. #include <owa4x/pm_messages.h> #include <owa4x/owerrors.h> I've tried to add the directory in the rsync command from cm...
The header file were locate to C:\Users\myuser\AppData\Local\Microsoft\Linux\HeaderCache\1.0\-1280310364\opt\gcc-linaro-5.3-2016.02-x86_64_arm-linux-gnueabihf\lib\gcc\arm-linux-gnueabihf\5.3.1\include C:\Users\myuser\AppData\Local\Microsoft\Linux\HeaderCache\1.0\-1280310364\opt\gcc-linaro-5.3-2016.02-x86_64_arm-linux-g...
64,228,959
64,229,163
Constructing a string_view from a range of chars
While a span can be constructed from a range, a string_view cannot be constructed from a range of chars. Thus, for example, the following code is required: // assume chars_span is a span of chars std::cout << std::string_view(chars_span.data(), chars_span.size()); // or: std::cout << std::string_view(chars_span.begin()...
P1391r3 proposed this, though this was dropped in the version that was eventually adopted for C++20: P1391r4. The reason for the drop unfortunately is completely absent from the paper (indeed, the paper does not even mentioned that it was dropped). However, a follow-up paper, P1989R0 presents the issue as what happens ...
64,229,232
64,230,140
deduce function parameter types of overloaded member function by argument count
Currently I'm looking for some way to get the parameter types of an overloaded member function by argument count and instance type. In my case we know the name, the return type (void) and the argument count. In addition there can't be a second overload with the same argument count and the functions are never cv nor ref...
With limited number, you can do something like: template <std::size_t Size> struct helper; template <> struct helper<0> { template <typename C> std::tuple<> operator() (void (C::*) ()) const; }; template <> struct helper<1> { template <typename C, typename T1> std::tuple<T1> operator() (void (C::*) (T...
64,229,743
64,229,939
TCP high CPU multiclient server
I am curious about best design of TCP server to handle 500+ active connections, that sending a stream of data to me. The biggest problem here is that my data handler uses active CPU and can consume more time than happens between client sending chunks. Client records a sound with microphone and sends it to my server in ...
I suppose the key question to think about is, what do you want to have happen when data is being sent to your server faster than the server can process it? E.g. imagine your server's CPU is fast enough to process 100 audio streams simultaneously in real time, but 200 clients are connected and sending audio. One way to ...
64,230,710
64,232,249
How does musl's GCC wrapper differ from musl's cross-compiler?
I am trying to compile various programs such as MariaDB with a musl toolchain. That is, I don't want any dependencies on glibc or GNU's linker after compilation has finished. Thus far, I have been using musl's GCC wrapper, musl-gcc to compile things. But, with larger programs like MariaDB I struggle to get all the nece...
All the wrapper does is remove the default library and include paths and add replacement ones. Otherwise, it relies on the compiler's view of the ABI being sufficiently matched that a GCC that thinks it's targeting glibc (*-linux-gnu) works with a musl (*-linux-musl) target. A full GCC toolchain has a number of "target...
64,230,791
64,230,943
Is there a way of using `std::optional` optionally for all the members in a class
Consider the classes struct Foo1 { int n; double m; }; and struct Foo2 { std::optional<int> n; std::optional<double> m; }; In reality the number of members is greater than this. Is there a way I can templatise this to one class, something like template<class T> struct Foo { T<int> n; T<...
You can write a simple switch that chooses between a type or its optional: template <typename T, bool O = false> using optionally_optional = std::conditional_t<O, std::optional<T>, T>; And then, use it as follows: template <bool O> struct Foo { optionally_optional<int, O> n; optionally_optional<double, O> m; }...
64,230,877
64,231,216
function redefinition: const parameter
1. In global scope, this gives error: redefinition of 'f' #include <iostream> using namespace std; void f(int x) { cout << "f" << endl; } void f(const int x) { cout << "f (const)" << endl; } // error: redefinition of 'f' int main() { } 2. Defining two copy constructors (one with const, the other without) compile...
There is a fundamental difference between the two. One is an overload between int and const int. It's a value type. There is no semantic difference for the caller, the effect of const only affects the body of the function. void f(int); int a = 1; const int b = 2; f(a); // must copy the int value into the argument f(b...
64,231,131
64,231,789
list insert Iterator outside of range error
I have this function void Deck::draw(Hand &hand) { int random = (rand() % deckCards.size()) + 1; list<Card*>::iterator cardID = deckCards.begin(); for (int i = 1; i < random; i++) { cardID++; } Card* selected = *cardID; deckCards.erase(cardID); hand.getHandCards().insert(hand.getHandCards().end(), selected); } ...
This function returns a copy of handCards list<Card*> Hand::getHandCards() const { return handCards; } So, below one temporary copy is created and you pick its end() iterator. another temporary copy is created and you use the end() iterator from the other copy to insert. hand.getHandCards().insert(hand.getHandCa...
64,231,392
64,232,030
Is function name also a namespace?
I'm new to c++ and was reading up about namespaces on dfs-minded and came across this, using my_fancy_app::HelpfulFunc; // bring it to the scope HelpfulFunc(); // or just my_fancy_app::HelpfulFunc(); // fully qualified name My doubt is why HelpfulFunc is appended to 'using myfancy_app'. Can't we just do: using my...
Is function name also a namespace? No. Function name is not a namespace. my_fancy_app::HelpfulFunc(); // fully qualified name The comment is a bit wrong. That is a qualified name, but not a dully qualified name. A fully qualified name would be ::my_fancy_app::HelpfulFunc.
64,231,614
64,231,759
C++ Compiler picking the wrong overloaded function
I am trying to implement std::list, for learning process as I just started studying linked and doubly-linked list in school. Here is the code stripped down to only the part that is causing. Stripped down to make reading better to be able to analyze the problem. For the full code (that is still a working in progress) he...
The non-const version of an overload is selected if the object is not const. If this wasn't the case, the non-const version would never be picked. iterators are required to implicitly convert into const_iterators in containers as specified in the standard: X​::​iterator ... any iterator category that meets the forward...
64,231,878
64,231,973
Why can my child object not access its parent's function?
Even if I try the other getter functions which are defined in cpp files my compiler does not let me do so. If I try boar.getEnemyName(); it tells me expression must have class type. class Enemy { public: Enemy(std::string enemyName, int enemyHealth, int enemyAttack, int enemyDefense, int enemyMoney) { ...
This line: Boar boar(std::string name = "Boar", int health = 20, int attack = 1, int defense = 1, int money = 10); is not constructing a Boar, it's actually a declaration of a function named boar that returns a Boar, and takes 5 default arguments. This explains the error expression must have class type, when you do bo...
64,232,212
64,232,363
Why is sorting a std::vector of std::tuple's faster than sorting a vector of std::arrays?
I was curious to see whether sorting a vector <vector<int>> would be slower than sorting a vector <array <int, 3>>. The dimensions of the vector is 1000000 by 3, and below is my driver code implementing this: #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> using namespace...
While the disassembly for the whole programs are too large, this demonstrates the core difference between operator< for array and tuple: https://godbolt.org/z/h1Y33e Essentially, in the tuple version, you have a fixed comparison of 3 elements whereas in the array version, you have a loop. Though I'm surprised that the ...
64,232,315
64,233,603
How to get value type from string using nlohmann json?
string I get { "players": [ { "SteamId": "765611974898245625", "CommunityBanned": false, "VACBanned": true, "NumberOfVACBans": 1, "DaysSinceLastBan": 1011, "NumberOfGameBans": 1, "EconomyBan": "none" } ] } I nee...
I've not used that parser before, just read its readme.md. It appears that both of these methods work: bool b1 = j3.at("players")[0].at("VACBanned"); bool b2 = j3["players"][0]["CommunityBanned"]; Your JSON has one root node players that is an array; its first element is accessible by [0]; from that point you can acce...
64,232,967
64,233,299
I'm getting this weird error when testing my code
I was doing a practise task on codewars.com and I had finished my code and tested it. It worked and so I attempted to hand it in, but then I got thrown 2 cases where my code doesn't work. I wanted fix my mistakes but I don't understand what the error/ failed attempt means. Here's an image of the error: Here's the erro...
In general the size of the string str can be less than the size of the string ending. Thus the value of the variable dif can be negative long long dif = size - end; Used in the call of the member function substr string endi = str.substr(dif, end); it is converted using the usual arithmetic conversions to a big unsign...
64,233,342
64,233,519
Adding an exit statement to this?
Here's my problem. I have to read a line from the console, for example: Name,Area,Cost Then using the comma as the delimiter character, it has to name, area and cost and place them into their corresponding variable to be placed in a hash table. Then using a loop the program needs to continuously do this until the user...
By default, std::getline() reads until '\n' (Enter) or EOF (Ctrl-Z on Windows, Ctrl-D on *Nix, etc) is encountered. If you specify a delimiter other than '\n', it will not stop reading on '\n' anymore. So, getline(cin, name, ','); will not stop reading when the user types in exit and presses Enter, it will stop only ...
64,233,643
64,233,727
why references to members of a class in a vector point to the same value for different objects?
Let's have a simple class: class Var { public: explicit Var(const std::string& name, const double v) : value(v), ref(value), _name(name) {}; ~Var() {}; double value{}; double& ref; void print() { std::cout << _name << ":\n"; std::cout << "\tvalue = " << value << " (" <...
std::vector requires an appropriately written assignment operator. The one the compiler provides is useless for your class since the reference is not rebound. So you need to write it out yourself. And that's not trivial: Assignment operator with reference members The best thing to do though is to drop the reference cla...
64,233,648
64,233,766
How do I display my array map alphabetically?
So I've been trying to find ways to make my array map display in alphabetical order but I couldn't really grasp the idea on how to Here's what I've tried so far: int count[256] = { 0 }; string sen; cin >> sen; for (auto c : sen) ++count[static_cast<unsigned char>(c)]; for (int i = 0...
You are using characters as array indexes. So simply loop through the array from characters a..z, A..Z, 0..9, etc to display the counts in your desired order, eg: int count[256] = {}; string sen; cin >> sen; for (auto c : sen) ++count[static_cast<unsigned char>(c)]; for (int i = 'a'; i <= 'z'; ++i) { ...
64,233,711
64,260,730
Is there a faster way to concatenate two integers bit-wise?
For my C++ program I want to bit-wise concatenate two 32-bit unsigned integers into one 64-bit unsigned integer. Similar questions have been asked multiple times and the answers mostly looks similar to this: #include <cstdint> #include <iostream> int main() { std::uint32_t leftHalf = 1; std::uint32_t rightHalf...
The combined information of the discussion leads to the following answer to the original question: It depends. Also, a faster way most likely won't make a difference. Depending on the surrounding code, the following techniques are possible: One can store the 32 bit parts as two elements in an array and then memcpy tha...
64,234,001
64,234,239
Struct and Classes member structure c++
When creating struct or classes, usually attributes don't have a specific value at all, and when they call the constructor, they assign the values that they want. struct Point{ int x; int y; } Point myPoint = {0,0}; However when is appropriate the following case? struct Point{ int x = 0; int y = 0; } ...
However when is appropriate the following case? [example with default member initialisers] Depends on what standard version you use, and what you need from the class: It is not appropriate prior to C++11 because that is when default member initialisers were introduced to the language. It is not appropriate prior to ...
64,234,895
64,234,944
Can I get these template arguments deduced?
I left out the template parameters where the question marks were and I got an error, for obvious reason, but what to do in this case? I essentially want the two parameter arguments < ? , ? > to be the types of the getter and setter. template <typename TGet, typename TSet> class Object {public: Object(int i, float f...
Let the compiler deduce the types for you: template <typename ... TArgs> // removed 'typename T' static auto create(int i, float f, TArgs ... args) { // ^^^^ return new Object(i, f, args...); } And Creator::create( 7, 0.f, []() { return "Called Getter"; }, [](const char* i) { std::cout << "Called...
64,235,076
64,235,103
Replace if else with Switch statement
I am working on the code below and trying to use switch statement instead of if/else. The problem is that I cannot figure out how to get the switch to work. A few things a tried: I know that every time an expression is equal to the case constant, the code then will be executed. Example: switch (expression) { case ...
The problem, from eyeballing, appears to be because you return 1 outside the switch statement, which is why the code after it never gets run. You should replace your case 4 with a default: label and move the return 1; into that case as well as add a break statement under case 3.
64,235,172
64,235,511
Can't launder(void), therefore free() is UB?
I am trying to determine what the strictly conforming pattern for using memory allocators with C++17 is. Specifically, moving away from the working in practice UB pattern: example * foo = (example*)malloc(sizeof(example)); // no object here, don't use foo! Therefore placement new into the allocated memory. Something li...
What makes free(ex) well defined? free requires a pointer whose address is one directly returned by a call to malloc. You have provided that. Why wouldn't it work? Why is launder(void) forbidden? Because it makes no sense. std::launder<T> returns a pointer to an object of type T within its lifetime whose address is...
64,235,178
64,235,321
How to initialize inherited values, and have abstract methods c++?
This is kinda multiple questions in a single question. First off, is there a way to initialize inherited values in C++? In other words, this is what I mean in java : // Class X public class X { int num; public X(int num) { this.num = num; } } //Class Y public class Y extends X{ public Y() { ...
First: You want to learn about initializer lists. For your first code snippet, the appropriate code would be class X { int num; public: X(int t_num) : num(t_num) { } // We can use initializer lists to set member variables }; class Y : public X { public: Y() : X(5) { } // No need to have anything in the bod...
64,235,206
64,248,100
Can i forbid vector to reallocate objects?
Let's say we have a vector of double (values) and a vector containing objects that store pointers to the elements of the vector of double (vars): class Var { public: explicit Var(double* v) : _value(v) {}; ~Var() {}; const double get() const { return *_value; }; void set(const double v) { *_value = v; ...
The key is objects after adding are never deleted Rather than store pointers/iterators/references to elements of the vector, store a pointer1 to the vector and an index. class Var { public: explicit Var(std::vector<double> * vec, size_t index) : vec(vec), index(index) {}; double get() const { return v...
64,235,376
64,235,401
Friend function can't access the private variables
I am trying to overload the << operator to display a matrix, but it says that none of my private members can be accessed. In my header file, I have: friend ostream& operator<<(ostream& os, const matrix& out); and for my private members I have: private: int p_rowSize; int p_rowSize; vector<vector<double> > p_matrix; I...
A friend function has access to the data members, but since it's still a free function (rather than a member function) you need to specify which object you're accessing using out.p_rowSize, etc. ostream& operator<<(ostream& os, const matrix& out) { for (int i = 0; i < out.p_rowSize; i++) { for (int j = ...
64,235,474
64,235,591
I'm having trouble understanding a particular piece of syntax
I'm having trouble understanding what a specific syntax accomplishes in a piece of code. I understand what the code accomplishes overall, I'm just trying to understand exactly how it works so it's no longer just "magic". The line I'm having trouble with is the last line, however I do understand what is happening befor...
L" ABCDEFG=#"[pField[y*fieldWidth + x]]; is the piece of syntax where I really just am not sure what I'm looking at, or even what this is called. Let's break it down, so the following L" ABCDEFG=#" has the type wchar_t const (&) [11] You can check that with static_assert(std::is_same_v<decltype(L" ABCDEFG=#"), wch...
64,235,510
64,235,646
How to use fold expression to instantiate each type in a variadic template function?
I am trying to create an "object manager" that will create and store instances of a template class. The class takes one template argument and inherits from a base class to allow instances with different template args to be stored in the same container. The types that will be used as template arguments will be provided ...
If I understand correctly what do you want, you're looking for std::vector<A*> a_vec { new B<Types>{}... }; But this isn't "fold expression"; it's a simple variadic template pack expansion and it's available starting from C++11. An example of "fold expression" (available from C++17) can be the following std::vector<A*...
64,235,635
64,235,662
C++ no instance of constructor matches the argument list
I've been coding a dll and it is almost finished, the final issue I have is this. Argument list consists of: (const char [23], const char [23], const char [21], const char [24], const char [24], const char [24], const char [24], const char [17], const char [42]) The above error displayed at this place in my code... ...
String literals are not modifiable, and therefore cannot be stored as char*. You can use const char* instead: std::vector<const char*> monitors = { ... }; Or, as pointed out in the comments section, you could consider std::vector<std::string>. That would be preferable if there is no special need to store these liter...
64,235,651
64,235,928
How is 'std::thread' is able to determine the number of variadic arguments passed to the constructor
When calling the constructor of std::thread you pass a function and its desired arguments. How does std::thread determine the total number of arguments meant to be passed to the function? #include <iostream> #include <thread> void task(int i, char c, bool b) { return; } int main(int argc, char** argv) { std::...
The std::thread constructor is implemented using a variadic template: template< class Function, class... Args > explicit thread( Function&& f, Args&&... args ); Where: Function is the type of callable object that will be invoked by the thread (whether that be a function, a lambda, a functor, etc). Args is the list of...
64,236,103
64,236,177
Load shellcode from file to char* comes strange characters in end of text
I have a char array[] and is like following: // MessageBox char xcode[] = "\x31\xc9\x64\x8b\x41\x30\x8b\x40\xc\x8b\x70\x14\xad\x96\xad\x8b\x58\x10\x8b\x53\x3c\x1\xda\x8b\x52\x78\x1\xda\x8b\x72\x20\x1\xde\x31\xc9\x41\xad\x1\xd8\x81\x38\x47\x65\x74\x50\x75\xf4\x81\x78\x4\x72\x6f\x63\x41\x75\xeb\x81\x78\x8\x64\x64\x72\...
The issue is that the printf format specifier "%s" requires that the string is null-terminated. In your case, the null-terminator just happens to be after those characters you're seeing, but nothing guarantees where the null is unless you put one there. Since you're using C++, one way to print the characters is to use...
64,236,475
64,252,221
Print the latest C++ standard that gcc supports
The GCC-family compilers accept an argument to specify the language standard that the compiler can use. For example, gcc has --std=gnu++20 (or --std=gnu++2a) and gcc has --std=gnu18. What I expect is a way (bash script preferred) to print the latest standard supported by my local gcc. So far I cannot even find a way to...
Much thanks to @ssbssa. Here's a draft version of the bash script that works as intended (on gcc 10 for C++ standards): $ gcc -v --help 2>/dev/null | egrep "gnu\+\+[^I]+ISO [^1]" -std=gnu++11 Conform to the ISO 2011 C++ standard with GNU extensions. -std=gnu++14 Conform to the ISO 2014...
64,236,532
64,236,579
Invalid Conversion int* to int while attempting to get p_thread id to int
For some code I am writing I am trying to get a threads but I keep getting an error. I am programming on linux in visual studio code. This is the code: void* start(void *s) { int me = (int*)s; //int me = pthread_self(); printf("Entered: %d\n", me); Lock(me); printf("TEST 1"); for (int i = 0; i...
int* is a pointer to a value, not the value itself. You have passed a value cast as a pointer and you should cast it back to a value: int me = reinterpret_cast<int>(s);
64,236,604
64,237,291
Template class method specialization fails when type is a pointer
I have a template class called Vector and I want to specialize one of its methods called my_compare depending on the type that the class takes in. I am able to successfully specialize it for most types, however the specialization will not compile if I am using a pointer type. At top of cpp file: template <typename T> c...
It's a little subtle, but it's because const char* is not the same as char* const. Your function my_compare(const T a, const T b) expects a const T. T in this case is char*. So you want a constant pointer not a pointer to a constant. The rules for adding qualifiers allow you to put const and volatile to the left of the...
64,236,717
64,236,886
C++ alternative to pre-processor #ifdef / #endif
I have a StopWatch class which I use to measure execution time. I instantiate several different stopwatches to log execution time by category. For example: #ifdef EXEC_TIME_PROF StopWatch func1sw; StopWatch func2sw; #endif void foo() { #ifdef EXEC_TIME_PROF func1sw.start(); #endif func1(); #ifdef EXEC_TIME_PROF fu...
You can just use the macro to switch between a class that does something and a class that does nothing at all. The compiler should recognize that and exclude it from compilation. #ifdef EXEC_TIME_PROF // your actual implementation class StopWatch { // ... }; #else // completely empty implementation class StopWa...
64,236,928
64,274,541
undefined reference to `hostGetByName' VxWorks
I am trying to compile a simple vxworks RTP app. I am getting undefined reference to `hostGetByName'. This function should be available in user space according to the documentation, and ive included the necessary layer "IPNET_USRSPACE" in the VSB but still getting the error. Any ideas what im missing? /* includes *...
Looks like linker is not picking net lib. -lnet will do the work.
64,237,439
64,237,554
How do I print multiple inputs and outputs in C++?
I'm trying to solve a problem on a competitive programming book where the output only appears after entering in the last input. I seem to have gotten the logic down but I'm still confuse as to how to do the input/output portion. Here is the code: #include <bits/stdc++.h> int main() { std::ios_base::sync_with_stdio...
Use while(cin >> word){ ... your code ... } to read until EOF (End Of File) in case every line only contains a word (no spaces allowed). You can keep the output as it is.
64,238,261
64,238,720
Folder "Microsoft Visual Studio 14.0" Is Missing
I'm trying to add pthread library to Visual Studio 2017 (I'm using Windows 10 OS). I'm using the following guide from another post tat I saw, but I can't find the "Microsoft Visual Studio 14.0" folder in "C:\Program Files x86". I have Visual Studio 2017 and It's working. I've checked and I've installed the Visual Studi...
Since visual studio 2017 visual studio is installed in C:\Program Files (x86)\Microsoft Visual Studio\<version>\<edition> by default e.g. C:\Program Files (x86)\Microsoft Visual Studio\2017\Community. There are other changes to the internal layout of files within the visual studio directory too. Your guide seems to onl...
64,238,277
64,238,423
Can I use cin inside a function call mult(); to allow the user to input 2 ints?
#include <iostream> using namespace std; void mult (); int main() { cout << "Please enter two integers: "; mult(); } void mult(int a, int b){ int ans = a * b; cout << "The answer is: " << ans << "." << endl; }
@imran is correct. As he said, you can pass arguments after taking inputs or you can take inputs in mult() functions by declaring variables there itself. #include <iostream> using namespace std; void mult (); int main() { mult(); } void mult(){ int a,b; cout << "Please enter two integers: "; cin>>a; cin>>b; int ...
64,239,530
64,239,670
Can I use template parameter as variable?
I want to allocate memory according to the template parameter like this: enum typeFlag { kFloat32 = 0, kFloat64 = 1, kFloat16 = 2, kUint8 = 3, kInt32 = 4, kInt8 = 5, kInt64 = 6, kBool = 7, kInt16 = 8 }; template<typename dtype, typename ctx> inline TBlob<dtype,ctx>::TBlob(const size_t &size): shape_{size} { switc...
It seems you want to map a non-template (enumerator) parameter to a type: #include <cstddef> // Platform-independent type descriptions. enum class TypeFlag { kFloat32 = 0, kFloat64 = 1 // ... }; // Platform-specific TypeFlag to type mapping. template<TypeFlag FLAG> struct MappedType; // Specialize type mapping f...
64,239,554
64,240,105
Variables does not accept more than 3 inputs
I'm having minor difficulty that infuriates me. Can someone help me out? Both int boo (books) and double pri (price) doesn't accept more than two inputs. Thanks in advance. #include <iostream> #include "Customer.h" using namespace std; int main() { int id; int boo; //books double pri; //price ...
You need another variable. The moment this line happens: cin >> boo; you are wrinting the new value into boo. It does NOT get added to boo. The reason why you think it gets 2 values is because of this: boo += boo; which is effectivly: boo = boo + boo; To fix your code you need anther variable that gets the value fro...
64,239,850
64,240,054
clang 10 & OpenMP on range-based for error (docs say should be ok)
I am testing clang 10.0 on an c++17 & OpenMP project and get errors when #pragma omp parallel for is used on range-based for. Release notes for clang 10, in the OpenMP Support in Clang section, say quite clearly: Added support for range-based loops. When I compile a MWE with clang++-10 -fopenmp -std=c++17 (see https:...
Support for range-based for loops was added to OpenMP 5.0, and, as is also described in the Clang 10 Release Notes that you link to, you need to explicitly use the -fopenmp-version=50 option to activate support for it: OpenMP Support in Clang Use -fopenmp-version=50 option to activate support for OpenMP 5.0. Thus, if...
64,240,126
64,240,272
How do I solve this overloading error (c1) condition?
How can I use the operator keyword or any other way to solve this problem? #include <iostream> struct Counter { Counter(int count_) : count(count_) {} int count; }; int main() { Counter c{0}; // Error: could not convert 'c' from 'Counter' to 'bool' if (c) { std::cout << "true\n"; } else { std...
You can define a user-defined conversion function to bool. #include <iostream> struct Counter { Counter(int count_) : count(count_) {} // User-defined conversion to bool operator bool() const { // Arbitrary predicate: return false if 0, true otherwise. return count != 0; } int cou...
64,240,762
64,240,865
c++ iterators, alternative syntax?
For some object V that is iterable, iterating on it commonly uses this syntax (here with std::transform) std::transform(V.begin(), V.end(), V.begin(), /*somelamda*/ ); Here V is specified 3 times. One would think that an overloaded (albeit less flexible) function could exist for the common use-case. std::transform(V, ...
The verbosity of the .begin()-.end() pattern is a well-known (minor) issue. C++20 will mitigate this: #include <ranges> std::ranges::transform(V, dest.begin(), /* some function */); But note that the second argument is mandatory (as opposed to your snippet), because a destination of the result of the transformation w...
64,241,182
64,242,205
Random Device member class gives same sequence?
My problem is as follows: I've got a class that holds a vector of another class that have to use random number generators. One way of implementation gives me a compile error 'error: use of deleted function ‘Ant::Ant(const Ant&)’ and a second approach gives me identical results in the repeated runs of the algorithm in m...
The problem is the random_device that is not copyable. There are 3 solution: Static Variable : you can define a static variable in the Ant class. Singleton : you can define a singleton variable for the random_device Global random_device : you can define a global variable for the random_device The solution is not triv...
64,241,278
64,241,822
Using mmap with C++ and dynamic containers
I am trying to use mmap for mapping and sharing data between processes on my device. My target is an embedded device running Embedded Linux My processes are implemented using C++, and using containers such as std::list and std::map. Obviously the size of the containers are changing as the program runs. If I use a struc...
For the length parameter, can I use sizeof(myStruct) + myStruct.list1.size() for example ? No, because: list.size() is the count of elements in the list. You would need list.size() * sizeof(int) to store the bare elements, but that doesn't account for the storage of list itself or its node overhead ... you probably...
64,241,283
64,241,546
Difference between __int32 vs int vs int32_t (again)
The answers around the web (one, two) only tell parts of the story, and omit some details that I would love you to help me to clarify: int, by the C++ standard, must be >= 32 bits. Different compilers (implementations) can make int to allocate different amount of bits by default. So Compiler A can make int to allocate...
Which one of my guesses are correct? int, by the C++ standard, must be >= 32 bits. Not correct. int must be >= 16 bits. long must be >= 32 bits. Different compilers (implementations) can make int to allocate different amount of bits Correct. ... by default. I don't know of a compiler with configurable int siz...
64,241,321
64,637,358
SimpleINI library - can't compile a code with SI_NO_CONVERSION defined
I use SimpleINI library on Linux. There is the following comment: // Defines the conversion classes for different libraries. Before including // SimpleIni.h, set the converter that you wish you use by defining one of the // following symbols. // // SI_NO_CONVERSION Do not make the "W" wide character version of ...
SimpleIni.h only defines SI_Case and SI_NoCase when either of SI_CONVERT_GENERIC, SI_CONVERT_ICU or SI_CONVERT_WIN32 is defined. This leaves SI_Case and SI_NoCase undefined when (only) SI_NO_CONVERSION is defined, which causes the CSimpleIniTempl template instantiation to fail, with the related compile errors. This is ...
64,241,683
64,242,120
Pointer-interconvertibility of derived and base class objects and the Standard's wording on it
I'm trying to understand when I can safely cast a derived object to a base subobject through a pointer to void (I think it should be the same as reinterpret_cast). But the Standard's wording on this, which I could find, confuses me. First of all, Two objects a and b are pointer-interconvertible if: — one is a standard...
The point is in definition of standard-layout class. From http://www.cplusplus.com/reference/type_traits/is_standard_layout/: A standard-layout class is a class (defined with class, struct or union) that: has no virtual functions and no virtual base classes. has the same access control (private, protected, public) fo...