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
65,873,280
65,873,456
Derived classes and function hiding
Consider the following example: class A { public: int foo() { return 1; } int bar() { return foo(); } }; class B : public A { int foo() { return 2; } }; int main() { auto b = B(); return b.bar(); } Why does main() return 1 insted of 2? Is foo() not the most visible function for B? Does there ...
This is what virtual is for! The function you're calling, A::bar(), doesn't know that the full object is a B. It only knows the A context. You can also think of it as doing a call to this->foo(), where this is an A* (because it is). If foo were virtual, the call would work as you expect: looking up the most-derived ty...
65,873,450
65,873,801
Why does std::literals operators not automatically export when include their correspond header?
There are some literal operators in the std::literals namespace with their corresponding header such as operator""s, operator""sv etc. I wonder why those operators are not automatically export when including the corresponding header since they cannot conflict with each other or user-defined literals operators which mus...
In C++, a using declaration cannot be undone. Once it's there, every piece of code that follows it (within its scope) will have its name lookup rules affected by that directive. A global using statement is therefore somewhat dangerous. It is even more dangerous in a header, as this will inherently affect the behavior o...
65,875,424
65,875,627
Assigning char x[] array to char* ptr
I receive a character address and I want to have the character pointer hold the values in the character array void assign(char set[]) { m_ptr = new char[strlen(set) + 1]; strcpy(m_ptr, set); // OR m_ptr = set; Are both ways okay? I also want to avoid memory leak as well, but I do have a destructor so...
First version void assign(char set[]) { m_ptr = new char[strlen(set) + 1]; strcpy(m_ptr, set); This code creates a new character array and copies the characters from the old array to the new one. So you end up with two character arrays and two pointers, each pointing at one of the character arrays. Both array ...
65,875,495
65,878,639
VSCode compiles slower C++ even though I'm using the same command line script
C++ code compiled from a command line shell script runs much faster than when I use the same shell script from a Task:Run in VSCode. I successfully tried an echo command in the script to make sure VSCode was running the same script I use at the command line. I know there are compiler settings in a .json file, but I don...
I found the answer. Turns out it's because VSC isn't Apple Silicon native yet and I'm on an M1 Mac. Anything I did from inside VSC, even the terminal window, forced the results to be x86_64 code, which runs 4x slower than the arm64 code I compile from outside VSC. Need to wait for the native version I guess.
65,875,596
65,877,995
undefined reference to `__printf_chk' when building from source with musl-g++
I'm attempting to compile a C++ library called VRPN with musl instead of glibc, and running into linker errors. Dockerfile # This build container compiles fully static binaries for alpine FROM ekidd/rust-musl-builder:1.49.0 AS build ENV CC=musl-gcc ENV CXX=musl-g++ ENV CFLAGS=-static ENV CXXFLAGS=-static USER root # I...
I managed to figure this one out. I think I was using host libraries rather than a proper musl toolchain. I got it to work by building in the messense/rust-musl-cross docker image (created with musl-cross-make), which contains the gcc toolchain compiled for the x86_64-unknown-linux-musl target. Here's my working docker...
65,875,684
65,875,897
Segmentation fault with vectors, but not sure what I did wrong
So when I run this code: #include <iostream> using namespace std; #include <vector> #include <string> int main() { int current_number = 0; vector<int>primes; for(int i = 0; i < 100; i++) { current_number++; for(int h= 0; h < primes.size(); h++) { if(current_number % primes[h] == 0...
Among the problems in the posted code. The inner loop body will never be entered because primes is initially empty the only code that changes it is in that loop. Even after fixing the initial primes content with {2} and starting the counter loop with 3, the logic in the inner loop is still wrong. It appends on ever n...
65,875,830
65,875,946
Struggling to understand C++ template instantiation
I am writing a template class, and then need to write test cases to test my code and verify all of the methods work properly. In my testing file, I attempt to create an instance of Collection, but get the following error: "no instance of constructor "Collection" matches the argument listC/C++(289)". I have a no-arg con...
The operator new returns a pointer. So this declaration Collection<int> testCollection = new Collection<int>(); (where you forgot to specify the template argument in the expression with the operator new) can be imagined the following way Collection<int> *p = new Collection<int>(); Collection<int> testCollection = p; ...
65,875,848
65,876,037
How would I go about running this loop until someone enters 0 in any position?
The instructions are to make sure that this loop runs indefinitely unless someone enters 0 in either the op, a, or b variables. How would I go about doing that? Because right now it can't go further than one equation inputted. Here's the code: #include <iostream> #include <string> #include <cmath> #include <math.h> #i...
Try this and let me know if it works for you. P.s I added for loop in main function and replace EXIT_SUCCESS; with exit(1). #include <iostream> #include <string> #include <cmath> #include <math.h> #include <stdlib.h> using namespace std; void calculate(float a, char op, float b);//used this function so it can be calle...
65,875,870
65,889,827
Why is my output for Balanced Bracket Problem using Recursion wrong
So I wrote some recursive code for printing balanced brackets when number of bracket pairs (noOfPairs) are given as the input. But my answers are wrong. For example: On inputting n = 2, the two types of brackets would be (()) or ()() but my program is outputting (()) and (()( which is wrong. Kindly help! // Generate Br...
After the first recursive call to generateBrackets, you need to pop the '(' that you had just pushed, because otherwise it will interfere with the next call where you add a close bracket.
65,876,055
65,876,160
Why is the ternary operator returning 0?
Why does the following code have '0' as output? #include <bits/stdc++.h> int main() { int max = 5; std::cout << (false) ? "impossible" : std::to_string(max); }
The statement std::cout << false ? "impossible" : std::to_string(max); is equivalent to (std::cout << false) ? "impossible" : std::to_string(max); because << has higher precedence than ?: and false is printed as 0. You probably expected this std::cout << (false ? "impossible" : std::to_string(max)); You should read ...
65,876,124
65,876,125
How do I use a cubemap array in OpenGL to render multiple point lights with shadowmaps?
I read and implemented the following tutorial: https://learnopengl.com/Advanced-Lighting/Shadows/Point-Shadows Now I want to generalize it to render multiple point lights in my scene, how would I go about it? I heard that cubemap arrays could be used for something like this, how do they work exactly? Could someone show...
If you want to pass multiple cubemap shadowmaps to a shader, and you dont know in advance how many exactly then cubemap arrays are a good solution. They work like a 3D texture, where each layer is a cubemap. In the fragment shader you can create a sampler for them like this: uniform samplerCubeArray cubeMapArray; You ...
65,876,360
65,876,458
C++: Template Specialization causes different result in Debug / Release
In the following code, I create a Builder template, and provide a default implementation to return nothing. I then specialize the template with int, to return a value 37. When I compile with -O0, the code prints 37, which is the expected result. But when I compile using -O3, the code prints 0. The platform is Ubuntu 20...
You should add a forward declaration for build<int>() to builder.h, like so: template<> int Builder::build<int>(); Otherwise, while compiling main.cc, the compiler sees only the generic template, and is allowed to inline an instance of the generic build() function. If you add the forward declaration, the compiler know...
65,877,299
65,880,752
-Wsign-conversion error when getting index for vector
#include <iostream> #include <vector> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); std::vector<std::string> possible_result{"Rock", "Paper", "Scissors"}; std::string selection{}; std::cout << "(R)ock, (P)aper, (S)cissors: "; while(std::cin >> selection){ if (selecti...
As mentioned in the comments, the operand of the [] operation for the std::vector container is a size_t type, which is always an unsigned type (but it's bit width may vary between platforms). Thus, your compiler generates a warning (which you have instructed it to convert to an error) when you give a signed integer as ...
65,877,310
65,877,342
Implementation of stack <array<string, 100>>
I have been learning C++ for a couple of weeks now and started making my game where I pumped into this problem with std::stack. I have a class that have a board and a stack #include <string> #include <stack> array<string, 100> board; stack<array<string, 100>> history; each time I create my board or make changes I pus...
history.pop(); This removes the element at the top of the stack. As in: it goes away. It ceases to be. It goes to meet its maker. It joins the choir invisible. It pines for the fjords. It is now an ex-element. Afterwards: arr = history.top(); This returns the current element on the top of the stack. This does not ret...
65,877,508
65,877,539
Why is declaring a std::ifstream called cin not a compilation error?
Recently, I was curious as to what would happen if I declared a std::ifstream called cin, then tried to read input with it. I thought that this would result in a compilation error, because the compiler wouldn't be able to differentiate whether to use the std::istream or the std::ifstream for the input operation. Here's...
The same identifier can be used for different variables: in different namespaces, and inside a code block, with the inner scope overruling the outer scope. In your code you do both of these things. The global object called std::cin and the local object of main function called cin can coexist with no problem. A name d...
65,877,677
65,877,856
C++: Infinite loops from input validation
So I have this method where I have to intake a single value (an integer with a value greater than 1), and loop back to the user initialization if the value given is seen to be outside of those above parameters. The issue I'm having is when a letter is input to the console the program either interprets the letter as 0 (...
What's happening in your code is that whenever you input a letter, cin keeps its invalid state for subsequent inputs, so you have to clear it and remove bad inputs first. So you can do something like this : if (!(cin >> n)) { cout << "THE NUMBER INPUT IS NOT RECOGNISED AS AN INTEGER, TRY AGAIN." << endl; cin.cl...
65,878,492
65,879,443
GCC with c++17 standard cannot compile range-based for case with different begin/end data type
For C++17, it has a small change with proposal p0184r0,which make it possible to specify different begin() and end() type for a user-defined type, to compatible with range-based for. But it seems gcc will failure on following cases: #include<iterator> #include<iostream> using namespace std; class read_t { public...
This is a compiler bug as far as I can tell. If you replace the range-for loop with its non-range equivalent, as per the standard, it compiles: { // init-statement auto &&range = read_t() ; // auto &&range = for-range-initializer ; auto begin = std::begin(range...
65,878,511
65,878,543
Can you perfectly forward without templates
I have a class that has multiple constructors: class Obj { public: Obj(int x, int y) {} Obj(std::string const& str) {} Obj(char v, int s) {} }; Now I want to add an Options object to the constructor that is stored in the object. But to make this work well I want to move t...
Forwarding references only work with templates, you could templatize the constructors and impose restriction on template parameter. class Obj { Options options; template<typename Opt> using ValidOption = std::enable_if_t<std::is_same_v<Options, std::decay_t<Opt>>, bool>; public: template <type...
65,878,923
65,879,213
OpenGL - Texture not rendering properly
I'm trying to render a cube with a wood texture (all faces of the cube with the same texture), but the texture is not being rendered as it should (looks like the texture is trasparent at some parts): But if look inside the cube, it seems to be rendering properly: : Here is the .obj file that I'm reading from (with the...
Thanks to @Sync it I find out that the solution was to enable depth testing. glEnable(GL_DEPTH_TEST);
65,879,324
65,879,421
Importing a file c++
I am trying to make a code that takes a number from a user, and makes that the size of an array. Then I fill the array with strings from a file. #include <iostream> #include <fstream> #include <string> #include <cstring> using namespace std; int main() { cout << "Please input a number: " << endl; in...
seems like your file does not exist, and you haven't done any error handling here ifstream luckyFile; luckyFile.open(lucky.c_str()); if (luckyFile.is_open()) { // your code here } else { // handle error cout << "Error: " << strerror(errno) << endl; }
65,879,919
65,880,865
Why do we need to define a static variable of a class, unlike the other member of a class?
Whenever we have a class with some static member variable, why do we need to define it? Why can't we use it directly? I wanted to see if any memory space would be allocated to the static variable if I don't define it, so I wrote this little code and it seems like memory is indeed allocated for the variable. #include <i...
For static data member you have to allocate memory for it in your implementation, what you are doing now does not allocate memory but you are just getting the size of the int. In C++ 17 you can declare static variable inline, for int its default value is zero but you can set any value you want. Like this: static inlin...
65,879,925
65,880,234
Error C2664: Cannot convert argument from initializer list to std:initializer list
I have a function read() that reads a file and store information into a map. However, whenever the function calls map.insert(), it gives me an error. Employee and Volunteer are two customs classes with only a few variables. For example, If I call ifstream fin; std::map<std::string, Employee*> employees; fin.open("Emplo...
Try following code: template <typename T, int T_LINE_SIZE> inline void read(std::ifstream& in, std::map<std::string, T*>& input) { std::string name = ""; std::string ID=""; std::string line; double salary; while (getline(in,line)) { if constexpr (std::is_same<T, Volunteer>::value) { ...
65,880,213
65,880,940
Problem with writing on serial port in QT
I want to write to a serial port . By using hercules, I have opened the port "COM6" and when I run the program, I can see the text "ok" in hercules window. But when I put the line "serial->write("ok");" inside a while loop, even my mainwindow isn't poped up. I would appreciate if someone could help me fix this prob...
Move your sending function to your on_pushButton_clicked slot to send your message when you click on your button. void Widget::on_pushButton_clicked() { qDebug() << "salam"; serial->write("ok"); } Also if you want to send something in a loop you can define a QTimer and send you message when QTimer triggered. Y...
65,880,956
65,881,045
use of std::less in std::map does not compile
I am unable to understand why does following function not compile #include <iostream> #include <map> int main(){ std::map<int, int, std::less<int>> myMap(std::less<int>()); myMap[2] = 2; std::cout << myMap[2] << std::endl; return 0; } The error message is as follows - std_less_check.cpp: In function ‘int main...
In the first program, you have a vexing parse. If the compiler can parse a declaration as either a variable or a function, it will choose to parse it as a function. myMap can be parsed as a function declaration. It returns a std::map<int, int, std::less<int>>. It takes an argument of type std::less<int>(), which is its...
65,881,377
65,881,440
Access derive class from a base class pointer
I want to access derive class from a base class pointer, but my code is not working and I am not getting what is wrong #include <iostream> using namespace std; class base { public: int n1; void display() { cout << "\nBase number is: " << n1 << endl; } }; class derive : public base { public: ...
You cannot access derived class' members using a base pointer, if you are sure that bptr is indeed pointing to a derive instance, you could cast it to a pointer to derive and use it auto dptr = static_cast<derive*>(bptr); dptr->n2 = 66; EDIT: There is a bigger problem in your code, display is not virtual in base class...
65,881,568
65,881,732
how it works QMessageBox
Please tell me where I made a mistake? My code: void deletetable::on_pb_dell_clicked() { QMessageBox messageBox(QMessageBox::Question, tr("Sure want to quit?"), tr("Sure to quit?"), QMessageBox::Yes | QMessageBox::No, this); messageBox.setButtonText(QMessageBox::Yes, tr("Yes")); messageBox.setBu...
messageBox.QMessageBox::Yes Is just accessing the enum Yes, which is going to evaluate the same each time. You want to capture the actual response from the question and query that, such as: auto response = QMessageBox::question(this, "Save", "Do you wish to save?", QMessageBox::Save | QMessageBox::Discard | QMessageBo...
65,882,077
65,882,336
How to debug DirectShow push source filter?
I tried one of sample DirectShow based virtual camera available at https://github.com/roman380/tmhare.mvps.org-vcam I am able to compile and build and its working fine in browsers(Chrome and Edge). But in case of Desktop app like Zoom and Team virtual camera is getting recognized but not showing any frames. On selectin...
Debugging PushSource/VCam based filter is Zoom is to happen along the same lines as debugging of a DLL project running in context of external application. Namely the procedure is this: Stop target application (Zoom) Build your project, register the DLL as/if needed with COM (regsvr32) Have the target application start...
65,882,464
65,885,277
How can I print the requests in boost.asio?
I'm using boost.asio to write a simple server. The code below is trying to do 2 things: print the request respond to the client hello but it does not. #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(){ try{ boost::asio::io_context ioc; ...
First thing I notice: std::string buff; socket.read_some(boost::asio::buffer(buff), err); This reads into an empty string: 0 bytes. Either reserve space: buff.resize(1024); socket.read_some(boost::asio::buffer(buff), err); or use a dynamic buffer with a composed read operation (see next) read_some reads whatever is...
65,882,667
65,883,584
C++ Is conversion from int to long a promotion?
After numerous research on the web, I couldn't figure out if a conversion from int to long is considered as a promotion or not. If found the following code on the Microsoft's website here : long long_num1, long_num2; int int_num; // int_num promoted to type long prior to assignment. long_num1 = int_num; However it...
long long_num1, long_num2; int int_num; // int_num promoted to type long prior to assignment. long_num1 = int_num; The text is incorrect. int_num is not promoted, because it's already an int, so no point applies here. On assignment, a implicit conversion happens - from source type to destination type. Because lo...
65,882,929
65,882,930
Compiler variance for trailing requires-clauses on non-templated functions
Consider the following example: void f() requires true { } int main() { f(); } Clang(1) (DEMO) accepts this program, whereas GCC(1) (DEMO) rejects it with the following error: error: constraints on a non-templated function Note that the constraint expression can actually be used in Clang's case, as the following pr...
All standard references below refer, unless noted otherwise, to N4861 (March 2020 post-Prague working draft/C++20 DIS). This is a Clang bug, and GCC is correct to reject the program, as per [dcl.decl]/4 (as well as [temp.constr.decl]/1) [emphasis mine]: The optional requires-clause in an init-declarator or member-dec...
65,883,011
65,883,254
Explicit type conversion really necessary?
Arduino's LiquidCrystal Library defines virtual size_t write(uint8_t); In their example you'll find a few calls to that function: lcd.write(byte(0)); // when calling lcd.write() '0' must be cast as a byte lcd.write((byte)1); lcd.write(4); My C++ is a bit rusty, so I'm not sure why they say it must be cast as a byte?...
I suspect that's due to these 2 overloads in the base class Print: virtual size_t write(uint8_t); size_t write(const char *str); If called as write(0), the write(const char *) overload will be selected as a better candidate (the first requires a narrowing conversion, but 0 is a null-pointer). So to send a 0 byte, you ...
65,883,106
65,883,182
emplace_back in a list from a unique_ptr
This does not compile std::list<int> l; std::unique_ptr<int> p = std::make_unique<int>(); l.emplace_back(std::move(p)); The internal storage of lists are _List_node, which are simply back and forth pointers to the underlying data, here int. So a list could steal the internal pointer of a unique_ptr and emplace i...
So a list could steal the internal pointer of a unique_ptr No, it couldn't. A list allocates nodes where the element is stored. An object of element type won't be of use to it. Only thing std::list can steal elements from is another std::list of same type. In order to avoid the move, either create the object as an el...
65,883,476
65,885,557
How to configure systemd *.service using XML file configuration
I'm making a cross-platform background process. For Windows, I have a XML configuration file, which has a service name, load type etc. On windows, program during execution just parses this file and creates the service, easy. Linux, on other hand, has this *.service config file, which doesn't allow me to use my XML conf...
I suspect you use the well-known technique of registering your Windows Service executable as a service, when you run it as a regular process. That is simply a matter of calling the right Service Control Manager API's. You know you're not a service if StartServiceCtrlDispatcher fails. The same idea works for Linux. If y...
65,884,482
65,885,187
C++ files stopped compiling - keep getting error: linker command failed with exit code 1 (use -v to see invocation)
I've had no problems compiling in the past, and code that I wrote previously is compiling fine, but it is now giving this error when I try to compile a very simple C++ file using Visual Studio Code on my M1 Mac: Code: #include<iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0;...
This was occurring as I hadn't saved the file prior to compiling and therefore the compiler couldn't find it.
65,884,733
65,889,382
What is wrong with this merge sort algorithm?
Can someone please tell what is wrong with this piece of code? This code is to sort a set of elements in an array using merge sort. #include<iostream> void merge(int arr[], int left, int mid, int right){ int left_ptr = left; int right_ptr = mid + 1; int size = right - left + 1; int temp[size]; ...
Here is a list of things wrong with your code. I'm taking "wrong" broadly here. For each bit of code, my primary criticism is style based not "correctness", where the style aimed for is one that makes correctness easier to spot. Along the way, one of the style criticisms results in spotting what looks like a bug. voi...
65,884,758
65,884,801
String function won't return string
I cant seem to return str in my RemSpacePunct function. I wanted to make a function that removes spaces in a string but when I run the code, it won't remove the space. string RemSpacePunct(string str); string sort(string str); int main(){ string s = "partial men"; sort(s.begin(), s.end()); RemSp...
You're ignoring the return value. str is copied when it's passed to the function, so any modifications you perform on the argument aren't reflected back to the original value. Instead, you should return a modified value - which you do, but you then ignore it instead of using it: string result = RemSpacePunct(s); cou...
65,884,975
65,885,122
How to take arbitrary number of number input using cin in c++
I want to take input from the user until he presses enter key. I have used the following approach, but in vain, as the loop won't terminate. Please help. #include<bits/stdc++.h> using namespace std; int main() { int n; vector<int> array; cout<<"Please enter the elements of the array"<<endl; while(cin>>...
The while loop will go on until cin >> n fails. It doesn't fail when you press enter. Enter is treated like any other whitespace character and will be skipped by default when doing formatted reading using operator>>. You could read complete lines and extract data from those instead. If the user enters a blank line, you...
65,885,138
65,885,709
(OMNeT++) Where do packets go?
I'm trying to do a project described also here: PacketQueue is 0 I've modified the UdpBasicApp.cc to suit my needs, and in the handleMessage() function I added a piece of code to retrieve the length of the ethernet queue of a router. However the value returned is always 0. My .ned file regarding the queue of routers is...
You are not creating that queue. It was already instantiated by the OMNeT++ kernel. You are just getting a reference to an already existing module with the getModuleByPath() call. The router3.eth[*].mac.queue. module path is rather suspicious in that call. It is hard-coded in all of your application to get the queue le...
65,885,145
65,885,707
std::regex_error at memory location
I have a regex as: std::regex regexp( R"(\$\ part,\ model.*[\n\r]([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*),([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*))",std::regex::extended); The code compiles, but I receive the following error: Unhandled exception at 0x748F49C2 in regex.exe: Microsoft C++ exception: std::regex_error a...
According to the regex spec, the effect of escaping a space (which is not a special character) is undefined: 9.4.2 ERE Ordinary Characters ... The interpretation of an ordinary character preceded by an unescaped <backslash> ( \ ) is undefined, except in the context of a bracket expression ... Apparently in the MSVC i...
65,885,236
65,885,323
Function that returns just the constructor
#include <iostream> struct something{ int i; something(int i) : i(i) {} }; class otherthing { otherthing(){} static something foo(int value) { return { value }; } }; In this example what the foo function returns? Am I understand correctly that it creates an object on the heap and ...
In this example what the foo function returns? Object of type something, initialized with value value. Am I understand correctly that it creates an object on the heap and returns a pointer? No. It creates an object with automatic lifetime (typically associated with stack memory). It returns that object and no point...
65,885,550
65,916,292
cstdlib not able to resolve using ::wcstombs
I upgraded my system to fedora 33 after which I observed that stdlib.h was not able to resolve some data structures: In file included from /usr/include/c++/10/cstdlib:75, from /usr/include/c++/10/ext/string_conversions.h:41, from /usr/include/c++/10/bits/basic_string.h:6545, ...
turns out there is recent patch added to cstdlib: https://www.cygwin.com/bugzilla/attachment.cgi?id=12133 that might have been uncaught, I did not investigate the related files right now, but the adding the minimal changes patchset if someone else bumps to this issue... diff --git a/stdlib.h b/stdlib.h index f255e4a..d...
65,885,754
65,886,603
Reading json text file fails parsing. Is ostringstream doing something to it?
I read a text file (.json) that contains this: { "a" : true } I read the file using: std::ifstream fileStream; fileStream.open(configFilePath,std::ios::in); std::ostringstream sstr; sstr << fileStream.rdbuf(); std::string text = sstr.str(); fileStream.close(); If I print the contents, I get the correct text in the ou...
I found the error thanks to the comments of the users. The file was saved in an Utf-8 encoding with BOM, adding symbols not printed in console, magic numbers that tell the editor that the document is encoded as utf-8. To print hidden symbols in Linux: cat filename.json -A You can save the file without BOM or change th...
65,885,762
65,885,920
operator const char* () and explicit copy ctor
so i ran along this question in a past test from my uni, and i noticed something strange that i couldn't find an explanation to. the question is: what would the line cout << s2; in main would print? I followed to flow execution in the VS2019 debugger and when the line MyString s2 = s1; was performed it called operator ...
The compiler tries hard to find a way to compile the program. Since it can't make an implicit copy (explicit copy ctor), it tries other constructors, and the const char* one seems to be a viable candidate after an implicit user-defined conversion to const char*. There are no other candidates, so it is selected. Useful ...
65,885,992
65,886,157
How to convert an 8-byte integer to a 4-byte integer
I'm trying to convert an 8 byte integer to a 4 byte integer so that I can draw a cube on the screen. The warning it gives me is: Warning C26451 Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to av...
What your referring to by bit is actually a byte. The reason is that when programming in C++, the smallest size of memory you work with is a byte (it may vary). So its not 4 bit or 8 bit, its actually 4 bytes and 8 bytes. unsigned int* can be represented as a 8 byte integer in a x64 application. In these type of applic...
65,886,048
65,886,193
Some questions about Class
first of all, I have to say this community suggested Primer C++ to me, and so far, it was an amazing experience, and I've learned tons of things, but the class chapter starts a little bit weird. The code is about two functions called read and print. I have a problem understanding this code. It will be a huge help if yo...
I'll try to answer your questions: Why write istream/ostream because is the type in both cases: return and parameter. Maybe you need to know that C++ a strongly typed language. Same reason than first point, this isn't a new object, it's the parameter type. In this line you custom the input stream and the ouput stream ...
65,886,215
65,886,710
C++ zero initialization without constructor
I don't understand what happens regarding the zero initialization of structs that has default values for its members. If I have these structs: struct A { int *a; int b; }; struct B { int *a; int b; B() : b(3) {} }; struct C { int *a; int b = 3; }; What we can say without a doubt is: A a; leaves all fi...
As of C++14, C is an aggregate (like A), and C c{} syntax performs aggregate initialization. This includes, in part: [dcl.init.aggr]/8 If there are fewer initializer-clauses in the list than there are elements in a non-union aggregate, then each element not explicitly initialized is initialized as follows: (8.1) — If ...
65,886,397
65,886,636
C++ Function with variable number and types of arguments as argument of another function
I would like to create function calling another function and printing its arguments. It should be compatible with many functions (returning the same result) with many combinations of variables of arguments. I would like to have something like this: int fun1(){} int fun2(int i){} int fun3(std::string s, int i){} void e...
It is not foolproof, but any possible errors will be caught at compile time (ie. the code will not compile). It should work file, as long as the provided parameters match those of the called function, and a matching << operator exists for each parameter. template<class Fn, class...Args> void execute_and_print(Fn fn, Ar...
65,886,468
65,886,579
C++ virtual inheritance and access to a public virtual method whose implementation is in a class whose inheritance is protected
I am using a virtual inheritance to create a class EditablePrimeNumberSet (a set of prime numbers) that inherits the class EditableNumberSet (a set of integers that can be incremented) while only exposing the base class NumberSet (a set of number). (I don't want my class to expose the method add that will lead to a set...
If you want to expose a single name from the protected class, you can use a using declaration: class EditablePrimeNumberSet : public virtual NumberSet, protected EditableNumberSet { public: using EditableNumberSet::contains44; // Expose EditableNumberSet::contains44 as // p...
65,886,495
65,886,547
how to link .so files with CMake
I want to rebuild a simple application based on a .cpp, a .h and multiple .so files. From what i've seen, my CMakeLists.txt should be like this : cmake_minimum_required(VERSION 3.5) set(CMAKE_CXX_STANDARD 11) project(test C CXX) add_executable(${PROJECT_NAME} main.cpp) target_include_directories(${PROJECT_N...
The error message means that you have to add pthread to the list of linked libraries. In target_link_libraries you only list the library names without path, lib prefix and file extension: cmake_minimum_required(VERSION 3.5) set(CMAKE_CXX_STANDARD 11) project(test C CXX) find_package(Threads REQUIRED) add_ex...
65,887,326
65,902,577
Formatting type by fallback to pointer with fmt library
I am try using fmt::format("Expected : '{}' vs. '{}'", getDataOrPointer(rA), getDataOrPointer(rB)); where getDataOrPointer should return a void pointer (which can always be formatted) or the default value when a formatter exists: //! Return the type if a `fmt::formatter` exists. template<typename T, typename ...
You can use fmt::has_formatter, quoting https://github.com/fmtlib/fmt/issues/1369: has_formatter<T, Context> tells you that type T has a formatter specialization for Context (context basically specifies character and output iterator types) and it can be used with SFINAE. Example: https://godbolt.org/z/pCD14x. The main...
65,887,570
65,887,715
Time limit Exceeded in if-else
Following is a function which change the value of array according to conditions: If the difference between the array element and the next multiple of 5 is less than 3, round up to the next multiple of 5. If the value of array element is less than 38, no rounding occurs. Code: vector<int> gradingStudents(vector<int> g...
Time Limit Exceeded happens most often when the input size if very large, and/ or your logic takes a long time to process. One place I see in your code is, if there was a place where no if statements were satisfied, it will never be because i wont be incremented. Basically your loop will run forever. You can either inc...
65,887,575
65,887,621
How does std::stack enforce that the container class meets certain requirements
If you create a stack with a container that doesn't meet the requirements of the required underlying container, you get a compile error. How is this an error that can be determined at compile-time vs. run-time. For example: #include <iostream> #include <stack> using namespace std; class Test { int data; }; int m...
std::stack isn't actually doing anything. Inside std::stack, there is a like like using value_type = Container::value_type; and for your case, Container is Test and since Test::value_type does not exist, you get a compiler error.
65,887,747
65,887,971
The minimum number of applications of the process?
The apples from Dorel's orchard had an excellent year. He wants to harvest all the fruits but feeling overwhelmed, he resorts to a strategy like this: he chooses as large a sequence of trees as possible from which he harvests the same amount of apples. The procedure is applied until all the apples are harvested. Calcul...
I do not understand the logic of your code. There might be more issues, but this cannot be correct: int i, min; for (i = 0; i < n; i++) if (v[i] != 0) min = v[i]; for (;i < n; i++) if (min > v[i] && v[i] != 0) min = v[i]; The first loop stops when i<n is false, but if i<n is false then the sec...
65,887,794
65,887,865
Does gsl::not_null hurt performance?
C++ Core Guidelines recommends a gsl::not_null type. As stated in I.12: Declare a pointer that must not be null as not_null: To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr. ... By stating the intent in source, implementers and tools can provide better diagno...
But, it also adds an overhead because methods operator->() and operator*() Except, those functions are defined inline and are extremely small, thereby optimiser will (very likely) expand them inline, which would remove that potential overhead entirely. how did the doc conclude the net performance gain is positive? ...
65,888,032
65,888,393
Draw lines using mouse clicks OPENGL
I am trying to draw lines in opengl using mouse clicks, but everytime I click a line between coordinates (0, 0) (corner left) and the actual mouse click is drawn. I want to have only the lines drawn in between clicks. Here is the mouse function: int i = 0, x[50], y[50]; void mouse(int button, int state, int mousex, in...
Change this for (int k = 0; k <= i; k++) // CAREFUL -- there are i points { glBegin(GL_LINES); glVertex2f(x[k], y[k]); glVertex2f(x[k + 1], y[k + 1]); // CAREFUL k+1 = i+1 in last iteration glEnd(); } to this glBegin(GL_LINE_STRIP); for (int k = 0; k < i; k++) { ...
65,888,525
65,900,286
How to exploit polymorphism on embedded systems?
I have been developing a C++ software driver for the adc peripheral of the MCU. The individual analog inputs connected to the adc can be configured for operation in the unipolar or bipolar mode. To reflect this fact in my design I have decided to model the analog inputs by the AnalogInput abstract class and then define...
The "auxiliary array" as you call it is mostly needed for memory management, i.e. you need to choose the memory to store your objects in. It's also an interface - the array is how you access the ADCs. You can store your objects either in the heap or the (global) data segment - an array of objects implements the latter ...
65,888,788
65,893,998
C++: static assert that functor's argument is const reference
I'm writing a template function in C++17 which accepts a functor F as argument and I want to restrict the passed in functor to have only one constant reference argument, where T can be any type. for example: template <class T> struct my_struct{ std::vector<T> collection; template <class F> std::vector<T> func(F...
I finally managed to achieve it in the following way: template <class T> struct my_struct{ std::vector<T> collection; struct noncopyable_value_type : T{ noncopyable_value_type(const noncopyable_value_type&) = delete; noncopyable_value_type& operator=(const noncopyable_value_type&) = delete; ...
65,888,852
65,888,998
Converting an inline-asm x87 fsqrt function from C++ to C for x86-64
I was looking at different methods to compute the square root, and one in particular (sqrt14 from here) caught my attention, unfortunately it was written in C++ (it only uses assembly), it's difficult for me to translate it back to C - if that's possible. double inline __declspec (naked) __fastcall sqrt14(double n) { ...
The example you cite is very specific to one compiler... __declspec (naked) is an implementation specific feature (non-Standard) __fastcall is an implementation specific feature (non-Standard) Even in your revised example: __attribute__((fastcall, naked)) is an implementation specific feature (non-Standard) Even th...
65,888,872
65,906,344
Can an injected class name be used as a type name in a friend declaration?
Consider this code: template <typename T> class Singleton { }; class Logger : public Singleton<Logger> { friend class Singleton; }; It compiles in gcc and clang, but is it valid? [temp.local].1 says: When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as th...
When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it is a template-name that refers to the class template itself. The condition in bold does not apply to the examp...
65,889,148
65,889,419
How to access variable of an object from within an other object stored in void pointer
I have to make a dynamic array in a class and store another class' object in that array. Then use the array to access the other classes. there are a total of 3 classes to be stored in that same array. But when I try to access the var, it wont allow me to... (obj.arr[0].a;) This one. I tried many ways but cant find any ...
It does not want to let you, because a void* has no member named a. You have to let the compiler know that you want to pretend the void* is actually a T1*. That being said, this is a terrible practice. One of the advantages of c++ over c is that it provides a way of avoiding the need to force-polymorphism like this. A ...
65,889,473
65,889,610
How to deal: zeros disappear
I have a program and one of its tasks is to save data to DB (i'm using SQLite). Here is my writing to DB code: qry.prepare("INSERT INTO " + DB_TABLE_OMEGA + "(KART, |. . . other stuff|) " "VALUES(:KART, |. . . other stuff|)"); qry.bindValue(":KART", KART); ...
There is no STRING data type in SQLite as it is explained in Datatypes In SQLite Version 3. If you define the data type of a column as STRING, the column's affinity will be determined as NUMERIC and as such any numeric value with leading 0s or trailing 0s after the decimal point will be stored without them. Redefine th...
65,889,668
65,890,285
Intel compiler inline size
I have been compiling my code for some time with g++ and then moved to Intel's icpc compiler. With icpc I kept getting the following warnings: remark #11074: Inlining inhibited by limit max-size remark #11074: Inlining inhibited by limit max-total-size I never had this problem with g++. After some research, I unders...
My question is whether it is always a good practice to remove sizes on inlining and inline as much as possible? No, it is not always a good pratice to remove size limits on inlining nor to inline as much as possible. Ideally, inlining should be done only when it improves performance. Are there situations at all wher...
65,889,745
65,890,580
How to turn a string containing tile numbers into a map or vector that contains coordinates of the tilenumber?
I am using tinyxml2 (https://leethomason.github.io/tinyxml2/index.html) to parse a .tmx/.xml file to C++. There is an ChildElement named data, it has text content. <data encoding="csv"> 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3, 3,3,0,2,0...
I think you've confused the purpose of std::map, a more efficient implementation might use something like std::vector instead. Maps can be helpful when mapping pairs with non-integer keys, but for an application like this they're overkill. #include <string> #include <vector> std::vector<std::vector<unsigned int>> pars...
65,889,768
65,890,377
C++ store pointer of element of container
In my application, I have a std::list<TreeNode> that is the owner of my tree nodes. Now I want to be able to access the left and right neighbor inside a TreeNode, so which smart pointer should I use to store the neighbors inside a TreeNode? The only pointer suitable for this is a raw pointer because a TreeNode is not ...
so which (smart) pointer should I use to store the neighbors inside a TreeNode? You should use a suitable pointer type. The only pointer suitable for this is a raw pointer Well, there you go. If the raw pointer is the only suitable one, then using an unsuitable smart pointer would be counter-productive. If you hav...
65,889,841
65,890,490
Why VS doesn't see included files?
I am a student writing a project. I have created a program (here's the link to SVN: https://mysvn.ru/Ilya_Antonov/antonov_sem_prj). I use CMake to build it and generate the .sln project. But when run it in Visual Studio, there are some errors: the compiler can't open the files "drumswindow.h" and "mainwindow.h" (fatal ...
You don't include the current source dir and therefore the compiler doesn't find it. Either add the current source dir or use the correct include statements (#include "keyswindow.h" for example)
65,889,893
65,890,551
Multithreading nested foor loop with std::thread
I am quite new to c++ and I would really need some advice on multithreading using std::thread. i have the following piece of code, which basically separates a for loop of N = 8^L iterations (up to 8^14) using thread: void Lanczos::Hamil_vector_multiply(vec& initial_vec, vec& result_vec) { result_vec.zeros(); st...
Is it better to create threads in the function which calls Hamil_vector_multiply and then pass a vector of threads to Hamil_vector_multiply in order to avoid creating each time new threads? If your worried about performance, yes it would help. What your doing right now is essentially allocating a new heap block in ev...
65,890,083
65,890,242
C++ template: cannot combine with previous 'type-name' declaration specifier
I'm writing a utility function to look for elements in containers like so: #include <algorithm> #include <type_traits> // Helper to determine whether there's a const_iterator for T. template <typename T> struct hasConstIt { private: template<typename C> static char test(typename C::const_iterator*); template<t...
template <typename Container> typename std::enable_if<hasConstIt<Container>::value, void>::type struct In { is wrong. This is done as either template <class Container, typename = std::enable_if_t<hasConstIt<Container>::value>> struct In { in old-fashioned C++11. Note the second argument: it has default value and is n...
65,890,172
65,890,246
How to get return type of template parameter method?
I am trying to make a template class that expects a lambda as input, stores it, and also stores in a vector some elements of type = return type of the lambda. But I don't know how to get that type, even though when an instance is built the lambda is known with also its return type. I'd like the class to be constructed...
decltype needs an actual call expression to get the return type, which you can't really reliably get from the type F (because the type F might not be default-constructible for example). You must use std::declval to "create" an instance of F that you can then call. Perhaps something like using value_t = decltype(declval...
65,890,360
65,890,507
Ambiguous function call in C++
The following code gives the compilation error of main.cpp: In function ‘int main()’: main.cpp:18:19: error: call of overloaded ‘print(int, int)’ is ambiguous print(0, 0); #include <iostream> using namespace std; void print(int, double); void print(double, int); int main() { print(0, 0); return 0; } While t...
Sloppy speaking, overload resolution picks the overload that is a better match considering the types of the parameters. print(0) calls void print(int){} because 0 is an integer literal of type int. When you call print(0, 0) then either the first 0 could be converted to double to call void print(double, int) or the seco...
65,890,538
65,890,590
Size of array exceeds maximum object size in CPP
Recently, i'd faced this error while solving a variation problem of knapsack. Can anyone please suggest some way to get rid of it. const int n=105, w= 1000000005; int val[n], ans[n][w]; int weight[n]; Error: size '4000000020' of array 'ans' exceeds maximum object size '2147483647'.
What your doing there is creating Tera Bytes worth of memory allocations. Usually you do those type of allocations in the heap (using vectors like std::vector<int> val(n); and std::vector<std::vector<int>> ans(n, std::vector<int>(w));). But still, are you sure you need that much of memory? After all your talking about ...
65,891,004
65,891,071
Is it possible to check if a type has been instantiated with a specific template parameter?
Not quite sure if my terminology is 100% correct, so here's the code: template<class... Ts> struct Empty { }; int main() { using T = Empty<int, double>; // How to check if T "contains" double? return 0; } So this is specifically for types that accept multiple template types. Also this would ideally be at co...
Not sure to understand what do you exactly want... but I suppose is something as template <class check, template<class...> class TypeToCheck, class... T> constexpr bool does_obj_contain_type(TypeToCheck<T...>) { return (std::is_same_v<check, T> || ...); } // ... using T = Empty<int, double>; auto x = does_obj_con...
65,891,041
65,891,192
GLSL shader compilation debugger results in a flood of the character \x00 on the console
I am trying to debug my OpenGL shaders compilation but i'm having some strange output related to null characters I believe, my debugger console is flooded with a lot of \x00 characters and I am trying to understand where does it come from and how to get rid of it. This is my function: void DebugShader(GLuint shader) { ...
You're using maxLength uninitialized to set the size of the vector errorLog. You need to resize errorLog after initializing maxLength. The code should be more along the lines of (untested)... void DebugShader(GLuint shader) { GLint isComp = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &isComp); if(isComp!=G...
65,891,082
65,891,165
How to remake one array into two smaller via C++?
I need to make from one 10-element array two 5-element arrays. I made code like this #include <iostream> using namespace std; int main() { const int size1 = 10, size2 = 5; int array[size1]{ 1,3,6,2,82,10,6,34,2,5 }, arb[size2]{}, arc[size2]{}; for (size_t i = 0; i < 5; i++) { arb[i] = array[i...
These nested loops for (size_t i = 5; i < 9; i++) { for (size_t e = 0; e < 4; e++) { arc[e] = array[i]; } } do not make a sense. Moreover there are used unknow magic number 9 and 4. In fact all elements of the array arc except the last element are set to the value of the element array[8] ...
65,891,444
65,891,568
How to access a private variable that is a 2D array with getter function
Im making a chess game and I have a board class that looks something like this: class Board { private: Tile tiles[8][8]; public: Tile getTiles() { return **tiles; } } where Tile is another class with its member that I want to access. The problem is that I cant really do something like: void foo() {...
So, a Board is a collection of tiles. From a high level perspective, that's all it does. That it's stored as a 1D array, a 2D array, an hash map or a self balancing binary tree does not matter for the user. All that matters is that there are tiles in it. So, you should instead do it that way: Tile getTile(int row, int ...
65,891,522
65,892,777
Passing variadic template function arguments to another function
Straight up, there was a similar question, but different at its core. So, here is what I'm trying to do - lets say I have a variadic template function which takes T ...args and a function type FuncT funcName, so here is what we have so far: template<typename FuncT, typename ...T> void myFunction(FuncT (*funcName), T .....
I suggest that you use perfect forwarding: #include <iostream> template<typename FuncType, typename... Args> void myFunction(FuncType funcName, Args&&... args){ funcName(std::forward<Args>(args)...); } void function1(int a){ std::cout << a; } void function2(int a, int b){ std::cout << a << " " << b; } int mai...
65,891,873
65,896,827
Why is fetestexcept in C++ compiled to a function call rather than inlined
I am evaluating the usage (clearing and querying) of Floating-Point Exceptions in performance-critical/"hot" code. Looking at the binary produced I noticed that neither GCC nor Clang expand the call to an inline sequence of instructions that I would expect; instead they seem to generate a call to the runtime library. ...
It's required to support long double arithmetic. fetestexcept needs to merge the SSE and FPU states because long double operations only update the FPU state, but not the MXSCR register. Therefore, the benefit from inlining is somewhat reduced.
65,893,131
65,893,282
How to "ignore" template parameters for hashmap?
Coming from a non statically typed language I sometimes struggle with type constrains. I am looking for a way to store all my objects in a hashmap. The problem is, that the parent class uses templates as some children classes return different size and type of arrays. template<typename T, std::size_t Size> class Module ...
You could add a base class and store pointers to that in your map: class ModuleBase { public: virtual ~ModuleBase() = default; }; template<typename T, std::size_t Size> class Module : public ModuleBase { public: virtual std::array<T, Size> getValues() = 0; }; #include <memory> // ... std::unordered_map<s...
65,893,314
65,894,061
wxTimer not calling callback after binding with Bind()
I'd like to use wxTimer in my application, but I don't want to use the preprocessor macros to bind the events. Instead I want to use Bind() during the CTOR call to bind the events to my ui elements. After binding my timer, it doesn't start or it doesn't call the event handler. According to this it ought to work like I ...
You should change timer->Bind(... to just Bind(... The line timer = new wxTimer(this, wxID_ANY); sets the main frame to be the owner of the timer, so that is the item notified when the timer is fired. However the line timer->Bind(... sets up the timer to process the timer events. But the events aren't sent to the ti...
65,893,542
65,894,450
Why does DirectXToolkit ruin my depth testing
I'm sure I'm just missing some simple step that I've been too blind to notice so far, but I cannot seem to get depth testing to work at all. This is with DirectX 11. The code that should set it all up: DXGI_SWAP_CHAIN_DESC swapDesc = { }; swapDesc.BufferDesc.Width = 0; swapDesc.BufferDesc.Height = 0; sw...
DirectX Tool Kit does not 'capture/restore' state like the legacy D3DX9/D3DX10 sprite did. This was inefficient and relied on some hacky back-door functionality to capture the 'state block' for Direct3D 10+. In most cases, you are already going to set the bulk of the commonly used state to set up for the next draw call...
65,893,596
65,893,925
Erasing from vector by swapping to the end
I am wondering why there is no STL function that deletes an element from a vector by swapping it to the end and then removing it. Is there a better data structure than std::vector if you don't care about the actual order of elements and still want very fast traversal? Note that using std::remove and std::erase is not t...
You can use std::partition instead of std::remove/std::remove_if: Keep only values greater than 3: std::vector foo{1,2,3,4,5,6,7,8}; foo.erase(std::partition(foo.begin(), foo.end(), [](auto& v) { return v > 3; } ), foo.end()); Or you ...
65,893,646
65,944,267
Wrapping a function with two bi-directional parameters using SWIG to use in java [foo(char ** strs, unsigned int& size)]
I'm using SWIG 4.0.2 to wrap a C++ library to use from Java code. One of the classes has a tricky function that I'm having difficulties to wrap: class Bar { ... public: Status foo(char **strs, unsigned int& size); ... } The way "foo" is intended to be used is to allocate an array of strings and call the functi...
I've finally found the solution to this. The full solution is actually a mix of code taken from SWIG's own various.i file with a little tweak to handle the "char **strs" parameter and applying an existing typemap for the other parameter. Here is the relevant code from the .i file: %typemap(jni) char **STRING_IN_OUT "jo...
65,893,851
65,893,965
Why does this code that reads from cin recurse infinitely if the user types an invalid value?
I am learning C++, and I wrote this code: #include <iostream> namespace input { template <typename T> T prompt_user(std::string prompt) { T input; std::cout << prompt << ": "; std::cin >> input; if (std::cin.fail()) { std::cin.clear(); prompt_user<T>(prompt); } return inpu...
I had to add std::cin.ignore(std::numeric_limits<std::streamsize>, '\n') below std::cin.clear(). I am so sorry for my mess up.
65,894,160
65,894,193
Add random integer to total?
I am working on a blackjack-like program. I initially generate a random pair of cards and store the total of the numbers. If the user wishes to, another card must be generated, and the new total needs to be updated. Here is the program so far: /* Cortez Phenix The 25th of January, 2021 CS10B, Mr. Harden Assignment 2.1 ...
you need to add brackets for the addition and assignment operator as following. (also I think you mean += instead of =+ but I didn't change it in the code.) #include <iostream> #include <ctime> #include <iomanip> #include <string> using namespace std; int main() { srand(static_cast<unsigned>(time(nullptr))); ...
65,894,285
65,894,516
Time complexity of nested loops with if statement
I am taking a class on advanced C++ but I am getting stumped trying to find the Big-Θ of nested for-loops that are locked behind if-statements. Unfortunately my professor (for some strange reason) just expects us to know this from a pre-req class (even though I took it at a different college with different course conte...
The first question you need to ask is, what are you counting? Usually you can find some decent thing to count, instead of just "instructions", to get a good guess. Once you have your big-O value, you can double check the value is right. int count = 20; for (int i = 0; i < n; i ++) { Ok, this obviously runs O(n) time...
65,894,320
65,894,357
Could someone explain to me what uint64_t is doing exactly?
I am trying to undertand how this code works, specifically the line msk = ~(uint64_t) 0 << (uint64_t)(high - low + 1); I really only am curious what uint64_t is calling/doing. Not so much the bit operations Thanks for any insight! uint64_t clearBits(unsigned low, unsigned high, uint64_t source){ uint64_t msk; a...
uint64_t is an integer type. uint64_t msk; declares a variable of that type and (uint64_t) 0 casts 0 to that type since the literal 0 is an int. Similarly, (uint64_t)(high - low + 1) casts the result of a calculation to the type uint64_t. However, this second cast is unnecessary, as discussed in the comments since the ...
65,894,358
65,894,725
How to concisely express the C++20 concept of range containing T-typed values?
I want to write a function template that accepts ranges of MyType-typed values, so I wrote void f(const std::ranges::range auto& my_range) { /* ... */ } Unfortunately this does not constrain the type of the values contained in the range. I could use a requires clause before the function body block but I want something...
The problem here is: what is the actual constraint that you want? Do you want to: constrain on the range's value type being specifically T? constrain on the range's value type being convertible to T? constrain on the range's value type satisfying some other concept, C? any of the above but instead about the range's re...
65,894,506
66,055,304
Emscripten compile C++ on macOS: error "No thread API"
I'm trying to compile a relatively simple C++ program using emscripten for use in javascript (wasm). When I compile with the following settings emcc ./lttb.cpp \ --bind \ --target=wasm32-unknown-unknown-wasm \ --optimize=3 \ -v \ -nostdlib \ -Wl,--export-all \ -Wl,--no-entry \ -Wl,--allow-undefined \ ...
Fixed it by changing build args to following rm lttb.wasm emcc ./lttb.cpp \ --bind \ --optimize=3 \ -Wl,--export-all \ -Wl,--allow-undefined \ -s ALLOW_MEMORY_GROWTH=1 \ --no-entry \ -o lttb.wasm I believe it was the -nostdlib that was causing this particular issue (note: original build args were for a ...
65,894,608
65,894,812
How does the virtual keyword affect memory locations?
I had a job interview earlier and was asked what the output of the following code is: struct A { int data[2]; A(int x, int y) { data[0] = x; data[1] = y; } virtual void f() {} }; int main(){ A a(22, 33); int* data = (int*)&a; cout << data[2] << endl; } I talked through it but couldn't figure ...
Adding 1 or more virtual methods to a class causes (in this case 1) an object instance of that class to contain a hidden pointer to a compiler-managed "virtual method table" (vtable) at the front of the object's memory, eg: int *data = &a; A a; data -> -------------------- | vtable | -> [0]:...
65,894,655
65,895,087
regex_match cases that do & don't access deleted function
I'm trying to understand why one line of my code compiles one way and another line compiles another way. I can't pass the direntry.path().wstring() to regex_match directly without getting an "attempting to reference a deleted function" build error. const std::wstring directoryPath; // function parameter for (auto& dire...
Look at #7 in the list on that cppreference page. The call that takes an rvalue basic_string is marked as deleted. In your first call, you are passing a temporary string. (rvalue) In your second call, you are passing an lvalue. [Later] The reason that that call is deleted is to prevent a programming error. Consider the...
65,894,880
65,894,942
Undeclared issue, not sure how to fix
This program is meant to store a list of usernames, add usernames, and delete them as well. My code works as intended except for the first step. Whenever i enter a name to be stored nothing shows up on the list, and because of this nothing can be deleted. Im not sure where i messed up because i went over it and everyth...
You have 2 separate vector objects - addUser and userBase. You are adding all of your usernames to addUser only, but you are printing and deleting usernames from userBase instead. That is why you don't see anything. Get rid of addUser altogether, you don't need it. Add your usernames to userBase instead.
65,894,948
65,898,440
use "-I" to define g++ include path:why it only works when I set ".../include" instead of ".../include/boost"?
My application need boost lib. There is a boost lib in /usr/lib and boost include in /usr/include/boost, but they aren's what I need. So I compile new boost lib in my home , /home/js/anaconda/.../include/boost and /home/js/anaconda/.../lib. To use boost in home, I use "-I/home/js/anaconda/.../include/boost" to define t...
It's a common practice (but not mandatory) to include all the header files of a library into its own directory. This has a few advantages: When you look for a header file, you don't need to look through the header files of other libraries. When you read a file with include directives, you can see all the headers that ...
65,895,095
65,895,129
Moving unique_ptr constructed at lambda capture site into a vector fails
Dummy code of what I was trying to do: auto test_foo = [foo_o1 = make_unique<Foo>(), &vectorOfFoo]() { auto foo_o2 = make_unique<Foo>(); vectorOfFoo.push_back(std::move(foo_o2)); //COMPILES vectorOfFoo.push_back(std::move(foo_o1)); //ERROR: use of deleted function unique_ptr(const std::unique_ptr<_Tp, _Dp>&...
The function-call operator of the lambda is const-qualified by default, so foo_o1 that was copy-captured is non-modifiable inside of it. You can mark the lambda as mutable: mutable: allows body to modify the objects captured by copy, and to call their non-const member functions E.g. auto test_foo = [foo_o1 = make_uni...
65,895,435
65,899,245
how to access a tuple element by a non-const variable?
I have a tuple that I want to access element by a variable, how can I achieve this? Now I use the switch case to solve this problem. like this: unsigned short& indices(unsigned char samecnt) { switch (samecnt) { case 12: return std::get<12>(view).indices; case 11: ...
You cannot indeed use non-constant expression as template parameter, so you have to "transform" your runtime value into constexpr with some dispatching. switch is an alternative. In your case, you might use array: unsigned short& indices(std::index_sequence<Is...>, unsigned char samecnt) { std::array<unsigned short...
65,895,495
65,895,696
How to pass template of Anythings as template parameter in C++?
To have any types in template one may just write template <typename ...> struct S {};. To have any values (e.g. int values) in template one may write template <auto ...> struct S {};. To have template of any types in template one writes template <template <typename ...> class Tmpl> struct S {};. But how to have templat...
Strictly speaking, you cannot do what you're asking for. But what you can do is represent values as a special type, and then intermix that special type with other "normal" types. E.g., a helper could look something like this (untested code): template<auto v> struct value {}; Then any occurrence of value<...> would ind...
65,895,753
65,896,293
Compiling Kevlin Henney's Fizzbuzz with the use of lambdas in C++17 using Visual Studio 2017's compiler
I was following Kevlin Henney's Youtube video on Lambdas in programming. At about 20:30 - 20:40 in his video he gives this code snippet: string fizzbuzz(int n) { auto fizz = [=](function<string(string)> f) { return n % 3 == 0 ? [=](auto) {return "Fizz" + f("");} : f; }; auto buzz = [=](function<...
It is a bug; a?b:c is legal if b can be converted to an rvalue of type c and not vice versa (among other rules). To fix: auto fizz = [=](std::function<std::string(std::string)> f) { if(n%3 == 0) f = [=](auto) { return "Fizz" + f(""); }; return f; }; auto buzz = [=](std::function<std::string(std::string)> ...
65,896,197
65,896,306
How to separate a string with duplicated characters
I am trying to split string. For example, if I enter Shooby Dooby by the Wooby Sisters, the function should split the string so that the result will be Title: Shooby Dooby Artist: the Wooby Sisters but what I get from my code is Title: Shoo Artist: Sisters My code is string getArtistStr(string fName){ string retV...
Here is the solution to your problem: #include <iostream> #include <string> using namespace std; const string DELIMITER = " by "; string getArtistStr(const string& fName){ string retVal = fName; if (fName.length() > 0){ // Searches the string for the first occurrence of the delimiter int pos ...
65,896,295
65,896,484
Finding odd divisors with bit-shifting
(This question refers to this Codeforces problem) I want to find out if any n (2 ≤ n ≤ 10¹⁴) has an odd divisor or not. Using C++11, I thought it would be possible to brute force a solution by iterating through every odd number until n, and checking with % if it is divisible or not. Something such as: for(unsigned long...
To understand this, you have to understand how rightmost bit of odd and even number works. Basically any odd number has it's 0th bit(rightmost) as 1(remember bit counting start from right, i.e right most bit is 0th bit, then you go left one by one i.e 1st bit, 2nd bit and so on) and any even number has it's 0th bit as ...
65,896,600
65,904,364
codeforces problem named Strange List the "MEMORY LIMIT EXCEEDED"
With reference to the problem named "Strange List" in codeforces following is my code But the problem is All test case is passing but the last test case it is showing"MEMORY EXCEEDED LIMIT" and the last test case value is also huge like for n it is 100000. Please guide me the way to tackle it #include<bits/stdc++.h> #d...
You can use Dynamic Programming to solve this problem Implementation of storing results can be done by using Vector of pairs Below is the AC code demonstrates how these kinds of problems can be done efficiently in terms of memory consumption......Happy Coding :) CODE #include<bits/stdc++.h> using namespace std; #defi...
65,896,840
65,896,928
Zero initialization ignoring constructor
Following this and this discussion about zero-initialization, I would like to clarify in which situation these two paragraphs zero-initialization CPP reference occur at the same time: As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructor...
Then, in which case can I define a constructor for a class member and still ignore its constructor? Static storage. A class instance with static storage duration will be zero initialised during the static initialisation phase which ignores constructors if any. The constructor is called later in the dynamic initialisa...
65,897,214
65,897,807
How to get the next enum value from an enum in protobuf?
I have a protobuf message with non-consecutive enum values something like this: message Information { enum Versions { version1 = 0; version2 = 1; version3 = 10; version4 = 20; version5 = 30; } } I want to have a C++ function GetNextVersion() which takes in one enu...
You can use protobuf's reflection to achieve the goal: Information::Versions GetNextVersion(Information::Versions ver) { const auto *desc = Information::Versions_descriptor(); auto cur_idx = desc->FindValueByNumber(ver)->index(); if (cur_idx >= desc->value_count() - 1) { throw runtime_error("no next...