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
66,710,894
66,710,964
why send function return 0 in socket, but clients do have recieve the message?
void SendStr(int connfd, std::string str) { uint16_t *len = new uint16_t(str.size()); const char * lenByte = (char *)len; char *sendByte = new char[*len + 2]{0}; memcpy(sendByte,lenByte,sizeof(*len)); memcpy(sendByte + 2, str.c_str(), *len); std::cout << "str size " << *len << std::endl; //s...
What you see is wrong. In this statement if (nsend = (write(connfd, sendByte + nsend, nleft)) < 0) The comparision result of (write(connfd, sendByte + nsend, nleft)) < 0 is assingned to nsend. This will become 1 if the condition is true and 0 if the condition is false. It seems you are misunderstanding this co...
66,711,892
66,712,222
Does the derived class method override the base class version of the method in case the CRTP is used?
A couple days ago I found an interesting C++ construct named Curiously Recurring Template Pattern (usually known under abbreviation CRTP). From that time I have been attempting to fully understand how does this trick work. Let's say I have following code snippet #include <iostream> template<class T> struct GraphicalOb...
You're not doing anything polymorphically in main which would demonstrate the features of CRTP. Try this instead and see what happens: template <typename T> void drawObject(GraphicalObject<T>& obj) { obj.draw(); } int main() { Square s; Circle c; s.draw(); c.draw(); drawObject(s); // wha...
66,711,896
66,711,958
Why do i have to reference in this situation?
int main(){ while(true){ char input = getchar(); int x, y; POINT xypos; if (input == 'S' || input == 's'){ std::cout <<"enter new position" << std::endl; std::cin >> x >> y; SetCursorPos(x, y); } else if (input == 'g' || input == 'G'){ GetCursorPos(&xypos); ...
You probably mean why GetCursorPos(from the WinAPI) doesn't just return the position instead of taking a pointer and filling that right? That's how the WinAPI works, almost all functions return BOOL to indicate success or failure and take information they populate by pointer.
66,712,128
66,712,931
How to use Visual Studio with CMake AND preserve file structure
I use CMake to create C++ projects. Then I would like to use Visual Studio as my IDE. But the issue I face is that I can't get files to be structured properly. Here is the problem: Let's assume I have the following file structure on the disk. And here is my CMakeLists.txt: cmake_minimum_required(VERSION 3.20) set(sour...
Simply use the Open Folder option in visual studio. This will open the directory and automatically configure the project using CMake. It will display the tree independently from the CMake configuration structure. Microsoft has a page CMake projects in Visual Studio, that explains how to properly import CMake projects i...
66,712,160
66,712,414
Why does C++ not know to do an implicit move in the return when the variable is used in an initializer list?
Consider this code: #include <iostream> template<typename A> struct S{ S(const A& a){ std::cout << "L\n"; } S(A&& a){ std::cout << "R\n"; } }; S<int> f1(){ int a = 1; return {a}; } S<int> f2(){ int a = 1; return a; } S<int> f3(){ int a = 1; return {std::move(a)}; ...
The nice thing about: return name; Is that it's a simple case to reason about: you're obviously returning just an object, by name, there's no other shenanigans going on here at all. And yet, this specific case, has led to patch after patch after patch after patch. So, maybe not so simple after all. Once we throw in an...
66,712,532
66,713,551
How to create function whose type depends on a number of varidic arguments
My goal is to construct a function that would transform an array into n-dimensional vector given dimensions as variadic arguments. For example for two dimensions. template<T> vector<vector<T>> from_array(T *array, size_t d1, size_t d2) { auto v = vector<vector<T>(); v.reserve(d2); for (n = 0; n < d2; n++) {...
It's fairly straight-forward if you don't mind reversing the order of the size arguments (so the outer-most dimension is the first argument rather than the last): template <class T> auto from_array(const T*array, size_t d0) { return std::vector<T>(array, array + d0); } template <class T, class... Sizes> auto from_ar...
66,712,618
66,712,814
why does BluetoothSetLocalServiceInfo throw error 1314?
I have being trying to build a BT application. I would like to use BluetoothSetLocalServiceInfo but I get an error 1314 (A required privilege is not held by the client). I use the echo bluetooth example from windows driver. That's my modified code: DEFINE_GUID(BTHECHOSAMPLE_SVC_GUID, 0xc07508f2, 0xb970, 0x43ca, 0xb5, 0...
Error 1314 is ERROR_PRIVILEGE_NOT_HELD. Per the BluetoothSetLocalServiceInfo() documentation: The BluetoothSetLocalServiceInfo function returns the following values: ... STATUS_PRIVILEGE_NOT_HELD The caller does not have the required privileges. See the Remarks section for information about how to elevate privileges. ...
66,713,239
66,713,456
Return value optimization for string_view inside shared_ptr
It's hard to put into words so I will directly jump into a semi-pseudo-code. I have a download function (http GET), that is being called many many times inside my main code. std::string download_data(){ std::shared_ptr<HttpResponse> response = some_http_client->send_request("some_link"); return std::string(resp...
Your code will use RVO. It returns a temporary of the same type as the function returns, which is one of the cases where RVO is mandatory. Of course, it will still require one copy of the data, as part of the string constructor that accepts a string_view as an argument. You cannot just pass the string_view on its own....
66,713,386
66,713,631
Templating lambda inside a map
I'm trying to create a templated method that takes in an array and a lambda as a transformation function. I want the API to look as follow: template <class T, class R> void sort(std::vector<T>& array, std::function<R(const T&)> key); // I want to call it sort<SOME_CLASS,RETURN_TYPE>(some_array, [] (const SOME_CLASS& v...
Usually in C++ you write template in more generic approach, for example std::function is usable when you have regular function that needs to accept a functor, template can use pretty much any functor (if it would bind of course): template<typename Container,typename Functor> void sort( Container &c, Functor f ) { s...
66,713,516
67,028,560
'<' unable to resolve function overload and Parameters mismatch in Class template, Visual Studio compiler
The error pointed out was at the end just before the }; I don't even see any function overloading or any mismatching parameters. This is simply a queue data structure that I was trying to implement. But unfortunately, I got these compiler errors. I am sharing the whole code so that easily one can help, since neither I...
The answer is, there were issues, like some of the variables were not even initialized but they were being used, and the memory calculation errors were there. Like a pointer pointing somewhere in memory that actually does not exist.
66,713,945
66,714,036
Multi File Codes for Arduino for Visual Studio Code
I'm using VS Code with an Arduino Mega and I'm trying to figure out the best way to implement a multi-file workflow. So far I have been able to incorporate a header file, however I'm not sure how to get the extension to include the other .cpp files into the build. Current folder structure: -Workspace ---main -----main....
Plain and simple by using the free platformio plugin for vs code. The best solution I found for working with arduino. This plugin is reliable, platform independent, open source and you can manage projects with header files and the linking and compiling is done by dialogue. Also the documentation is well written. I hope...
66,714,693
66,714,819
How to call multiple functions when QTimer expires?
I want to be able to call multiple functions/ methods when a timer timeouts, without creating a new slot method that calls the desired methods (see code). int foo; int bar; // … private slots: inline void foo_func() { /*…*/ } inline void bar_func() { /*…*/ } inline void combination_of_multiple_func() ...
First, you should use Qt's new signal and slot syntax if you can. I can think of 2 ways I would solve this problem: Use a lambda if (foo == bar) { // Schedule … every foo or bar milliseconds QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [] { foo_func(); bar_func(); } ); timer-...
66,714,707
66,878,783
VS2019 popen not using environment variables
I'm trying to make a sort of eval command in my VS project and I've come across an error. This is my code: #include <iostream> #include <stdexcept> #include <stdio.h> #include <string> #include <fstream> using string = std::string; string eval(string cmd) { std::ofstream ree; ree.open("WRITEFILE.cpp", std::ofs...
You can inspect the PATH environment variable by clicking properties on your project then Debugging -> Environment then Edit and type $(Path) in the top window of the popup. Visual Studio 2019 will show the value of the PATH environment being sent to application when it will be debugged in the Visual Studio Community ...
66,714,926
66,715,223
Different behaviors in strringstream given std::hex, uint8_t vs int
I suppose the fact that uint8_t is really just an alias for char means that when the characters in the stringstream get read back in, they are stored natively, i.e. the ascii code for the character, whereas if the char is input to an int, with std::hex specified, it gets read in as a hex digit converted to base 10. Thi...
There are operator>> overloads for char, signed char and unsigned char, which all read a single character from the stream. A uint8_t argument selects the unsigned char overload as the best match, reading F as a character (ASCII code 70 or 0x46). To match an integer extraction operator>> overload, use an argument of typ...
66,715,049
66,715,084
printf returning line length at end of line
Every time I print out a printf statement, the length of the line is tacked on to the end. For example: cout << printf("%s", "foo") << endl; cout << printf("%s", "foobar") << endl; shows in my console: foo3 foobar6 An interesting bug, anyone know what it is? I'm using MinGW g++ as my compiler.
The statement cout << printf("%s", "foo") << endl; is equivalent to int res = printf("%s", "foo"); cout << res << endl; The printf function prints the string, and returns the number of characters it printed. Then cout << ... prints that integer value and the newline.
66,716,380
66,716,556
Is polling events compulsory for an OpenGL SDL 2.0 application?
I ran into this issue, recently, where I created an OpenGL ES 2.0 context, with SDL 2.0 and I realized that OpenGL does not render anything if SDL_PollEvent is not called, after a draw call. Here is my code: // After creating a valid OpenGL context // Compiling & linking shaders, and using program... float vertices[9...
I want to know what is happening under the hood, that is causing this behaviour!? Whenever a process fails to call back into one of the SDL event processing functions (SDL_PollEvent()/SDL_WaitEvent()/SDL_PumpEvents()) in a timely manner the OS/windowing system will generally consider the process frozen and stop showi...
66,716,696
66,728,102
Xerces-C++ XMLString::patternMatch() not functioning correctly
I'm trying to find a way to match strings in C++ against XML Schema regular expressions. The XML Schema regex grammar is not supported by std::regex so I installed the Xerces-C++ XML library to use its pattern matching functionality. Unfortunately even with a basic example, it doesn't seem to work right. #include <iost...
Okay so I wasn't able to get the Xerces regular expressions to work, and the documentation was nothing short of abysmal, so I decided to try out another library. libxml2 has XML regular expressions and although the documentation for the regex feature was similarly abysmal, I was able to get a working program. #include ...
66,716,898
66,717,475
how to append a buffer[] to a vector<> and then copy it to a jbytearray?
This does a sane_read (with SANE) and converts to a java application. expected_bytes might not be 100% accurate, hence the use of a vector<>. Something is wrong because the resulting image is wrong. It works if I use env->SetByteArrayRegion directly. So, the error is on the vector<> context. What am I doing wrong? ...
The first problem is that you've declared data as a vector of SANE_Byte* (i.e. pointers) rather than a vector SANE_Byte (raw characters). When you call SetByteArrayRegion(), you want to be passing in a pointer to character data, but you're actually passing in a pointer to an array of pointers; those will not yield the...
66,717,200
66,742,097
How to call StretchBlt by pressing a button? Program is not loading
case ID_BUTTON2: { StretchBlt(hdc, 100, rect.bottom, rect.right, -rect.bottom, hmem, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY); // mirror vertically break; } When I call it this way or try to release DC first, program is just not running. Just not a pro of handling memory alloc if this is a pr...
You need to handle the button press in WM_COMMAND. Here is some code you can refer to: case WM_PAINT: hdc = BeginPaint(hwnd, &ps); // Get DC handle GetClientRect(hwnd, &rect); // Get client rectangle hmem = CreateCompatibleDC(hdc); hbmp = (HBITMAP)LoadImage(0, L"\\image.bmp", IMAGE_BITMAP, 0, 0, LR_LOA...
66,717,296
66,717,581
Copy constructor memory leaks
I am trying to learn the basics of writing my custom constructors but I cannot figure out what I'm doing wrong. I know that for my purposes it would be enough to let the compiler do its' job, but I'm curious how I could fix my definitions. #include <iostream> #include <stdexcept> class Matrix { public: Matri...
The basic problem is that you are not copying the data after you've allocated the memory in the copy constructor. Matrix::Matrix(const Matrix& m) : rows_(m.rows_), cols_(m.cols_) { data_ = new double[rows_ * cols_]; data_ = m.data_; // <-- This is wrong } The line with the // <-- This is wrong comment not on...
66,717,620
66,718,091
(C++) String to Double converter is inaccurate and totally wrong with negative numbers. What am i doing wrong?
Our teacher gave us this exercise: "Given a string like '-5,14' write a function that returns the float value of -5,14 I used double here just to test the precision, but it also didn't work with floats. [also i'm from Europe, we use the comma instead of the dot. Oh also we aren't allowed to use the type string and bool...
use j = 1 to start your second for loop. You are trying to raise 10 to the power of -0 j = 1; for (i = (CommaIndex + 1); str[i] != EOS; ++i) { Result += (str[i] - ascii_to_int) * (std::pow(10, -j)); ++j; }
66,717,719
66,720,370
What is the equivalent of placement new in Ada?
I'm trying to learn Ada by writing a set of procedures for managing a dynamic array but I have no idea how to go about it. In C++ I can easily put arbitrary objects in memory like so: #include <new> #include <iostream> class object { private: int value; public: ~object() noexcept { std::cout << "<> "; } ...
In Ada you can write a custom "storage pool" (or subpool) where you redefine an Allocate function to use your buffer. Then you "bind" the access type to your storage pool object. with System.Storage_Pools; with System.Storage_Elements; procedure Main is type My_Storage_Pool is new System.Storage_Pools.Root_Storage_...
66,717,960
66,717,984
why doesn't the getline() terminate when I input a newline?
I have this code: string sentence2; while(getline(cin, sentence2)){ // while there are lines coming in cout << sentence2 << endl; } on VSCode, I put my final input as an empty line by pressing "Enter" key. The code returned an empty line. Why doesn't the loop terminate instead?
You can add a condition to check that the line is not empty: string sentence2; while(getline(cin, sentence2) && not sentence2.empty()){ // while there are lines coming in cout << sentence2 << endl; } std::getline returns a reference to cin and cin will be in a failed state if it wasn't able to read anything - ...
66,718,213
66,718,279
Forks and Pipes in c++
I am using 4 processes in which A's output will goto A1 and A1's output will go to A2 and A2 output will come out in the console. Even A1 output also will comeout in console. 1st program - A C++ program which is a random generator that will generate the output as per the requirements of A1's input and also act as a co...
When you launch A1, you are closing A1toA2[1] and then after that trying to dup it into stdout. Do all of the dups first, and then close what you don't need.
66,718,222
66,718,591
Is Unreal Engine 4 C++ managed or unmanaged?
Unreal Engine 4 controls some runtime aspects of the application, such as having its own Garbage Collector and a unique metadata ("reflection") system. The question is: is it correct to say UE4 makes the C++ code "managed" in the context of "managed" and "unmanaged" languages (as in C# is a managed language and C++ is ...
If by "managed" you mean "managed memory" meaning "garbage collected" then C++ allows you to opt-in to that if you so wish, but by default it does not offer such a thing. C#, like Java and many others, forces garbage collection on you, there is no way around it. In C++ you can use things like std::shared_ptr to wrap ar...
66,718,387
66,718,516
What's the time complexity of std::string::contains in C++23?
The cppreference says std::string::contains is coming out, https://en.cppreference.com/w/cpp/string/basic_string/contains but there is no runtime requirement. Is it guaranteed to run in linear time? (say, using KMP algorithm in implementation) or quadratic time? I've tried to find it in the current C++ standard draft (...
Going by the most recent draft, contains is: Equivalent to: return basic_string_view<charT, traits>(data(), size()).contains(x); With the string_view function being: Equivalent to: return find(x) != npos; Since equality testing an integer with basic_string_view::npos is a constant-time operation, the time complexi...
66,718,982
66,719,836
Preorder Traversal (Binary Tree) - Iterative Method
I am implementing Preorder Traversal of Binary Tree (without recursion). The following code runs into an infinite loop. I cannot understand what's happening void Tree::n_preorder() { Node* temp; stack s; cout<<"\nPreorder: "; while(1) { s.push(root); while(1) { ...
The outer loop is never exited: its while condition is always true, and it has no break. The only break you have will break out of the inner loop, but not the outer one. You should not need nested loops to do this. And when you have just one loop, it makes no sense to break out of it without putting the left child on t...
66,719,092
66,719,150
C++ class or namespace?
I am a beginner in programing in c++ and I can't really imagine how to make an Object Oriented Design. Every time I apply classes, inheritance, polymorphism or function overloading, the code I make gets really messy and hard to keep track of things. I always think that "maybe I'm making too many things for the computer...
Usually when implementing a struct inside a class or writing a nested class (a class within a class) you want to achieve a principle called encapsulation, where you want that struct or class hidden or inaccessible by the user. Now to why we put or functions inside of a class or a struct conforms with the object oriente...
66,719,200
66,719,226
Insert() in uint8_t array
I am new to C++, when I try to insert an element in the uint8_t array, I get the following error. Please help me in solving this. Error main.cpp: In function ‘int main()’: main.cpp:10:9: error: request for member ‘insert’ in ‘array’, which is of non-class type ‘uint8_t [5] {aka unsigned char [5]}’ array.insert(1,0x...
That's not something you can insert on, primitive types like uint8_t don't have functions. That's what "non-class type" means. You need std::vector<uint8_t> which does have insert(). It's from #include <vector> One thing to keep in mind is C++ has a quick and easy iterator method you can use if you don't care about the...
66,719,237
66,719,447
is there range map in c++?
in c++, unordered_map and map are good tools to search key from a map. i can build a map, which a key is date and value is double (or my self-defined struct). but i want a range map, which means the key is a range, for example: #inlcude <map> m[20190101] =3; m[20201201] = 4. cout << m[20200101]; // i want this can retu...
std::map stores the data in a binary tree, so you can easily find the closest key greater than/greater than or equal to a value with the upper_bound and lower_bound methods m.lower_bound(k): returns an iterator pointing to the first element with key not less than k, or m.end() if such an element is not found. m.upper...
66,719,426
66,719,542
Why (if that is the case) does the standard say that copying uninitialized memory with memcpy is UB?
When a class member cannot have a sensible meaning at the moment of construction, I don't initialize it. Obviously that only applies to POD types, you cannot NOT initialize an object with constructors. The advantage of that, apart from saving CPU cycles initializing something to a value that has no meaning, is that I c...
Is moving an object with an uninitialized, trivially copyable member indeed defined as UB by the standard? Depends on the type of the member. Standard says: [basic.indet] When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization...
66,719,602
66,723,431
Undefined behavior of constexpr static cast from int to unscoped enum with non-fixed underlying type compiles in C++17
This is a follow up question of Undefined behavior of constexpr static cast from int to scoped enum with non-fixed underlying type compiles in C++17 (same question for scoped enumerations). TLDR is that scoped enums always have a fixed underlying type (by default int, hence you can always cast from int to scoped enum)....
It should not compile. It's a compiler bug. The reason it was made undefined in CWG 1766 was so that this conversion would be diagnosed in constant expressions. This is GCC bug #95701. I could not find an open bug for Clang.
66,719,638
66,719,662
std::array template function
I have a simple function to shuffle elements in an std::array template <typename T, uint size> void Shuffle(std::array<T, size> &arr) { for (uint i = 0; i < arr.size() - 1; i++) { std::swap(arr[i], arr[Random(i, arr.size())]); } } make/g++ doesn't like the way I'm declaring this, giving the error "...
uint doesn't match the type of the 2nd template parameter of std::array, which is std::size_t. This causes template argument deduction failing when calling Shuffle, unless you specify template arguments explicitly. You should declare the 2nd template parameter with type std::size_t. e.g. template <typename T, std::size...
66,719,654
66,730,882
How to get JavaScript stack trace from C++ call
I have written a C++ module which I am calling from JavaScript. In the C++ module is it possible to get the stack trace that identifies the following from the JavaScript call: JavaScript file name Function name (if call I made from a function) Line number of call in file. I know I can make calls from JavaScript befo...
Looks like this is the update: https://doc.qt.io/qt-5/qjsengine.html#script-exceptions
66,720,404
66,730,503
C++ Access "parents" class members
I'm new into learning C++. And what I've learned is that using global var is not a good practise. And I don't wanna use static var, since they behave like "global" var as well, if I'm correct. In the code below I want class B to get access to its "parents" member, is that possible?(see class B constructor) Or how shoul...
Using pointer to >>this<< keyword when creating a "child" class worked for me. class A { public: int nr; A(); }; class B { public: B(A* classA) { std::cout << "Written in class B, value from class A: "<< classA->nr; }; }; A::A() { nr = 77; B* classB = new B(this); delete classB; } ...
66,720,589
66,720,633
Any tipps on writing a copy constructor when copying a member from a third party module is denied?
I am currently writing some code that shall read data from an xml file. To this end I use the pugixml module that offes a class xml_document providing methods to parse the file. To store this data I have created a class tXmlDoc that manages loading operations (like setting path, storing the parse result and so forth). ...
Is it possible to copy it manually: I found this question on the subject xml_document copy; copy.reset(doc); Another option if you do not want to really copy it is to keep a shared_ptr to a const version of the xml-root.
66,720,598
66,725,611
Why does this solution works in JavaScript but takes too long in C++? (Dynamic Programming)
This is what my canSum function needs to do: Given a target sum x, return true iff it is possible to get that sum by adding elements from a given array, assuming array elements can be used any number of times. Examples: canSum(7, {2,3}) -> true canSum(7, {2,4}) -> false Below is the JavaScript code which I rewrote in ...
A difference between your JavaScript and C++ code samples is: the C++ function has just two parameters instead of 3, the map object being managed as a global entity. In some sense, having just 2 parameters is “The Right Thing”. The unordered map is about some internal necessity of the algorithm. Why should user code ha...
66,720,917
66,721,236
Kickstart 2020 RoundG Problem A Runtime Error
I am trying to solve the problem "Kick Start" from round G from last year. In short you need to count the number of appearances of the substring "KICK....START" with any number of characters in between the two words. The input is a string with only capital letters. I wrote some code and the sample works fine. But after...
text.size() is of type std::size_t, which is an unsigned type. If the length of the text is less than 4, text.size() - 4 wraps around and becomes a huge positive number. Replace the comparison with i + 4 < text.size().
66,720,937
66,721,081
Should I use sorting algorithms like bubble sort, insertion sort or should I use the inbuilt sort() function in c++ to sort arrays?
Should I use sorting algorithms like bubble sort, insertion sort or should I use the inbuilt sort() function in c++ to sort arrays? And if I should use sort() function, why do I need to learn other sorting algorithms? I'm not understanding what is the use of such algorithms if there is an inbuilt sort function, do they...
Should I use sorting algorithms like bubble sort, insertion sort or should I use the inbuilt sort() function in c++ to sort arrays? It is your wish. You can use anything. But you need to understand the importance of time and space complexity, your requirement before using any code. And if I should use sort() functi...
66,720,962
66,721,025
Is there any alternative for auto &c in c++
I am a beginner and new to this platform. I am trying to run a program to test a valid password with uppercase, lowercase letters and at least one number. Part of the program is... bool hasUpperCase(const string password) { for (auto &c : password) { if (isupper(c)) return true; } re...
You're using an outdated (version of your) compiler, this compiler acknowledges breaking changes coming in C++11 which was standardized 10 years(!) ago. Every modern compiler compiles at least with C++11 as base which would remove this error. The easy and only good solution is to update your compiler, if you for some r...
66,720,963
66,721,043
How can i get template's type if my instance is stl map?
I want a get_value template function. please see the following code: template<typename T> (something i want) get_value(const T& m, int key) { auto it = m.upper_bound(key); return it == m.begin() ? (*it).second : (*--it).second; // please notice here, // if my instance is map<int, map<string, int>> the return typ...
The "second type" in a std::map<K,V> is called std::map<K,V>::mapped_type. However, you can use auto to let the compiler deduce that for you: template<typename T> auto get_value(const T& m, int key) { auto it = m.upper_bound(key); return it == m.begin() ? (*it).second : (*--it).second; // please notice here, } or...
66,721,219
66,726,177
Dynamic programming - canSum memoization in C++
The objective is to return true if the sum can be made by adding up elements from a given vector. The vector elements maybe used and reused in any order. Example: sum = 7, list = [4,5] return false because you can't use these list elements to make 7 sum = 9 or 5 or 20 or 8, list = [4,5] return true because 9 = 4+5, 5 i...
The problem in your code is the way you handle the storing of sates in your memo table. You store only when the result is desired in the for loop and same problem is while returning using the memo table. So, the states which result in false are not stored in your memo until the complete recursive call ends and you are ...
66,721,805
66,721,859
asio async_receive how to get sender ip address
I wrote a small protocol stack to connect to KNX/IP routers. The mechanism is as follows: Discovery_Channel: For discovery the client sends out an UDP/IP packet to multicast address 224.0.23.12. KNX/IP routers listen to this multicast address and reply. The KNX/IP router can potentially be connected to multiple KNX me...
On datagram sockets you can (should, likely) use async_receive_from. It takes a reference to an endpoint variable that will be set to the remote endpoint on success.
66,721,814
66,721,863
Using Malloc to allocate memory to STL list?
I am trying to allocate memory to stl list using malloc. I works fine with new as below: typedef pair<int, int> iPair; list< pair<int, int> > *adj; adj = new list<iPair> [V]; But throws segmentation fault if I use malloc instead of new. adj=(list<iPair> *)malloc(sizeof(list<iPair>)*V); Why malloc cannot be used to al...
Because malloc comes from C and C has no idea of classes and thus no concept of constructors. new allocates the memory and calls the appropriate constructor, malloc only allocates the memory.
66,721,894
66,722,222
Generic function that compares sequences
Write generic function that compares two sequences of same number of elements.Function returns true if all elements are same (a[0]=b[0] , a[1]=b[1] ...) and if are not it returns false.Fucntion takes 3 parameters begin iterators from both sequences and end iterator from first sequnce. !! Iterators that operate on seque...
#include<iostream> #include<vector> #include<list> #include<iterator> using namespace std; template <typename S> bool jednako(typename vector<S>::const_iterator pocetak1,typename vector<S>::const_iterator kraj,typename vector<S>::const_iterator pocetak2){ for(auto i = pocetak1;i!=kraj;i++){ if(*pocetak1 !=...
66,722,058
66,722,160
Diffrence between real and double
double real2double(real* r) //This function job is to transform real objects to double { double n = r->num; double frac = r->frac; //Saving the number while (frac > 1) //Saving the fraction frac =frac/10; n =n+frac; return n; } I found this function to convert real to double in C++ I'm quit...
In your code real appears to be a class type. From the usage in the function we can conclude that it has members frac and num of some type that either is double or can be converted to double. The members are accessible in the function which implies they are either public or the function is a friend of the class. Making...
66,722,089
66,722,361
what is the best practice of get value from a map?
i am a little confused with function return, my purpose is to avoid copying as much as possible. i read some doc, which tolds me dont use reference as map's value. but in the following code, i am puzzled. struct BigCls { // this struct has a expensive constructor BigCls(...); }; // solution 1 void create_function(...
std::map<Key,T,Compare,Allocator>::at T& at( const Key& key ); (1) (since C++11) const T& at( const Key& key) const; (2) (since C++11) Returns a reference to the mapped value of the element with key equivalent to key. If no such element exists, an exception of type std::out_of_range is thrown. (cppreference) std::map...
66,722,093
66,722,247
No viable overloaded '-=' after redefining operators
I'm trying to define "-=" and "-" for a class that represents vector in 2D but I get this error: Vecteur2D.cc:131:7: error: no viable overloaded '-=' vec1-=vec2; Vecteur2D.cc:81:23: note: candidate function not viable: 'this' argument has type 'const Vecteur2D', but method is not marked const Vecteur2D& Vecteur2D::...
You cannot call a non-const method on a const instance. Your operator-= looks ok, but if you try to call it eg like this: const Vecteur2D x,y; x -= y; // error You get an error similar to the one you report. -= is expected to modify the left operand and your operator-= does that. The left operand cannot ...
66,722,709
66,723,129
How to get and set environment variable from mingw, c++ (or c)
I am writing a program that needs to set environment variables for the current process from mingw (to be available for subprocesses when using system(...)-call). I know how to do in linux, and windows with msvc and clang. However, I cannot find any goood examples on how to do it with mingw-g++. How do I implement funct...
With inspirations from the comments i found this question on putenv and managed to whip together this prototype application: #include <cstdlib> // For system(...) #ifdef __MINGW32__ extern int putenv(char *); // Not defined by mingw #endif int main() { putenv(const_cast<char *>("x=10")); system("set"); // Ou...
66,722,947
66,723,089
C++ 17 How to specialize static function template in class template
How to do this in G++? Declare a class template ss. [ok] Decalre a static function template f [ok] How to specialize f ? [error] This code is ok for VC++. #include<iostream> #include<utility> #include<typeinfo> template<typename T> struct ss { template<typename F> static constexpr ...
This is GCC's issue. According to CWG 727, explicit specialization should be allowed in any scope, including in class scope. An explicit specialization may be declared in any scope in which the corresponding primary template may be defined (N4868.9.8.2.3 [namespace.memdef], 11.4 [class.mem], 13.7.3 [temp.mem]). To ma...
66,723,003
66,728,554
How to return a pointer to the parent node of children[poz] in the following code?
I am trying to find a specific RGB point in an octree ( after I have inserted it already) and I want this function to return a pointer to that node's parent or a list with the node and its brothers. How can I change this code to get that? Also when an empty node is encountered I tried returning nullptr or NULL and I ge...
The error message is a clue. Your method is returning a vector, so you can't return a pointer. You can either change the return type of your method or create and return an empty vector. Without knowing the structure of your data, I don't have an absolute answer for how to return the parent, but you could either retain ...
66,723,206
66,736,829
OpenCV setting resolution results failing in reading frames
I've tried to change the resolution on raspicam v2 with my raspberry pi 4 b, but this code gives me false every time I try to read frame... Is there anything I am missing? I can easily read frames without setting those parameters, but then it gives me really poor resolution. #include "opencv2/opencv.hpp" using namespac...
The problem was in raspi-config, I thought I've enabled the camera through config.txt, but I've not. so when I've got into the interfaces tab and enabled the camera, everything worked perfectly. Thank you guys for help :)
66,723,254
66,723,348
Problems sorting an array of std::reference_wrapper, referencing vectors
I am a bit stuck on this, I'm using a std::array to store reference wrappers to vectors. I was trying to sort these by the vector's size using std::sort but am unable for reasons I am not quite sure of, even after reading the compiler errors. Will I have to use another sort function because it appears that std::sort im...
It's because you are using std::cbegin (const begin) and std::cend (const end) in std::sort. It means, that you can't change the order of your array! Just replace it with std::begin and std::end like this: std::sort(std::begin(vecRefs), std::end(vecRefs), [](const auto vecA, const auto vecB) -> bool { return ve...
66,723,453
66,723,542
Why does my boost::circular_buffer crash when accessed using an iterator?
In the following program, when I access elements from the front of the circular buffer using *(begin_iterator + index) I get a crash. But if I access the same elements using buffer[index], the crash is eliminated. (See the two commented lines below). Why does this happen? #include <boost/circular_buffer.hpp> #include <...
You're experiencing undefined behavior because you're reading and modifying the same object unsynchronized from multiple threads. Coding it one way or another might eliminate the crash, but the program is still wrong. If we add a mutex, then there's no crash anymore: #include <boost/circular_buffer.hpp> #include <threa...
66,723,575
66,723,675
Calling a Function with integer [[mayb_unused]] macro and default argument boolean type parameter
I am writing a Function with 2 Parameters, 1st is integer type marked [[maybe_unused]] and 2nd is Boolean Type with Default Argument false. int preOrderTraversial([[maybe_unused]] int searchData, bool forDisplay = false) This is the function declaration. The function is used for pre-order Traversal in Binary Search Tr...
[[maybe_unused]] means that the function body may not use it, but the signature of the function always have it. Actually event the default value for the boolean does not modify the signature of your function; Thus your function always take 2 arguments, the first being a integer, and the second being a boolean (that may...
66,723,585
66,723,670
what happens if I initialize a virtual function other than 0? will it create a pure virtual function or what else happens in memory?
I have created a definition for virtual function and initialized it with (=1) and when I compiled a project it get complied successfully. And because it get compiled successfully I wanted to know what actually happened. does it create a pure virtual function or anything else got happened.
There is no such thing as initializing a virtual function to a value. The grammar = 0 is a pure-specifier, not an initializer. It is special grammar that is given special meaning; it designates that the virtual function is a pure-virtual function and must be implemented by any classes inheriting from it. = 1 following ...
66,723,646
66,723,858
Priority queue lambda comparator and normal comparator
#include <iostream> #include <queue> #include <vector> #include <array> using namespace std; auto cmp2(const array<int, 2>& a, const array<int, 2>& b) { return a[0]+a[1] > b[0]+b[1]; } int main() { auto cmp = [] (const array<int, 2>& a, const array<int, 2>& b) { return a[0]+a[1] > b[0]+b[1]; }; ...
cmp is a lambda. It's an object with a () operator. But cmp2() is a function. You can't use a function as a callable type, but you can use a function pointer as a callable type, in that case you must use decltype(&cmp) to get a function pointer type: priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(&cm...
66,723,758
66,724,468
Store threads inside of a vector in C++
I'm learning parallel programming and there is an example in my lecture for it. We have an array for storing 20 fibonacci numbers and basically, for computing each of them, a thread is created. This is the code for the fibonacci function: unsigned int fibonacci(unsigned int n) { if(n==0) return 0; unsi...
Your issue is scope (there are other problems): for(auto i=0u; i < 20; i++) { // This value is reinitialized every loop. // Though it is likely that every loop will use the same // physical memory location for f this is not guaranteed by // the standard (especially if the loop is unrolled) auto f = ...
66,724,269
68,022,139
QML map - TLS initialization failed ERROR
I am currently creating an application that will be able to display maps. Before I add more advanced features, I would like to simply display a map of a certain area in the application. For this I used a bit of modified code from the Qt example "Minimal map". Code in map.qml file: import QtQuick 2.0 import QtLocation 5...
If your OS is windows you should install OpenSSL. and also you are using the osm plugin so you should be connected to the internet when Running the application. your code in my system Runs like this :
66,724,621
66,725,027
Deleting node in linked list causes output of seemingly random nubmers
I am trying to delete a node from a linked list using this function: void del_node(int del_data) { node* temp = NULL; node* trail = NULL; node* del_ptr = NULL; temp = head; trail = head; while (temp != NULL && temp->data != del_data) { trail = tem...
I'll comment on your code inline: void del_node(int del_data) { node* temp = NULL; node* trail = NULL; node* del_ptr = NULL; temp = head; trail = head; // This is fine, but recommend you use nullptr instead of NULL. // This will find the first instance of data matches del_data, // But i...
66,724,696
66,724,885
c++ Import two functions with the same name and parameters from different files
Let's suppose I have a function named the same and with the same parameters in two different files that I want to import to my main. void foo(int a) { // Some code, this function in file A } void foo(int a) { // Some code, this function in file B } How can I do it? If it is possible, how could the compiler di...
The simplest way is to use namespaces: filea.hpp namespace a { inline void foo(int a) { // Some code, this function in file A } } fileb.hpp namespace b { inline void foo(int a) { // Some code, this function in file A } } main.cpp #include "filea.hpp" #include "fileb.hpp" int main() { ...
66,724,891
66,724,927
Why is the second column of the square not printed in its excepted place?
sorry if the question isn't clear enough so here I am explaining more: #include <iostream> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; for (int y = 1; y <= num; ++y){ for (int x = 1; x <= num; ++x){ if (x == 1 || x == num || y == 1 || y == nu...
You're not printing any spaces when you're not printing asterisks. Just add printing for that case as well: if (x == 1 || x == num || y == 1 || y == num) { cout << "* "; } else { cout << " "; // to align the * to the right } Here's a demo
66,725,583
66,726,928
Variable cannot be implicitly captured in template function
I'm trying to pass a lambda to a function but I'm getting an error and I don't know how to get it fixed. Should I qualify the typename F somehow so that it knows the function must accept a single integer argument? [cquery] variable 'f' cannot be implicitly captured in a lambda with no capture-default specified Here i...
The error message says clearly that f is not captured in the lambda, so you need to do that just like you captured i. Also, your lambda doesn't have a return statement, so it returns void. That means you have an incompatible return type in foo which is declared as returning an int. Simply add a return statement inside ...
66,725,664
66,726,282
Is there a workaround for returning Null in c++ when the return type is a vector container?
The thing is that I am implementing a recursion, in which I have to use NULL value to specify that the recursion branch being traversed is invalid. But in C++ we can't return NULL when the return type is a container( vector container in my case). So is there any workaround for the problem or do I have to use some other...
You have the following options: Return result + bool Return std::pair<std::vector<int>, bool>, or even better a struct like this struct Result { std::vector<int> result; bool is_valid; }; Result howSum(int target, const std::vector<int>& in); where bool would indicate whether or not the result vector is actua...
66,725,992
66,726,094
Expanding template parameter pack to declare class members
First, I have a template class: template <typename T> class Component; Then I would like to create a class that can hold an arbitrary set of Component<T>'s as members, e.g. for N=2: template <typename T, typename U> class Aggregate { private: Component<T>* m_comp1; Component<U>* m_comp2; }; At first glance, this ...
try using a tuple: template <typename... Comps> using Aggregate = std::tuple<Component<Comps>*...>;
66,726,363
66,726,382
Perfect forwarding a value of type auto
How can we forward a function auto parameter using std::forward for the below code? void push_value(std::vector<MyType>& vec, auto&& value) { vec.emplace_back(std::forward<?>(value)); }
You want decltype(value)(value) (without forward). Some prefer to write std::forward<decltype(value)>(value), but it does exactly the same thing, the forward is superfluous.
66,726,615
66,726,817
is it possible to add extra data to a struct in boost
Hello so if i have class like this class Doors { private: friend class boost::serialization::access; template <class Ar> void serialize(Ar &ar, unsigned) { ar &username &password; } public: string username; string password }; and then i serialized the class and added it to MySql th...
Notice the second argument to serialize() which you're not using, it's the class version. You can bump the class version and optionally read the additional fields depending on the version. class Doors { private: friend class boost::serialization::access; template <class Ar> void serialize(Ar& ar, unsigned v...
66,726,618
66,932,694
Problems with QtXQuery in qt 5.12.8
I am trying to read xml tags from a document using QtXQuery. Works out fine besides a '\n'-char that is attached to each query-result. Moreover using the last()-statement on a collection returns the expected number of items in the collection with a trailing repetition + '\n'. Why QXmlQuery seem to add a ` \n` to result...
Solved this with a workaround: results=results.remove('\n'); results=results.split(' ')[0]; not really nice, but it works...
66,726,845
66,729,180
Which order should allocated memory blocks be freed in?
Given something like: char *a = malloc(m); char *b = malloc(n); char *c = malloc(o); Once you have finished with the blocks of memory, this is correct: free(a); free(b); free(c); And so is this: free(c); free(b); free(a); Yet one or other order must be used, and it is more satisfying to have a basis for choosing one...
This is a low-level detail, subject to change when your build environment upgrades. As such, I would look to general principles instead of specific implementations. In this case, I would add a hypothesis to the general principles. Hypothesis: If the order of freeing memory makes a difference for performance, the build ...
66,726,924
66,727,399
Error while compiling when using list in C++
I get this strange error when I used the explicit declaration { "C++", "C", "PHP" } of the list : [main.cpp 2021-03-20 22:02:08.850] ,,main.cpp: In function `int main()': main.cpp:22: error: syntax error before `{' token Here is the code : #include <iostream> #include <list> using std::list; using std::string; class...
It's compiling fine. Check the name of the file and the folder, cause the code doesn't have 22 lines. $ g++ -g -o name name.cpp $ g++ --version g++ (GCC) 10.2.0 Copyright (C) 2020 Free Software Foundation, Inc.
66,727,027
66,727,829
How to correctly 'install' wxWidgets on a Mac
I have been trying for a while to get the wxWidgets library working on my Mac, but I have been having tons of issues. I have tried both downloading the source and building it myself and using Homebrew. I have gotten to the point where I can compile the following: helloworld.hpp: #include <wx/wxprec.h> #ifndef WX_PRECOM...
@scriptor6, Get rid of homebrew install. Get rid of the one you compiled Download latest release of the library from wxwidgets.org/downloads. Unpack it somewhere. Do this cd wxwidgets-3.1.4 mkdir buildOSX cd buildOSX ../configure --enable-debug make cd samples/minimal make open minimal.app If at any point you will get...
66,727,031
66,727,093
Lookup of dependent qualified names
This program does not compile (error: 'foo' is not a member of 'N'): namespace N { // void foo(); } template<class T> void template_func(T t) { N::foo(t); } But if we uncomment the declaration of void foo();, it compiles. Demo. Both versions have an error. foo even if declared, takes no parameters. The followi...
Your analysis seems to be correct, and your code is ill-formed, no diagnostic required, regardless of whether void foo(); is commented out or not. The part of the standard you're looking for is: [temp.res.general]/6.1 The program is ill-formed, no diagnostic required, if: — no valid specialization can be generated for...
66,727,129
66,727,758
List of atomic shared pointers
I need a thread-safe list of shared pointers and I saw that in c++20 they added template specializations for the atomic shared _ptr. (std::atomic<std::shared_ptr<Delegate>>). I was thus wondering do I need to implement my own doubly-linked list or this is what I need std::list<std::atomic<std::shared_ptr<Delegate>>> fo...
A std::list<std::atomic<std::shared_ptr<Delegate>>> is a list of atomic pointers. This means the pointers have some thread safety guarantees. It is not an atomic list, nor does the list structure have any extra thread safety compared with the same structure with no std::atomic. So for example if you have two threads w...
66,727,200
66,727,374
Is there a way to connect a QSlider and a QLineEdit object to each other?
I'm trying to connect a Slider and LineEdit widget together so that when one is changed the other will match this value. I'm struggling since lineEdit takes strings and Slider takes ints. I already used setValidator on the lineEdit so that only ints can be entered. I tried using the old signals and slots syntax with no...
Use the lineEdit() method of QSpinBox(): connect(textbox, &QLineEdit::textEdited, slider->lineEdit(), &QLineEdit::setText);
66,727,414
66,730,450
Intuitive GSL stiff EDO
I need to solve an ODE that has stiff behaviour. Said ODE would be given by int odefunc (double x, const double y[], double f[], void *params) { double k=1e12; //At k=1e7 it works (doesn't show stiffness) double y_eq=-1.931+1.5*log(x)-x; f[0] = k*(exp(2*y_eq-y[0])-exp(y[0])); return GSL_SUCCESS; } I...
To manually implement an algorithmic differentiation it helps to include explicit intermediary steps int odefunc (double x, const double y[], double f[], void *params) { double k=1e12; //At k=1e7 it works (doesn't show stiffness) double y_eq=-1.931+1.5*log(x)-x; double v1 = exp(2*y_eq-y[0]); double v2 =...
66,727,795
66,727,848
How to initialize 2d array using 1d arrays in C++
I have the following code int vertical[] = {0, 1}; int horizontal[] = {1, 0}; int diag1[] = {1, 1}, diag2[] = {1, -1}; int directions[][] = {vertical, horizontal, diag1, diag2}; Which gives me the following error on line 5: Array has incomplete element type 'int []' Thus, I'm stuck doing the following: int direction...
You can use std::array #include <array> #include <iostream> int main() { std::array vertical {0, 1}; std::array horizontal {1, 0}; std::array diag1 {1, 1}, diag2 {1, -1}; std::array directions {vertical, horizontal, diag1, diag2}; for (const auto dir : directions) { for (const auto val : d...
66,727,849
66,738,007
C++ output elements of a vector not expected
I'm practicing vector and ranged for loop, my code: #include <iostream> #include <vector> using namespace std; int main(){ int size,element; cout<<"enter vector size: "; cin>>size; vector<int>v(size); for(int i=0; i<size; i++){ cout<<i<<"\t"; cin>>element; v.push_back(elemen...
vector<int>v(size); This creates a vector of having size equal to size variable. Now if you do push_back it will create a new vector and with size+1 and add the element to it. Instead inside for loop do cin>>v[i];
66,728,606
66,728,612
C++ returning an assignment?
In C++ what does it mean when a function returns an assignment? e.g. int a = ...; int b = ...; int some_function(p) { return a = b; }
In this case it performs the assignment, then returns b. This sort of stuff might get flagged by the compiler as an inadvertent bug, usually you'd mean a == b, so you may need to deal with that. Doing it as a separate line makes it clear it's intentional.
66,728,709
66,729,220
Which should be the standard implementation of static jagged arrays in C++
If i want this, somehow, continuously in memory: arrs = {{a,b}, {a,b,c}, ...} (I know the size of each array at compile time) Which is the, generally, optimal implementation. I have seen a similar question, about an specific design (they also point other solutions). However, I immediately thought of another method; so...
You clarified in the comments that you know the sizes at compile time and you are interested in non-dynamic allocation. So You can create a jagged array template type with all the matrix flattened and all the size information encoded in the type (no need to extra pointer/index storage). Implementing it is not so trivia...
66,729,533
66,729,622
Creating a struct during while loop skips over input
I'm trying to create a struct and collect its inputs from the user with a while loop, however on the second iteration it just seems to skip past the inputs. #include <iostream> #include <list> struct Student { std::string name; std::string course; float mark; }; int main() { std::list<Student> studen...
The problem here is that when you press "Enter" after your second line of input, that newline is fed to std::getline(std::cin, student.name); on the next iteration. And so students[1].name would be an empty string. To get around this, add std::cin.ignore() or std::cin.get() after reading your second line. This tells ci...
66,730,395
66,730,562
Reading strings and floats from a text file
I realize there are similar questions to this however, those solutions seem to only work if a group of data is on the same line. I have some data structured in text file like so: <string student name> <string course> <float mark> ... Every 3 lines is a new student, with a total of 6 students. My code works until it ge...
I had the requirement to get the data line by line, assuming every three lines was a new student. My next requirement was that the third line would be a float but getline() reads in as a string. My solution was to just create a temporary variable to take the string and then convert it to a float on the fly. #include <i...
66,730,592
66,730,627
Why when a character array is compared to another character array, output is wrong but when character array is compared to a string output is correct?
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish...
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing. In short, what you're really doing is: if(&s[0] == &a[0]) And those two pointers will never be equal. To compare the contents of character arrays, you need to use strcmp() or similar function instea...
66,730,771
67,534,238
How to fix Boost::Asio Client Http request error?
I'm trying to lean Boost::Asio networking library for C++ by watching this video but I stuck at making request using threads asynchronously. The code : #include "stdafx.h" #include <iostream> #include <boost/asio.hpp> #include <boost/asio/ts/buffer.hpp> #include <boost/asio/ts/internet.hpp> #include <boost/system/error...
Thanks @sehe for the answer and recommendations, it took so long but I've upgrade to New Windows10 and Visual Studio 2019, and Boost 1_76 and the problem solved! Those errors were totally irrelevant to the code!
66,730,993
66,731,280
How does this expression work? (c^0,c^32);
gets(s); for(;s[i];){ f&=(s[i++]<'a'); } for(i=0;s[i];){ putchar(s[i++]^f*32); } I don't know how s[i++]^f*32 works, I have never seen this expression before and I would like to know how it works, I know it uppercases letters if f is 1 but why is it to the 32th power and why to the 0 power it makes it lowercase
As mentioned in the first comment, ^ indeed is the XOR operator, not the power. In top of this, there are consequences for the order of the operators, as you can see here: s[i++]^f*32 // a piece of your code =(s[i++]^f)*32 // due to the order of operators, this is the same thing. What does this mean for some valu...
66,730,999
66,732,159
How can I optimize my code from O(n^2) to nlog(n)
Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value. So, the pr...
Solving this by hand, what I'd do is to take the numbers which start with the highest digits in their sequences, right? So, in other words, what I'd do by hand is to sort them by this criterion and then appending them. As soon as you are able to describe the criterion, this becomes nothing more than a sorting algorithm...
66,731,097
66,732,929
How to create an array and start its lifetime without starting the lifetime of any of its elements?
Arrays of any type are implicit-lifetime objects, and it is possible to to begin the lifetime of implicit-lifetime object, without beginning the lifetime of its subobjects. As far as I am aware, the possibility to create arrays without beginning the lifetime of their elements in a way that doesn't result in UB, was one...
The whole point of implicit object creation is that it is implicit. That is, you don't do anything to get it to happen. Once IOC occurs on a piece of memory, you may use the memory as if the object in question exists, and so long as you do that, your code works. When you get your T* back from allocator_traits<>::alloca...
66,731,113
66,731,308
How does this template function work? It checks runtime whether type conversion is possible, without using cast
/// Segédsablon típuskonverzió futás közbeni ellenőrzésere ///That translates into: Helper-template to test type conversion during runtime template <typename F, typename T> struct _Is_Types { template<typename D> static char (&f(D))[1]; template<typename D> static char (&f(...))[2]; static bool const conver...
The check is really done at compile-time. Let us analyze what each line does. template<typename D> static char (&f(D))[1]; This line declares f to be a function that takes a parameter of type D and returns a reference to a char[1]. template<typename D> static char (&f(...))[2]; This line overloads f as a function tha...
66,731,276
66,737,587
How to produce a Python dictionary from a C++ unordered map using SWIG?
I'm trying to wrap an unordered map in a python dictionary using swig: // UsingAnUnorderedMap.h #ifndef LEARNSWIG_USINGUNORDEREDMAP_H #define LEARNSWIG_USINGUNORDEREDMAP_H #include <unordered_map> #include <string> std::unordered_map<std::string, int> makeStringToIntMap(){ return std::unordered_map<std::string, ...
Here goes a small example showing conversion of std::unordered_map to a python dictionary %module dictmap %{ #include "test.h" %} %typemap(out) std::unordered_map<std::string, std::string> (PyObject* obj) %{ obj = PyDict_New(); for (const auto& n : $1) { PyObject* strA = PyUnicode_FromString(n.first.c_str())...
66,731,646
66,731,981
How to define constructor c++
I have only been working with C++ for a year now and I am hoping to gain a better understanding of abstraction with my current project. I created a Black Jack card game from my book 'Beginning C++ Through Game Programming'. The game works, but I am working on a menu option that restarts the game, adds scores and allows...
Your Menu class (before calling the constructor) wants to create a Game instance using default constructor (without parameters) but Game class don't have a default constructor (because if you create any constructor, default constructor is not created automatically). You have three options: Provide an empty constructor...
66,731,730
66,731,762
Is one-line initialization of a <set> possible with C++20 <ranges>?
I would like to know if with <ranges> in C++20 it is finally possible to select from a sequence and initialize a set in one line, as is possible in C# with IEnumerable. This would probably require converting a <ranges> object to a std::initializer_list. C#: int[] sequence = new int[] { 0,1,2,3,4 }; HashSet<int> set = n...
Actually, it is not possible for now, but in near future, we can get ranges::to which will have such functionality.
66,731,990
66,733,239
When must you pass io_context to boost::asio::spawn? (C++)
I was surprised to find that the code below works without passing io_context as the first argument to spawn. Could somebody please explain why I don't need to pass it in this case, and in what situations you must explicitly pass it. I'm using Boost 1.75.0. #include <boost/asio/spawn.hpp> #include <boost/asio/deadline_t...
Asio has added the concept of associated executors and default executors. The associated executors is not really new, because the handler_invoke protocol already allowed for handler-type specific semantics. However, since the formulation of the executor concept it became more generalized. Now you can post any handler, ...
66,732,156
66,732,190
C++ Why there is error when I delete pointer?
I have problem with visual studio ( i think so ). When i try compile it in Visual Studio i'm getting error (breakpoint). int main() { int p = 4; int d = 7; int* x = &d; cout << *x << endl; delete x; } I'm gettin error like this. Am i doing something wrong??? In code blocks it works. When i restart...
delete pointer; does not delete the pointer itself, but the data that the pointer is pointing to. In this case, that happens to be memory that's allocated on the stack when the scope of the main() function is entered, and is freed automatically when the scope of main() exits. Your program attempts to free this memory u...
66,732,193
66,732,387
Can't convert char[9] to char*
I'm new to game hacking, and started by following a tutorial which gave me the source code. Once I understood what it does, I tried to compile, and 3 identical errors came up: Can't convert char[9] to char* (Error n. C2664) The errors are referred to the variables ProcessName and ModuleName. Even if I know good funda...
The error occurred because you attempted to pass a string literal (a const char[]) to a function that expects a pointer to non-const char array (char *). Because you never modify the contents of ProcessName you should change bool AttachProcess(char *ProcessName) to // VVVVV bool AttachProcess(const cha...
66,732,235
66,732,299
Difference member initialisation between C++ and Java
Consider the following code snippets: class A { public: A() {cout << "First creation";} A(int x) {cout << "Second creation";} }; class B { A first; public: B() {first = A(2);} }; When creating a new B object, First and second creation get printed (to avoid this one uses member initialisation lists). H...
In C++ the member initializer goes before the method, AND the object A as a member is an actual object, so you have B() -> B.first - A() default ctor() initialization B() -> B() method. Has A.first=(temporary A(2) parameter ctor initialization). In C++ if you declared a private assignment operator the code would the...
66,732,242
66,732,296
c++ initializing lvalue reference with a temporary object rvalue as well as auto deduction
I perform following statements in MSVC with /std:c++17 successfully without any compile error. class A { public: A() { std::cout << "default constructor." << std::endl; } A(const A&) { std::cout << "const A&" << std::endl; } A(A&&) { std::cout << "A&&" << std::endl; } int a; }; A& a = A(); a...
If you compile with the /Wall flag, you will be given the answer by the compiler itself: warning C4239: nonstandard extension used: 'initializing': conversion from 'A' to 'A &' note: A non-const reference may only be bound to an lvalue warning C4239: nonstandard extension used: 'initializing': conversion from 'A' to '...
66,732,741
66,732,797
C++ How to resize a Pointer Array to add new values the best?
Hello people I have to create a program for class which should store Float Values in one pointer array in a class. I looked up how pointers work and l think l got it. Or maybe I didn't? because my code does weired stuff. private: float * messdaten; int mdi = 0; public: CMesswerte(){ ...
The line *(messdaten + i) = daten[i]; is wrong. The index for daten should start from 0, but here it actually starts from mdi. It should be: *(messdaten + i) = daten[i - mdi]; Another option is changing for(int i=mdi; i < mdi+size; i++) { *(messdaten +...
66,732,769
66,732,812
template specification without definition
I have the following code template <typename Signature> class Holder; template <typename I, typename O> struct Holder<O(I)> { // code here } }; ... int main() { ... Holder<int(double)> a; ... } I know that the declaration of one argument template parameter is necessary (since I'm calling ...
No, this is a valid template specialization (not "specification", that's a wrong word). The primary (non-specialized) template being declared but not defined doesn't have any special effects. You won't be able to create an instance of it (just like of a non-template struct that's not defined), but that's all.
66,732,824
66,732,900
C++ std::shared_ptr debug assertion failure
I am studying the std::share_pointer with visual studio 2019 and I wrote a program just implements swapping two integers. #include <iostream> #include <memory> void swap0(int* a, int* b) { int t = *a; *a = *b; *b = t; } void swap1(std::shared_ptr<int> a, std::shared_ptr<int> b) { int t = *a; *a = ...
Your problem is in this line, shared pointer requires that the data it uses be allocated on the heap, not the stack. This is why the constructor takes pointers not references. //... std::shared_ptr<int> pa(new int{a}); std::shared_ptr<int> pb(new int{b}); //... Note in swap1 you are swapping the ints that are containe...
66,732,877
66,732,894
How can I write into a string like I write into a char[]
For example, if I have this function: void read(std::string& s) { std::cin >> s; } and the input first sentence s will contain 'first' only. If I would've used something like: void read(char array[100]) { std::cin.get(array, 100); } for the same input, I would've got "first sentence". Is there any way to ach...
You can use std::getline(). void read(std::string& s) { std::getline(std::cin, s); }
66,733,245
66,733,340
Copying a dynamic array of structs to another dynamic array of structs
I am trying to copy the contents of a dynamic array of structs to another dynamic array of structs, but I am getting the error, 'invalid array assignment' and was hoping someone could point me in the right direction. Here is my struct: struct Agent { char name[C_STRING_SIZE]; int idNum; double years; ch...
It's easier than you think. for (int i = 0; i < numOfAgents; i++) encryptArr[i] = agentArr[i]; Each value in the array is something that meets all requirements of an "object", and can be copied/moved as a whole. No need to bother copying each member of the struct.