question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
67,097,801
67,097,939
Sending UDP packets via sendto
I want to send a datagram UDP message via sendto with 4-byte address, 1 short int number, and 4 bytes int distance. So it should be exactly 9-bytes. How can i do it? I already have tried to convert those values and put them in buffer, but it didn't work. sendto(sockfd, &message, sizeof(message), 0, (struct sockaddr*) &...
The most portable way is to assemble the bytes into a buffer yourself: uint8_t buf[64]; // make sure this is large enough to hold the bytes uint8_t * b = buf; uint32_t neDist = htonl(msg.dist); // send multi-byte values in big-endian form memcpy(b, &neDist, sizeof(neDist)); b += sizeof(neDist); memcpy(b, &msg.num,...
67,098,054
67,118,305
bernoulli_distribution vs uniform_int_distribution
In comparing bernoulli_distribution's default constructor (50/50 chance of true/false) and uniform_int_distribution{0, 1} (uniform likely chance of 0 or 1) I find that bernoulli_distributions are at least 2x and upwards of 6x slower than uniform_int_distribution despite the fact that they give equivalent results. I wou...
Some comments and answers suggest using uniform_real_distribution instead. I tested uniform_real_distribution(0.0f, nextafter(1.0f, 20.f)) (to account for urd being a half-closed range) vs bernoulli_distribution and the bernoulli_distribution is faster by about 20%-25% regardless of the probability (and gave more corre...
67,098,202
67,098,440
Avoid MSVC warning when casting ShellExecute return (HINSTANCE) to int
The docs for ShellExecute state (italicized emphasis mine): Return value Type: HINSTANCE If the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure. The return value is cast as an HINSTANCE for backward compatibility with 16-bi...
HINSTANCE is a pointer type. The compiler is warning you that the size of the pointer is larger than the size of an int, so bits will be truncated during the cast of HINSTANCE to int. That happens when you are compiling for 64bit, where a pointer is 8 bytes and int is 4 bytes. In this particular situation, that trunc...
67,098,261
67,098,301
I keep getting the error "uninitialized local variable '_ 'used" even though in if statements I initialize variables
Here is the program I wrote to try to find the largest and smallest of 4 integers. If I do define the variables before the if statements it removes the error but gives me just the original numbers instead, completely untouched. int I, II, III, IV; printf("Enter four different integers: "); scanf("%d %d %d %d", &I, &II...
The assignment operator copies the value in righthand to the variable in lefthand. You have to swap lefthand and righthand operator of all of your usage of =. For example, you should write s = I; instead of I = s;.
67,098,535
67,098,734
Extraction of specific data column in .txt file
I have a text file (data.txt) with 4 columns of data (1st column is time and 2nd, 3rd and 4th are specific data) and I want to write a program that extract one of the channel that it contains, calling it by its name so it creates a new file with only 2 columns (1st the time, 2nd the channel extracted). The command line...
Here is one method: std::vector<std::vector<double>> database; typedef std::vector<double> DB_Row; //... double column1, column2, column3, column4; while (file >> column1 >> column2 >> column3 >> column4) { DB_Row row; row.push_back(column1); row.push_back(column2); row.push_back(column3); row.push_...
67,100,416
67,100,485
how to cout a subclass after static cast into a vector
I have two classes, Article and a subclass ArticleOnSale (public inheritance). And also a class Boutique, which contains a vector<Article*> arts. I have defined the << operator for both Article and ArticleOnSale In Articles.cpp I have a public Addarticle void Addarticle(Article* a) { Article* p; if (typeid(*a) ...
A possible implementation that takes better advantage of virtual functions would be something like this: class Article { public: virtual bool is_on_sale() const { return false; } }; class ArticleOnSale { public: virtual bool is_on_sale() const { return true; } }; then your vector would need to look like: std:...
67,100,467
67,100,497
LNK1169 one or more multiply defined symbols found. I know this could be considered a duplicate but I could not find anything that solved my problem
I have one header file that my teacher requires. I am using a global variable so I can move the value from one function to another. Looking up the problem, someone recommended using a namespace. That did not work. Additionally, I added some guards like someone else recommended, but that did not help either. I have mult...
When exporting global variables, you want them to be defined in your c++ file so that it gets compiled only once by the compiler. Currently, including it from the .h file adds it to all of your .obj files (built by the compiler) and the linker does not like the same variable existing at multiple places when it tries to...
67,100,774
67,101,923
filesystem error: cannot create directory: No such file or directory
I can't believe no one seems to have posted this error or the solution. I am spinning up on C++ 17. I am attempting to run the following code. fs::directory_entry result(CodeSource::ARDUINO_SOURCE); if (!result.exists()) { fs:create_directory(result); } return result; and I get the following result. terminate call...
I have written a minimal program, and confirm that it's caused by the path ~/arduino_source, you need an absolute path or relative path, but for the tilde ~ character, it will cause exceptions. Since the API directory_entry::directory_entry and std::filesystem::create_directory both can throw, your code needs to handle...
67,100,878
67,100,900
Computer only has 32 bits of memory addresses, but has 16GB of ram installed and working?
I just started learning C++ and was surprised to see that when calling &varname, I got a 8 hex-digit-long number. Assuming this math is correct: 2^(8 hexits x 4 bits hexit^-1) x 1 bytes address^-1 = 4.29497e+09 bytes of RAM addressable I should only be able to address 4GB of ram, and yet my computer has 16GB, all of wh...
Possibility 1: Your program is compiled for 32 bit and your OS is 64 bit. Possibility 2: Your program is compiled for 32 bit and your OS is 32 bit with AWE support and can actually map all 16 GB, just not to all processes. EDIT: Now knowing the OS is Windows, the only Windows version ever released that can actually do ...
67,101,063
67,101,177
How can I write positive/negative tests for C++ overload resolution and SFINAE?
I'm currently designing some functions that make use of SFINAE to control overload resolution. This is easy to get wrong, so I'd like to be able to write both positive and negative tests for what the API can be called with. For example: // A templated function that should only be used via type deduction. (We // don't w...
Since you tagged this C++20, the better approach is to write a concept: template <typename... Args> concept canAcceptVector = requires (Args(*args)()...) { AcceptVector(args()...); }; Which you can then test: // We should be able to feed the function most vectors. static_assert(canAcceptVector<std::vector<double>>...
67,101,231
67,101,324
How to create an array of sub objects of varying size
I am trying to create an array of sub objects DubPrime of varying size within the class Cluster P. However, it doesn't let me create an array the size of dubPrimeCount, presumably because you can't create an array with an uninitialized size? I want to have it so that the user defines the amount of DubPrimes that is enc...
Use new [] and delete [] to manage your dynamic array. You may rerence the document here. #include <vector> class DubPrime {}; class ClusterP { private: int dubPrimeCount; DubPrime *dArr; public: ClusterP() : dubPrimeCount(5), dArr(new DubPrime[dubPrimeCount]) {} ~ClusterP() { delete[] dArr; } }; Or use std...
67,101,412
67,101,475
Extracing words that start with '#' from a string into a stringstream- C++
I am trying to write a program that will return words that start with the symbol # from a string. For example: A string such as "I like #tacos and #pizza" would return: #tacos #pizza This is my current code: int main(void){ string myString = "I like #tacos and #pizza"; std::istringstream iss(myString); whil...
You just need to check the string's first character with front or myString[0], and print the output in the loop. Your original code will at most print once so I move the print statement into the loop. #include <iostream> #include <sstream> #include <string> int main(void) { std::string myString = "I like #tacos and ...
67,101,982
67,102,100
Do desktop GUIs (Graphical User Interfaces) written in C++, C#, Java, etc use the concept of DOM or something similar, like all web or mobile GUIs do?
Its extremely common to heavily understand and use concepts of the Document Object Model (DOM), to create various kinds of GUIs for web and mobile applications. I was wondering though, whether GUIs for desktops, embedded systems, other electronic devices and so on (programmed using C++, C#, Java, Python, etc) use this ...
There are an insane number of ways to do it. Graphical OS's usually provide one or more widget tool kits, which can include configuration files, binding engines, or just APIs to create widgets of various kinds. The windowing system acts a bit like the browser environment. In graphical games and other less OS bound ap...
67,102,410
67,103,610
Create JSON string with key and value form in C++
We can create JSON file using PHP or JavaScript. Can we encode string format into JSON-encoded string using function or API? Any useful information will be helpful.
There is nothing in the Standard-Library, but you can find a List of Libraries on cppreference.com. Just go to the sections for JSON and Serialization.
67,103,121
67,103,320
How is the pointer (*) making changes in the following code?
The following program is intended to check if a given element is in a given array, indices of array where the element occurs and number of times the element occurs. But, it doesn't give right results. I tried to replace poscount in seqsearch function with *poscount and did further changes for this pointer data type. Th...
The function seqsearch is supposed to return the result in pos and poscount, but the function takes poscount by-value which means that any changes you make to poscount inside the function, will be local to the function and not visible from the call site. If you change the function to take the argument by-reference, the...
67,103,735
67,103,929
Method to get the children of a node in quadtree
I'm trying to recursively get all the children of a node using the method below. getchildren(), addChildren() and the constructor for the Node work fine but when I try to get the children using the method below, the vector kids seems to be empty and I don't understand why given that inside the method when I print n.ge...
kids should be a reference. You are passing the vector by copy, instead of a reference. vector kids is a local for the method, pushing anything into it is not pushed into the vector kids from the caller. void Quad::getChildren(Node n, vector<Node>& kids) // ^ reference
67,103,866
67,103,955
Write text from an array of strings
I'm trying to do this. #include<graphics.h> string words[4]={"Monday","Tuesday","Wednesday","Thursday"}; outtextxy(12,24,words[2]); But I keep getting the error cannot convert 'const string {aka const std::basic_string}' to 'char*' for argument '3' to 'void outtextxy(int, int, char*)' How do I put array elements int...
Your outtextxy() expects a char pointer not an std::string, so either change your function, or use a pointer. Since this expects a char, and a string returns a const pointer you need to cast it. If you can change the function, then I would recommend to change it at least to a const char *. outtextxy(12,24,const_cast<ch...
67,104,878
67,105,000
Child Class Operator << overload C++
How can i overload the operator << so it can show the attribute of the parent class as well when those attribute are private withing the parent class?? Parent Class: Movie header ifndef _Movie #define _Movie #include <string> using namespace std; Class Movie{ private: string title; int year; float ...
My recommendation is that you instead make an operator<< function for the base class. This operator then calls a virtual "output" function to do the actual output. Each child-class then overrides this output function to output its own data, and call the base-class output function to let it print its own data. For your ...
67,105,072
67,105,440
Opening a file to read and write, create it if it doesn't exist
I was trying to create a file in both read and write modes, but it doesn't create the file, what can be the problem? This is code: fstream file("NameFile.txt", ios::out| ios::in); The program will start, but it will not create any files.
When you open the file using fstream: To read, the file is required to exist; To write you need to specify a write mode, ofstream would do that for you, but with fstream you need to do it yourself: Replaces the contents of the file when you write (ofstream default mode). std::fstream file("NameFile.txt", std::io...
67,106,345
67,107,483
How to prevent file functions to access files outside game folder?
I'm making a DLL plugin for a game which modders can use in their mods and I'd like to make a function which deletes a file in particular folder. But I want to restrict users from deleting files outside game folder. alignas(16) char s_strArgTemp[0x4000]; // this is the filepath that modder specifies in the function. I ...
One of the best ways to sanitize paths is to use absolute paths. #include <memory.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> bool sanitizePath(const char* parent, const char* relPath) { char fullPath[MAX_PATH] = ""; if(!GetFullPathNameA(relPath, MAX_PATH, fullPath, nullptr)) { return fal...
67,106,518
67,592,781
Setting Status icon for CFAPI does not work as expected
I try to set the status icon of the placeholder file created with CFAPI to error. (see below) content of folder T: I set the error state on the file, but it does not display the error. However the error is displayed on the containing folder. I use following code to set the error on the file (the complete code is publ...
Someone pointed me to an pull request in the windows cloud mirror sample that shows how to accomplish this. This is the code: void Utilities::UpdateErrorOnItem(PCWSTR path, bool setError) { try { winrt::com_ptr<IShellItem2> item; winrt::check_hresult(SHCreateItemFromParsingName(path, nullptr, II...
67,106,662
67,107,003
When a map is copied to another existing map, what happend in details?
int main () { std::map<char,int> foo,bar; foo['x']=100; foo['y']=200; foo['z']=300; bar['x']=100; bar['y']=2000; bar['zz']=400; foo=bar; return 0; } Is it such a process that foo clear all its elements and then traverse bar to construct its new elements? Or foo traverse all the keys of foo and bar...
Is it such a process that foo clear all it's elements and then traverse bar to construct it's new elements? Or foo traverse all the keys of foo and bar and then execute only necessary modification? What your doing there is a copy assign. Meaning that first the foo will be cleared and then the elements in bar will be ...
67,107,283
67,113,498
Modify data member of base class from constructor of derived class in C++
I can't understand the output of this code. I expect 10 to be printed, but the output is 85. Can someone explain what's happening? #include <iostream> using namespace std; class A { public: int x=3; A(int a) : x(a) {} }; class B: public A { public: int y = 10; B() : A(...
As suggested by the link in @Someprogrammerdude's comment: The order of member initializers in the list is irrelevant: the actual order of initialization is as follows: If the constructor is for the most-derived class, virtual bases are initialized in the order in which they appear in depth-first left-to-right travers...
67,107,603
67,119,162
C++ What actually happens in assembly when you return a struct from a function?
I'm trying to figure out what actually happens in C++ if you return a struct by value from a function, vs. return a pointer to the struct. How is a struct communicated when its sent by value if a function can only return a value that can fit in a register? (I read that somewhere.) I tried testing it on Godbolt to see w...
So I spent hours playing with Godbolt's Compiler Explorer and reading up until I figured out the practical answer. What I've gathered is this: If the value fits into a register, it's left in a register as the return value. If the value fits in 2 registers, it's left in 2 registers. If the value is larger than this, th...
67,107,677
67,107,797
What could be a better solution to calling a function recursively?
This is a simple function which will take value from user and if value is invalid then the function will call itself recursively until a valid input is provided. #include<iostream> using namespace std; void getnum(){ int num; string strnum; getline(cin, strnum); try{ num = stoi(strnum); }...
You get multiple outputs because you print outside "the happy path" - move printing inside the try block. It's even clearer to put the entire "happy path" inside the try: void getnum(){ try { string strnum; getline(cin, strnum); int num = stoi(strnum); cout<<"\n"<<num; } cat...
67,108,829
67,109,960
Writing a C++ iterator for a sparse matrix class
I'm attempting to get a basic constant forward-iterator to work in C++. namespace Rcpp { class SparseMatrix { public: IntegerVector i, p; NumericVector x; int begin_col(int j) { return p[j]; }; int end_col(int j) { return p[j + 1]; }; class iterator { ...
Thanks to @Evg, here's the solution: namespace Rcpp { class SparseMatrix { public: IntegerVector i, p; NumericVector x; class iterator { public: int index; iterator(SparseMatrix& g, int ind) : parent(g) { index = ind; } bool operator!=(iter...
67,108,977
67,120,455
Pass Interface Array from C# COM Server to C++ Via IDispatch
I am trying to develop a C# COM server that is accessible to clients only via IDispatch. Some of the methods of my COM objects return an array of interfaces to other COM objects. When I attempt to do this using early binding, such as via the code provided in this answer, it works with no issues. As soon as I try and de...
Remember that IDispatch / late-binding was created for special clients (eg: VB/VBA/VBScript/JScript), and it's always a pain to use from pure C/C++ clients. With the original definition, here is how the IMyRootClass is defined (you can read that using the OleView tool from the Windows SDK on the .tlb file generated by ...
67,109,500
67,109,907
Wrong template function deduction
Unexpected function deduction is happening in the following program. - Case I - template <typename T, typename> void foo(T x, int) { cout << "In int foo\n"; } template <typename T> void foo(T x, char) { cout << "In char foo\n"; } int main() { string s = "Hello World"; foo(s, (int) 1); } Output In cha...
In this function, template <typename T, typename> void foo(T x, int) { cout << "In int foo\n"; } You tell the compiler that, There are 2 template parameters. The return is void. Takes two parameters, one from type T and the other is int. Then the function body. When compiling foo(s, (int) 1);, the compiler knows...
67,110,066
67,112,031
All ArUo Tags are getting Rejected when passing the image data from Unity
Background I am trying to detect ArUco markers from image data sent from Unity to OpenCV Functions which are accessed using their .dlls. Versions OpenCV : 4.5.0/4.5.1 Unity : 2020.1.17f1 Aruco dictionary : 6x6_250 family and AprilTags 36h11 family Problem When I use a camera and send each frame(as shown in code here),...
I was doing the flipping wrong! Now I flipped the image using a image tool(any editing tool which flips image works; rather than manually) and now it works.
67,110,122
67,111,424
What is pseudo expression in eigen?
Documentation if full of use of this term, e.g. Pseudo expression providing partial reduction operations Pseudo expression providing matrix output with given format but I can not find what it means.
I believe what the Eigen documentation refers to as "pseudo expressions" are actually instances of "expression templates". Use of expression templates is a common technique in C++ when implementing things like math libraries, or really libraries in any domain where it is expected that users will concatenate together mu...
67,110,403
67,111,070
Load QIcon from base64 string
Is it possible to create a QIcon from a base64 string? I see we can load base64 strings into a QByteArray. And I see we can create a QIcon from a QPixMap. Using that, I have tried the following: const QByteArray data = QByteArray::fromBase64("iVBORw0KGgoAAAANSUhEUgAAAB8AAAAlCAYAAAC6TzLyAAAABHNCSVQICAgIfAhkiAAAABl0RVh0U...
No need for QImage, though: you can create the pixmap directly from the byte array QPixmap pixmap; pixmap.loadFromData(data);
67,110,600
67,117,106
python c++ api PyRun_SimpleFile is not giving desired output
I am trying to run a simple py file in dev c++. /// **main file** string script_name = "example.py" char* script_name2 = new char[script_name.length() + 1]; strcpy(script_name2, script_name.c_str()); FILE* file_pointer; Py_Initialize(); file_pointer = fopen(script_name2,"r"); ...
The script runs fine Visual Studio 2019. But in Dev C++ : file_pointer = _Py_fopen(script_name2, "r"); This does the trick.
67,110,648
67,110,849
Sublime text 3 Build System in C++ which takes input from Terminal
I was looking for a sublime text 3 build system which could run my program in C++14, takes input from user using terminal and show my output also in terminal. After some search in online i find such a build system online which does that. The build System is as follows : { /* Custom Build file for C++14, supports input ...
The warning message is perfectly self-explanatory. In the "Run" section, the command is "cmd": ["bash", "-c", "g++ -std=c++14 '${file}' -o '${file_path}/${file_base_name}' && gnome-terminal -x bash -c '\"${file_path}/${file_base_name}\" ; read'"] After the &&, instead of having gnome-terminal -x bash -c ..., simply pu...
67,110,815
67,111,118
Constructor initializer list doesn't follow order
I have following code: class Base { public: Base(int test) { std::cout << "Base constructor, test: " << test << std::endl; } }; class Derived : public Base { private: int variable; public: Derived() : variable(50), Base(variable) {} }; Derived derived; And I would expect that output ...
Is there any way i can make Base constructor get called after? No. An object's constructor must construct its base classes before any named member variables. I'm trying to get rid of all the init methods and their calls by putting them into constructor instead That is a worthwhile effort! I'll assume your real cod...
67,110,983
67,111,169
C++: How to use class type in other Class?
i have a big problem, and i don't know if i miss some obvious things or what, however i can't find my mistake. I have Class SPN, A and B. I overloaded 2 times operator=. I want to pass A type or B type as parameter. void SPN::operator=(A*& R) { (*R)(*this); } void SPN::operator=(B*& R) { (*R)(*this); } and it ...
Since A.h and B.h get included in SPN.h and SPN.h gets included in A.h and B.h, there is a circular dependency. What I would do is remove the A.h and B.h includes from SPN.h You may need to forward declare A and B in SPN.h though (since it won't actually be including the file, it'll have the same error you're seeing no...
67,111,283
67,112,459
gcc how find -lglfw packages?
when cpp code Linking on vscode must define json file like below. { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ 활성 파일 빌드", "command": "/usr/bin/g++", "args": [ "-g", "glad.c", "-...
how gcc compiler detect args parameter. Gcc is a very old project with a lot of options. It has it's own command line options handling library. The -lXrandr word is the name of the package you have installed No, it's not the name of package. It's the name of the library. What does the compiler do? Compiler search...
67,112,066
67,112,201
Can a primitive-type data member of a derived class be used as a parameter to its base constructor?
Inspired by my (currently deleted) answer to this question (but there's a summary in my comment thereto), I was wondering whether the constructor for the Derived class in the code below exhibits undefined behaviour. #include <iostream> class Base { public: Base(int test) { std::cout << "Base constructor, t...
The behavior is undefined, regardless of whether or not the Base constructor accepts the parameter by reference. When control reaches Base(variable = 50), the lifetime of variable hasn't started yet, because data members are initialized after base classes. So first, writing to it causes UB because the lifetime hasn't s...
67,112,084
67,112,306
Effect of #include inside C++ enums
enum CMD { CMD_none, #define A(x) CMD_##x, #include "cmd.h" }; I encountered the above while going through a github repository. Can someone tell me what the above code does? I do not understand the effect of #include inside enum. The official documentation also does not tell anythi...
Can someone tell me what the above code does? enum CMD { This is a declaration of an enum by the name CMD. CMD_none, This is the first enumerator. Its name is CMD_none and the value is 0. #define A(x) CMD_##x, This is a pre-processor macro definition. #include "stdio.h" I do not understand the effec...
67,112,301
67,114,103
(Winsock) SMTP server not receiving anything
I'm trying to create a simple SMTP server using Windows Winsock, and currently it's just a TCP server printing whatever it receives. However, when I connect to it, it's not receiving any data; it's getting connections but nothing else (not even disconnection messages). If I change the port to anything but 25, everythin...
Never mind, it was Norton messing with me all along. If someone's having the same problem, I solved it by going into Norton -> Settings -> Antivirus and turning off Email Antivirus Scan.
67,112,498
67,113,602
boost::bind member function as argument inside its own member function
I am following a tutorial (https://www.gamedev.net/blogs/entry/2249317-a-guide-to-getting-started-with-boostasio/) for boost asio. Now I want to convert some of the aspects of this tutorial to a class, to learn more about what actually goes on within each part of the code. So I am trying to boost bind this: class LDser...
The problem is that the thread function isn't static, so it needs an argument for this (LDServer*). Or you can make it static: static void workerThread(boost::shared_ptr<ba::io_service> io_service) { io_service->run(); } void createThreads() { worker_threads.create_thread( boost::bind(&LDser...
67,112,581
67,112,629
Difference and nuances of std::uint8_t(-1) vs std::uint8_t(0xffu)
I have seen the use std::uint8_t(-1) for example here: https://en.cppreference.com/w/cpp/language/fold The CPP reference is illustrating endianness swap and I'm wondering what is the difference compared to a std::uint8_t(0xffu)? On x86 there doesn't seem any difference: https://godbolt.org/z/Kb7v8K1nT My question could...
It's a shortcut to get the maximum value of an unsigned type without having to care how wide it is. All unsigned types behave in modulo 2n so unsigned_type(-1) is the same as std::numeric_limits<unsigned_type>::max().
67,112,794
67,112,833
Understand the constructor and the assignement c++
I’m a newbie in C++ and I come from C. The OOP is a whole new paradigm for me. So I will ask a question on this stupid example: #include <iostream> class Object { public: int first; int second; Object ():first (0), second (0) { std::cout << "created1\n"; } Object (int x, int y):first (x...
As far as Object's compiler-generated operator= is concerned (since you did not implement your own), there is no difference. It takes a const Object & reference as input, but it doesn't care where that Object comes from. The only real difference in this code is in where that Object is coming from. s = {2, 2}; construc...
67,112,813
67,114,366
C++ std::map named requirements allocator-aware container
Currently I'm trying to convert some of C++'s named requirements to C++20 concepts (https://godbolt.org/z/EdY5d6319 still highly WIP!). However, I stumpled upon a problem. Given the final C++20 working draft (http://open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4861.pdf): page 790: requirements for an allocator-aware ...
There's an explicit carve out for this case in [containers.associative.reqmts]/7: The associative containers meet all the requirements of Allocator-aware containers, except that for map and multimap, the requirements placed on value_­type in Table 76 apply instead to key_­type and mapped_­type. [ Note: For example, in...
67,113,057
67,139,864
How do I obtain a non-empty optional with the value inside it being default constructed?
Let's say I have a default constructed, thus empty, object ov of type std::optional<std::vector<int>>. Yeah, std::vector can express the concept of being empty without the help of std::optional, but bear with me. And then let's say that, based on some logic, I decide that I have to fill it with a vector on which I want...
The easiest way is std::optional<std::vector<int>> ov = {{}}; alternatives include std::optional<std::vector<int>> ov(std::in_place); sadly there is no way to do this with assignment instead of construction; {{}} is ambiguous, and the std::in_place constructor is explicit. There you have to call ov.emplace(). You cou...
67,113,252
67,113,449
Componentwise addition of elements of linkedlist of same size in c++
I need to define a class for linkedlist in which I need to support the componentwise addition of elements of linkedlist of same size using a sign +. I defined an operator in class that do 0 based indexing of elements in my list. Here's the definition of indexing operator. int operator[](int index) { node* current = h...
res[i] = (don't know what to put) + l[i]; You can dereference the this pointer to call your operator[] on the object that the operator+ is being called on, eg: res[i] = (*this)[i] + l[i]; Or, you can just call the operator directly like any other class method, eg: res[i] = this->operator[](i) + l[i]; However, even ...
67,113,369
67,124,968
Microblaze & C++ | Why does the code size increase dramatically under certain conditions?
I have been developing embedded software for the Microblaze processor for more than a year using C++. My designs were not so complex, so I wasn't using the powerful, object-oriented features of the language. For a while, I have been trying to enhance the structure of my designs. For this purpose, I try to widely use th...
The solution is a little bit creepy :) Before beginning, special thanks to everyone who helped. SHORT ANSWER Just add the following code piece to your main file: extern "C" void __cxa_pure_virtual() { while(1); } If you also want to solve the problem related to operator new and operator delete, add the following codes...
67,113,620
67,114,234
Visual Studio 2019 C++ After Successed Build Run an .exe
How to make my Visual Studio 2019, running an custom exe after my C++ Build successfully compile? i tried to insert into the PostEvent builds, following command: "start C:\Test.exe" but the executable starts while the compile is running ( compile completes only when i exit the Test.exe). I wanted to start the Program d...
It's not pretty but it does the job: powershell "Start-Process c:\test.exe"
67,113,673
67,114,173
How to access a template struct const variable in CPP
I am working with a code in which I am passing a constant variable to a templated struct like this #include <iostream> using namespace std; //Compiler version g++ 6.3.0 template<typename T> struct Data { T age; }; void show(); int main() { Data<const int> person{ 18 }; cout << per...
Your code simply does not work. The person variable is not populated to the show()'s body, so inside that function you just create a default struct where you do not specify a value. In the end, it crashes. What you can do is: Pass a structure to the function and get its inner variable. Create a static structure in the...
67,113,706
67,116,280
Why does setting SO_SNDBUF and SO_RCVBUF destroy performance?
Running in Docker on a MacOS, I have a simple server and client setup to measure how fast I can allocate data on the client and send it to the server. The tests are done using loopback (in the same docker container). The message size for my tests was 1000000 bytes. When I set SO_RCVBUF and SO_SNDBUF to their respective...
Clues for what is going on come from the kernel source handle for SO_SNDBUF (and SO_RCVBUF but we'll focus on SO_SNDBUF below). net/core/sock.c contains implementations for the generic socket operations, including the SOL_SOCKET getsockopt and setsockopt handles. Examining what happens when we call setsockopt(s, SOL_SO...
67,114,653
67,115,511
Receiving large binary data over Boost::Beast websocket
I am trying to receive a large amount of data using a boost::beast::websocket, fed by another boost::beast::websocket. Normally, this data is sent to a connected browser but I'd like to set up a purely C++ unit test validating certain components of the traffic. I set the auto fragmentation to true from the sender with ...
If your use pattern is fixed: std::string data(boost::beast::buffers_to_string(m_buffer.data())); And then, in particular callback(data); Then there will be no use at all reading block-wise, since you will be allocating the same memory anyways. Instead, you can raise the "locally configured limit": ws.read_messag...
67,114,717
67,116,057
Does OpenGL position the screen in front of the camera?
I am attempting to convert a mouse click to a global position. Even though the worldspace is 3d, I am currently trying to find the x and y coordinates of the click at z = 0. I have written up some code that does the converting, and it is almost correct. But there seems to be an error that grows with distance from (0,0)...
Assuming some standard conventions for the view matrix, this does not make sense: glm::vec4 mouseClickVector = invVP * glm::vec4(mouseX, -mouseY, 1.0f, 1.0f); glm::vec3 norm = glm::normalize(glm::vec3(mouseClickVector)); Usually, the view matrix contains both the orientation and position of the camera. You seem to ...
67,115,537
67,116,149
cannot declare field ‘’ to be of abstract type ‘’
I'm trying to write asynchronous code on callbacks and stuck into this error: error: cannot declare field ‘std::_Head_base<3, Callback, false>::_M_head_impl’ to be of abstract type ‘Callback’ note: because the following virtual functions are pure within ‘Callback’ ... error: no matching function for call to ‘std::tu...
The real problem with your code is this: std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) { func.OnResult({"API_Mul", arg1 + arg2}); }, arg1, arg2, std::forward<Callback>(func)); The call to async that you are using has this signature: template< class Function, class... Args> std::future<...
67,115,631
67,117,368
VirtualQueryEx unable to read memory, so can't dereference pointer (LPCVOID/uint8_t*)
I have a function to read the memory of an application template<class T> std::unordered_map<uint8_t, T> find_byte(T find) { std::cout << "Searching for value\n"; std::unordered_map<uint8_t, T> mapping; // Turn the T bytes to a vector to use nice C++ functions std::vector<uint8_t> byte_check; if co...
When you query a memory region, you should start scanning through its content from its BaseAddress, not from the address that you actually queried. VirtualQueryEx() may have to round down the address. info.RegionSize is relative to info.BaseAddress, so when calling ReadProcessMemory(), mem_chunk.size() will be too ma...
67,115,633
67,115,721
Drawing a dot with OpenGL
My program is supposed to open a window and draw a single blue dot in the center but fails to draw the dot. This is the full code I'm working with: #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #define numVAOs 1 GLuint renderingProgram; GLuint vao[numVAOs]; GLuint createShaderProgram() { const ...
A few issues: #version 320 doesn't exist, it went from version 150 in OpenGL 3.2 to version 330 in OpenGL 3.3. Drop down to #version 150 and make sure to check the shader compilation and link logs. GL_POINT is not a valid value for glDrawArrays()'s mode argument, you're thinking of GL_POINTS. Make sure to clear the ...
67,115,840
67,116,665
Why can't std::pair be compared to std::initiliazer_list
For std::pair, I am just curious to know why this works std::pair<int, int> response = {1, 2} while, this doesn't: if (response == {1, 2}) do something; Is it because the operator = is overloaded for std::pair while == isn't?
This is just syntax: braced-init-list can be an operand only to [] and () (on the inside) and = and any @= (on the right). The initialization case is also allowed, where there is no operator at all.
67,116,835
67,116,945
Eigen C++: Best Way To Convert 2D Polar To Cartesian
I am currently doing: Eigen::Vector2d polar(2.5, 3 * M_PI / 4); Eigen::Vector2d cartesian = polar.x() * Vector2d(cos(polar.y()), sin(polar.y())); but I'm not sure if this is the correct way to use Eigen or if there is some better built in way. Thanks!
That looks right to me if you're wanting to stick with using Eigen. Generally though since the polar representation has angles, it might be good to avoid using the Eigen::Vector2d just for the sake of reducing mistakes that may be made in the future (like adding multiple angles together and not dealing with the fact th...
67,116,949
67,117,347
C++ SFINAE partial specialization
I've been trying to define an auxiliary class to help me work with template methods in which I would like a generic implementation both for complex and real types. That has been my attempt so far: #include<type_traits> #include<complex> template<class T> struct is_complex{ static constexpr bool value = false;}; temp...
Usually this is done with specialization and a template defaulted parameter. I mean template <typename, typename = void> struct real_type; template <typename T> struct real_type<T, std::enable_if_t<std::is_arithmetic_v<T>>> { using type = T; }; template <typename T> struct real_type<std::complex<T>, void> { using t...
67,116,968
67,117,013
Comparing Char to String
I am currently doing a college project and most of my background comes from JS & Python. I have an Arduino that is receiving data and using ArduinoJSON to take in settings and deserialize them. I have it set up that the setting is a const char* setting. Which can contain a range of data types (mostly int or bool). ...
With const char*, the == operator will compare the pointer values rather than the text value (which will generally always be different since the data is stored in different locations). You could change it to: if (strcmp(setting, "true") == 0) { test = true; } else if (strcmp(setting, "false") == 0) { test = false; } i...
67,117,470
67,117,677
Accessing the address of a member data through qualified name yields error
As we know, a direct or indirect base class's of a derived class public and protected members are available in that derived one. So I have this example: struct Foo{int x_ = 10;}; struct Bar : Foo{}; struct FooBar : Bar{ void f()const{ std::cout << &x_ << " : " << x_ << '\n'; std::cout << &Foo::x_ <<...
First of all, most likely you did not intend to repeat the & operator in each std::cout statement, so I've removed each repeated instance, to print the value of a member rather than its address. Now watch this: #include <iostream> struct Foo{int x_ = 10;}; struct Bar : Foo{}; struct FooBar : Bar { void f()const {...
67,117,598
67,117,865
0xC0000005 Exception thrown when reading binary file (C++)
I'm trying to have user login and registration system using binary files to save the data, and check if username and password are equal to those saved. It seems to work fine when Create_Login() and Write() are called and even when Login() is called after. The problem occurs when Login() is called by itself. The Excepti...
Exception resolved. by changing ReadFile.read(reinterpret_cast<char*>(&username), sizeof(Files)); ReadFile.read(reinterpret_cast<char*>(&password), sizeof(Files)); to ReadFile.read(reinterpret_cast<char*>(&username), sizeof(username)); ReadFile.read(reinterpret_cast<char*>(&password), sizeof(password)); thanks ...
67,117,999
67,118,167
Iterating over a parameter pack of structured templates
I'd like to be able to pass a variadic function a number of structured templates (representing sensor readings) and have it iterate over the members of those structs. My template and initializers look like this: template <typename T> struct reading_t { const char *name; const char *fmt; const char *units; ...
If I understood correctly and you want to concatenate names of readings using parameter pack inside concat_readings, then you can do next. You can use no standard library includes at all, just implement your own string management functions like strcat/strcpy. In fact you can use fully working C++ features with template...
67,118,241
67,118,349
loop involving "cin.fail()" running multiple times
I am having trouble with the following code. It is meant to keep asking for a valid input until an integer or double is inputted. It works as intended for characters, however when I input a string of length more than 1, it will run the loop multiple times. For example, the input "hello" with cause "Please enter a valid...
You need use ignore with the overloaded one, see this anser here. Or you can just need to run getline to drain the contents, but this way is slower and unnecessary. #include <iostream> #include <string> int main() { double n; while( std::cout << "Please, enter a number\n" && ! (std::cin >> n) ) ...
67,118,776
67,121,178
Forcing optimalisation selectively on a std operator overloads
For code I own, I can selectively force a lot of things with __attribute__ which is amazing. However, I would like to selectively change a function I do not have access to. I tried to put it into a wrapper like this, naively hoping it would 'inherit' it and do what I want (of course it did not as the code is compiled i...
Chances are that the relevant definitions are in the #include <atomic>. You would need to put that at the top of your source file, surrounded by #pragma GCC push_options #pragma GCC optimize ("O3") #include <atomic> #pragma GCC pop_options (https://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html) Of c...
67,119,114
67,119,154
How to use both member function and friend function operator overloading in same class
As per an assignment requirement, I am trying to implement prefix ++ and postfix ++ operator overloading both as member function and friend function in same class. class dist { private: int kMeter; int meter; public: // postfix dist operator++(int unused) { dist dd = *this; (this -> met...
Most operators can be overloaded either as member or nonmember function. Some operators (= [] () ->) can be overloaded only as members. But you cannot have any oeprator both as a member and nonmember, specifically because it is unclear how to pick either one of them. What the assignment wants is probably: you overload...
67,119,268
67,119,379
I need to calculate the average of the numbers that the user writes, but when I try it tells me that the average is always 0
I need to calculate the average of the numbers that the user writes, but when I try it tells me that the average is always 0. #include<iostream> using namespace std; int main() { float Prices[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int n, Avr, i; float PrzVar; do { cout << "Inserire la quan...
Average of n numbers = (Sum of numbers)/(Number of numbers); In your code, these are the issues: I guess you intended to use PrzVar to store sum, however you placed it outside of loop. Also PrzVar has to be initialized to 0 Your final answer is stored in Avr but it is an integer, so you may get some rounding off in so...
67,119,376
67,119,527
Why am I getting strange values for integer in this example of derived class (C++)
I was given a task to write an example of derived class. But In my program, something strange is happening with the roll numbers. Also, when this program is compiled in g++. When I used char [] and gets() to store the strings and input values into them, it didn't allow me to enter the value for collname. When I use str...
You just forget the [i] after rollno in the two lines like: cout << i+1 << ".) Roll number: " << rollno[i] << " : "; There are a few other things I would ask you to improve if I was your supervisor/teacher: always use expressive variable and method names. Avoid any abbreviations. why is there the arbitray offset o...
67,119,850
67,120,039
Only allow a C++ vector to grow when resizing
Is there an alternative to resize() of an std::vector, which only allows the increase the size of the vector std::vector v; v.resize(10); v.resize(5); --> v.size() == 5, but I like its length to stay at 10 and moreover I like its data not to be (potentially) deleted. I could use std::vector v; v.resize(std::max(v.size...
This seems like a strange request. It would be interesting to know why you want this infinitely expanding vector. One solution (as suggested here) would be to inherit from std::vector privately and implement your own resize, ie something like: template <class T> // Can also forward the allocator if you want class Infin...
67,120,195
67,120,867
The path to include header files
Assuming there is C:\somelib\headerfromsomelib.h. I used to put on my project.pro the following INCLUDEPATH += C:\somelib And on file.cpp I will put #include "headerfromsomelib.h" Then hitting F2 over it will led me to that header file. In another approach I can, instead, add C:\somelib to the INCLUDE environment va...
A more reliable way of using environment variables for library paths is to create environment variables for each library. E.g. create an environment variable SOMELIB_PATH then you can do: INCLUDEPATH += $$(SOMELIB_PATH) This can be extended for libraries you need to link to as well: INCLUDEPATH += $$(SOMELIB_PATH)/inc...
67,120,260
67,120,486
C++ Preprocessor: Iterate over comma-separated list argument
I'm trying to generate comma-separated list of vectors of given types to instantiate std::variant of vectors. (I didn't want to write a huge one-line code so I decided to use macros. I am open to new suggestions for this root problem). Is it possible to write macro which would define a preprocessor variable which would...
This can be done with C++ templates: #include <variant> #include <vector> template<typename... Types> using VariantVectorGenerator = std::variant<std::vector<Types>...>; using MyWeirdVariantVectorThing = VariantVectorGenerator<int, double, float>; int main() { MyWeirdVariantVectorThing x; x = std::vector{42}...
67,121,073
67,121,669
Is it better to declare a large vector as a member variable or a local variable inside a member function?
Let us say we need to process a large vector, which is only locally used inside a member function. Do we have any advantage in declaring it as a member function to save reallocation time? Because everytime a 10000 ints are being created and destroyed? Assume this is running in a mission critical embedded system. And th...
Yes, there might be a performance gain by declaring it as a member variable, but it might also be insignificant. As always: Measure, don't assume. Constructing and destroying the ints is not the issue (this is a no-op), but the memory allocation and deallocation will be what changes. This will be dependent on which all...
67,121,169
67,121,255
convert unsigned char* into std::vector<uint8_t>
Hey I am trying to convert unsigned char* into std::vector<uint8_t> and here's what I have already tried. uint64_t something(unsigned char* raw1) { std::vector<uint8_t> raw_image; for (auto b : raw1) { raw_image.push_back(b); } } I could not get it to work, any more help will be appreciated!!
Once you know the size, you can easily use the correct std::vector constructor instead of your loop: std::vector<uint8_t> raw_image(raw1, raw1 + raw1_size); In this case the above invokes the iterator constructor overload. With that said, remember that this creates a copy of the data, it's not a "view" of the data poi...
67,121,212
67,121,320
How can I use templates here to avoid using std::function in this code
I have a class that describes a certain type of function (here I mean function in the mathematical, and not programming sense). Within this class I have a method called integrate(...) which uses std::function and std::string to determine exactly what to do. I know the way I have done things is poor, and I would like so...
Create sub-function: private: template <typename F> double integrate_impl(F to_be_integrated, double some_other_parameter, SomeType domain_of_integration) { // ... // evaluate the integral using // to_be_integrated, some_other_parameter and domain_of_integration ...
67,121,298
67,121,379
Why does writing pointer type in front of malloc function in C++ language?
int *pi = malloc(sizeof(int)); It can do in C language but in C++ language, it has compile error. In C++ language, it should use this way. int *pi = (int*) malloc(sizeof(int)); what difference is malloc function in C and C++ language?
C and C++ are two different languages each with their own set of rules. In both C and C++ malloc returns a void*. In C a void* is compatible with any pointer so it can (and should) be assigned directly. In C++ it is not compatible with anything else so it cannot be assigned directly to a non void*. So if you want to us...
67,121,553
67,122,414
Define enum-like constants of a class without providing access to the class constructor
In Java I can define enum constants that have multiple members and member functions, yet do not provide public access to the enum constructor so that the client code cannot create enums in addition to those that are already defined. I would like to emulate this behavior in C++, and tried to do so like this: // Card ran...
You might use class as namespace to allow friendship: class CardRank { private: friend class CardRankNamespace; constexpr CardRank(int val, char repr) : val{ val }, repr{ repr } {} public: int get_val() const { return val; } char get_repr() const { return repr; } private: int val; int repr; }; ...
67,121,659
67,121,728
Can't I change the pointer to another one when I use new operator in C++?
I ask you questions because there is something I don't understand while studying dynamic allocation in C++. Can I delete "St" and use "ptr" instead if I move the address stored in St to another pointer "ptr" when the dynamically allocated memory is pointed by the St pointer? If I delete the "St" dynamic allocation, can...
Once you've called delete[] on the pointer you get back from new Student[10], the value of that pointer is indeterminate. Both St and ptr are exactly that, but you reassign St. (Since C++11, use nullptr rather than NULL.) The behaviour of dereferencing the pointer you get back from new Student[10] following the delete[...
67,121,824
67,121,969
C++: I'm having trouble with find()
I'm not very experienced with c++, and I'm having trouble w/a program I'm making to learn some string functions. I've tried troubleshooting via writing other programs to test the functions individually. Expected behavior: It determines a name before the " ", and an integer after. Demonstrated behavior: Returns w/a blan...
Try using getline(cin, uni). cin on its own only reads until the first space. Also, the find() function returns the position of the string you search for. You might want to use the substr() function for gold too. Edit: I believe you meant to write the '+1' and '-1' outside the find() function brackets to get the positi...
67,122,354
67,125,767
How to add label / text to wxStaticBitmap?
I am trying to add label to wxStaticBitmap, but it is not appearing in the panel. Here is my code. bitmap_file_name = _U("numbertwo.png"); wxBitmap Featurebitmap((bitmap_path + bitmap_file_name), wxBITMAP_TYPE_PNG); wxStaticBitmap *pFeature = new wxStaticBitmap(this, -1, Featurebitmap, wxDefaultPosition, wxDefaultSize,...
wxStaticBitmap shows only a bitmap, it doesn't support text label. You have many choices to show a label if you need it: Simplest: use a separate wxStaticText control. Modify the bitmap itself to draw a label over it. What you probably need as it looks like your control is supposed to be used, and not just be "static"...
67,122,909
67,123,043
Numpy data size twice of the Eigen Matrix size is that the case?
I am generating numpy array with : p_desct = np.random.uniform(-1, 0.4, [5000000, 512]) Memory size almost ~20G Same data in Eigen Matrix (C++): Eigen::MatrixXf x_im = Eigen::MatrixXf::Random(5000000,512); MemorySize ~9,6G Is that the case numpy array doubles the memory usage of same matrix ? or am I missing some...
Numpy arrays use 64-bit floats (often called 'double') by default, while your C++ array uses 32-bit floats. This means your numpy array takes twice as much memory as your C++ one. Specify dtype = np.float32 if you wish to use 32-bit floats. Also see https://numpy.org/doc/stable/user/basics.types.html for all numpy arra...
67,123,092
67,123,252
signaling that unique_ptr is nullptr to classes using raw_ptr
I have underlying code. Is there a way to signal to the raw pointer that it's corresponding unique_ptr has been reset? std::unique_ptr<int> pi = std::make_unique<int>(3); int* rpi = pi.get(); std::cout << "rpi = " << *rpi << std::endl; pi.reset(); if( rpi != nullptr) // this is always the case { std::cout << "rp...
Assuming that your raw pointer value may end anywhere in program, no you can't. Imagine that you would need some kind structure that contains a reference or pointer to a unique global variable created for your smart pointer. That variable stores state, not the "structure-pointer" you pass around. That it would work. No...
67,123,273
67,123,832
const object assigning its address to pointer to non-const in its constructor
Why does the following code compile and the compiler doesn't issue any error or even a warning? AFAIK, the code has undefined behavior. But what is the reason the compiler is silent about this? class C1; class C0 { public: C1* c1{ nullptr }; }; class C1 { public: int i{ 0 }; C0 c0; C1() { c0.c1 = thi...
Intro: class.ctor "A constructor can be invoked for a const, volatile or const volatile object. const and volatile semantics ([dcl.type.cv]) are not applied on an object under construction. They come into effect when the constructor for the most derived object ([intro.object]) ends." class C1; class C0 { public: C...
67,124,287
67,124,404
Perform operations on std::variant<POD_PTR*...> in a generic way
Say the following variant is given: using Variant = std::variant<uint32_t*, uint16_t*> And then, a vector of such variants is needed: using VariantVecType = std::vector<Variant> How would one go about accessing the underlying values (pointed to by those pointers) to perform arithmetic operations on them in a more gen...
Usually you would use std::visit example #include <iostream> #include <variant> #include <cstdint> #include <vector> // from cppref: // helper type for the visitor #4 template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; // explicit deduction guide (not needed as of C++20) template<class... Ts>...
67,124,525
67,126,568
OpenMP parallel instantiation and modification of vector of vectors
I'm using OpenMP to parallelize some union operation on Boost::geometry polygons (BPolygon). However I am stumbling over very strange exceptions that only occur from time to time (despite my RNGs being seeded with the same seed) so I wonder whether I'm ignoring some undefined behaviors with OpenMP parallelization and c...
Thank to the comments, I realized that my idea about containers being thread-safe was wrong (well they are safe to read but not to modify). Assignments and call to push_back must be wrapped in #pragma omp critical
67,124,700
67,125,309
Why is address sanitizer not detecting this simple memory leak?
Does anybody have any idea why address sanitizer is not flagging this very obvious memory leak class A { public: A() = default; }; TEST_F(LibrdfSerializerTests, Test) { A* a = new A; } built with the following added to cmake: set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fs...
You can try using the ASAN_OPTIONS=detect_leaks=1 while executing the binary to detect leaks. Using the example from the documentation ❯ cat leak.c #include <stdlib.h> void *p; int main() { p = malloc(7); p = 0; // The memory is leaked here. return 0; } Compile the program clang -fsanitize=address -g leak.c and...
67,124,725
67,125,202
How to input and store long ints from a file to process it in a c++
So i have a long int dataset with about 3-4 million numbers in a .txt file which is one number per line and i want to take the numbers as an input for my program, i am not sure how to get it right, for my current code i am getting a segmentation fault long long int *buff; buff = (long long int*) malloc(100000000 * size...
I'm not 100% sure what your objective is but it looks like: You want to read long longs from a file. You want to filter some of them out. You'd like to apply the filter by looking at the numbers as strings. Since C++20, we have std::ranges::copy_if with projection: #include <algorithm> #include <fstream> #include <io...
67,125,273
67,125,512
Why does the sizeof operator produce different results for an array
Why does the sizeof operator produces 12 bytes when it should only be 4? When I reference the variable array, that is only referring to the memory address of the first index of the array. In fact, I printed the memory address of the first index &array[0] and compared it to array, they produced the same memory address r...
Arrays and pointers are not the same, and this is a prime example of this. In most contexts, an array decays to a pointer to its first member. One of the few times this decay does not happen is when the array is the subject of the sizeof operator. In that case it refers to the entire array and the expression evaluate...
67,125,788
67,125,974
mciSendString check if music is playing
I have an application that uses the mciSendString function to play mp3 files. The function that starts playing music is this one: void PlayMp3(std::string name) { std::string command = "open " + name + " type mpegvideo"; mciSendString(command.c_str(), NULL, 0, 0); command = "play " + name; mciSendString...
Based on: https://www.codeproject.com/Articles/63094/Simple-MCI-Player You would write something like this: void Mp3IsPlaying(std::string name) { std::string command = "status " + name + " mode"; char status[128] = {}; mciSendString(command.c_str(), status, 128, 0); return (strcmp(status, "playing") == ...
67,125,833
67,127,302
UWP - Write file using C codes
I have a C++ UWP app that calls a C function which writes to a file .e.g. FILE * fp = fopen ("file.txt", "w+"); fprintf(fp, "Hello"); fclose(fp); fopen() failes with error 13 which means that there are insufficient permission on the directory. How can I ensure that the C function can write to a file?
Since UWP runs in a sandbox, I solved it by getting a writable file path in C++: StorageFolder^ localFolder = ApplicationData::Current->LocalFolder; String^ path = localFolder->Path; Then I passed the path to the C program.
67,126,216
67,127,310
#defined enum on Doxygen
So I have a #define that creates a "MY_ENUM" (minimal version) #define MY_ENUM(ename, ...) \ namespace ename { \ enum ename { __VA_ARGS__, COUNT }; \ static std::string _Strings[COUNT]; \ static inline size_t size() {ret...
With the following code: /// \file #define MY_ENUM(ename, ...) \ namespace ename { \ enum ename { __VA_ARGS__, COUNT }; \ static std::string _Strings[COUNT]; \ static inline size_t size() {return COUNT;} \ } /** * @brief List of elements */ MY_ENUM(enuElements, ...
67,126,233
67,126,576
Pointer to Parent Class Member Method
I am trying to get the following simple code to work: #include <functional> #include <iostream> class Parent { public: void method(int a) { std::cout << "Parent::method(" << a << ")" << std::endl; } }; class Child : public Parent { public: }; template <typename T> std::function<void()> test(T* v...
Child "is a" parent It is in the object-oriented sense. But template argument deduction is primarily about type identity. &Child::method names a member of Parent. It may be accessible in Child but it is declared in Parent. So the only available deduction of T from that member is Parent. On the other hand, the pointer...
67,126,284
67,127,055
How would I store multiple different value types contiguously in the same array in c++?
for something I'm building I need to be able to store runtime created structs in an array, I also want these structs to be stored contiguously in memory. Is there a way to store a sequence of objects in an array, without knowing what objects they will be at compile time? I will know every possible object that could be ...
So I think I found an answer: std::vector<std::byte> bytes; void addFloat(float value) { size_t index = bytes.size(); bytes.resize(bytes.size() + sizeof(float), std::byte(0)); *(float*)(&bytes[index]) = value; } float readFloat(size_t index) const { return *(float*)(&bytes[index]); } This can read an...
67,126,912
67,127,060
Calling private member getter call class destructor every time
I'm working on a C++ project and I encountered this weird behavior. I have a Weapon class defined as follows: class Weapon { public: Weapon(std::string type); Weapon(void); ~Weapon(void); void setType(std::string type); std::string const &getType(void) const...
Even though you have defined the _weapon member of your HumanA class as a reference to a Weapon, the getWeapon function is declared as returning an actual Weapon object (by value); so, when called, it will make a copy of the Weapon object referenced by the member and return that – the copied object will be destroyed (a...
67,127,599
67,163,320
ZeroMQ: link to message relation
I am using the ZMQ's Pub-Sub-Pattern. And I know it is possible to connect a subscriber to any number of publishers in order to receive with the ZMQ recv-function all the publisher messages over just one socket. However, I also need the information over which "link" (e.g. ipc:///tmp/link.ipc) I received the current rec...
There is no way to query that information from the zmq frame. Another option would be to publish multipart messages with an "part" containing the IP address or ID if address is too long.
67,127,672
67,128,482
C++ System(); function not working as expected / Windows console commands in C++
Hello friendly people of stack overflow! I am currently working on a project using an Arduino Uno. Because i create all my files and sketches using a c++ program, i want to eliminate the Arduino IDE from my workflow. For that i can very easily use avrdude (which the IDE uses anyway) and some windows console commands. T...
The command looks messed up with respect to the parameters, although I don't see how exactly that triggers your specific error. The beginning is OK. The path is properly quoted (double quotes, protected by backslashes from the C compiler). But why do you have slashes and backslashes mixed? In some online examples I saw...
67,127,770
67,128,058
Why does ranges::sort return an iterator?
I can see that std::sort returns void. But now that ranges have been added to the C++20 Standard, why does std::ranges::sort return an iterator? cppreference specifies: Return value An iterator equal to last. What's the rational behind that choice? What's the use case advantage compared to void?
You don't have to pass an end iterator to the algorithms in std::ranges. You can pass a sentinel instead, which is something comparable to an iterator, but it's not itself an iterator (it can't be dereferenced or incremented). Think of how this might be useful if you wanted to pass a null-terminated string to an algori...
67,127,919
67,127,994
std::regex not matching
I have a regex which by regex101 works correctly: There are 2 matches, as intended. Now I'd like to split the same with std's regex_token_iterator: const std::string text = "This is a test string [more or less] and here is [another]."; const std::regex ws_re("\(?<=\[)(.*?)(?=\])\gm"); // HOW TO WRITE THE ABOVE REGEX ...
You can use const std::regex ws_re(R"(\[([^\]\[]*)\])"); Also, make sure you extract Group 1 values by passing the 1 as the last argument to std::sregex_token_iterator instead of -1 (-1 is used when splitting). R"(\[([^\]\[]*)\])" is a raw string literal that defines the \[([^\]\[]*)\] regex pattern. It matches \[ - ...
67,128,376
67,131,988
Recursively generate tuple of all distinct types referenced by a struct
I'm specifying a graph of types at compile time with usings and std::tuples like this: #include<tuple> struct C; struct A { using ReferencedTypes = std::tuple<>; }; struct B { using ReferencedTypes = std::tuple<C>; }; struct C { using ReferencedTypes = std::tuple<B, A>; }; struct D { using Referenc...
My template metaprogramming skills are rusty, but I have something working that will correctly ignore the cycles. For example, I'm sure a better answer will not force the use of std::tuple_cat and SFINAE. For the sake of readability, I used requires instead of SFINAE dark arts. First, let's write a metafunction that wi...
67,128,454
67,128,503
std::map: wrong number of template arguments, and assignment of read-only location
I am learning design patterns in C++. Now I am trying to implement Abstract Factory pattern. I have the following error related with std::map. I want to have a map with FactoryType as a key and unique_ptr to this factory type as a value. Currently I am facing multiple issues which origin I don't understand. Could you e...
Your typedef is slightly malformed. You need to remove type from std::string type, like this: typedef std::map<std::string, std::unique_ptr<AbstractGameObjectFactory>> FactoriesArray; Alternatively, you can use a type alias instead of a typedef: using FactoriesArray = std::map<std::string, ...
67,128,853
67,129,201
How to properly pass through pointers in parameters
int main() { char Grid[8][8] = { '~','~','~','~','~','~','~','~', '~','~','~','~','~','~','~','~', '~','~','~','~','~','~','~','~', '~','~','~','~','~','~','~','~', '~','~','~','~','~','~','~','~', '~','~','~','~','~','~','~','~', ...
You had one error, and that is every time you tried to pass Grid to the functions, you passed the 8th element of the 8th element of Grids. Simply remove the [8][8] when passing Grid to the functions and tada! Example: #include <iostream> using namespace std; void ShipPlacement(int, char[8][8]); //declaration void Show...
67,130,181
67,130,252
input vectors outside of main function c++
I am trying to get an input to a matrix by placing the whole thing as in a function outside of main (), as follows: void input_matrix(int row, int col){ std::vector<std::vector<int>> matrix; for (int m=0; m<row; m++){ for (int n=0; n<col; n++){ std::cin >> matrix[m][n]; } } return matrix; } ...
There are two errors in your code. The return type of the function input_matrix() is void which needs to be changed to vector<vector<int> > Initialize the matrix with proper space. The corrected code would look something like this: std::vector<std::vector<int> > input_matrix(int row, int col){ std::vector<std::ve...
67,130,317
67,132,997
How can I control what symbols are exported from a shared library in Bazel?
I'm learning Bazel, because I have to use it at work. I have a simple build rule that creates a library from a single file and I would like control what is exported by the linker by using a linker version file. (I'm on Linux) So I tried: cc_library ( name ="thelib", srcs = ["lib.cpp"], linkopts = ["-Wl,--ve...
First of all, shared libraries are generally declared with cc_binary in conjunction with its linkshared attribute rather than cc_library. This is counterintuitive but reflects the intention that cc_binary creates a transitive link while cc_library declares an intermediate library. (More adventurous folks may try out cc...