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
62,283,839
62,283,957
In what case std::basic_string::find with a count argument greater than the string length can be useful?
One of the signatures of std::basic_string::find method is: size_type find( const CharT* s, size_type pos, size_type count ) const; The parameters are the following: pos    - position at which to start the search count - length of substring to search for s         - pointer to a character string to search for T...
There is a false premise that you didn't spell out, but combining the title and the question it is: The null character indicates the end of a std::string. This is wrong. std::strings can contain null characters at any position. One has to be cautious with functions that expect a null-terminated c-string, but find is...
62,284,556
62,285,242
POSIX open() hangs on SMB share
I have a problem where I mount a Windows SMB share under linux with mount.cifs and write to files from my C++ program. This works fine, but as soon as network problems arise (i.e. Windows server disconnect), opening the file with POSIX open() will hang indefinitely. The same happens for the POSIX close() call if the sh...
Syscalls are interrupted when a signal arrives; errno will return EINTR. You can use alarm() before the syscall to schedule SIGALRM after a time-out period. You can also use alarm() to cancel a pending SIGARLM if the syscalls returns successfully before the time-out period expires.
62,284,562
62,288,041
PostgresSQL - SQL Prepared Statement vs String Escaping preventing SQL injection attacks
Hi I'm writing an c++ application using libpqxx to insert rows into a Postgres SQL Table and the data being written is user inputted so I need to guard against SQL injection attacks. From what I see online I can take two approaches: Prepared Statements std::string name_str = "Bob"; \\! User input unsafe!! ...
My application isn't going to keep the database connection alive therefore the prepared statement is only ever going to be used once If you are worried about performance, you should fix this single-use connection issue. And if you are not worried about performance, then why do you care if prepared statements are "ove...
62,284,565
62,284,633
Vector member is lost while managing a queue of the class pointers C++
I have a very simple class called AClass with two members: an int and a vector of ints. In my program, I'm trying to use a queue of pointers to objects of that class and a while loop on that queue until it is empty. Within that while loop, I sometimes create new objects and add them to the queue for some processing. Th...
Inside the while loop, you are adding pointers to the queue, that point to the address of a local variable. In the next iteration of the loop, that variable dies, and the pointer that you have is no longer valid. The first pointer that you add to the queue is the address of an object that lives for the duration of main...
62,284,696
62,284,882
How to convert the text of qml a textField to float and int
I tried to pass a value inserted in textField in a C++ float variable. The following code is a representation of what I need. TextField{id:textField1} Button{onClicked:function.printFloat = textField1.text.toFloat} but I received the following warning message: qrc:/qml/window/WindowConfigTelemetry.qml:215: Error: Can...
It's a bit hard with some parts of your code missing, but you can use the Javascript function parseInt and parseFloat console.log("integer: ", parseInt(textField1.text)) console.log("float: ", parseFloat(textField1.text)) See https://doc.qt.io/qt-5/qtqml-javascript-functionlist.html for more helpful functions
62,284,987
62,285,064
C++ std::thread and std::async tests are in progress, but an error occurs
I am trying to identify the difference between std::::thread and std:async through a simple experiment.(check std::async Thread Pool functionality) However, an error occurs during execution. What's the problem and how can I fix it? thread test. void for_print(int num) { for (int i = 0; i < 1000; i++) print...
std::vector<std::thread> v_thread(2000); for (size_t i = 0; i < 2000; i++) v_thread.emplace_back(std::thread(for_print, i)); for (size_t i = 0; i < 2000; i++) v_thread[i].join(); This is wrong. You first create a vector of 2000 "empty" thread objects, then add additional 2000 "living" threads, and finally join...
62,285,576
62,292,147
Simple linked list with full set Rule of Five
I'm trying to correctly implement a simple linked list respecting the rule of 5. I get to about 3, although I already have my doubts here, but from there on, I'm on thin ice. As it seems like a fairly common topic, I was surprised I couldn't find a complete example. I've found bits and pieces, but no complete set. So i...
The first thing to address is that your assignment operator is not correct. You're using the copy / swap idiom, but you forgot to do the copy. NodeList& NodeList::operator=(NodeList src) { std::swap(head, src.head); return *this; } Note the change from a const NodeList& to NodeList src as the argument. Thi...
62,286,102
62,286,103
How do I forward a signal to private signal?
Suppose I have the following class: class Example : public QObject { Q_OBJECT public: explicit Example(QObject * parent = nullptr); void example(); signals: void publicSignal(); void privateSignal(QPrivateSignal); }; The privateSignals use a QPrivateSignal and therefore can only get emitted by the...
Unfortunately not without a small helper. Qt's automatic QPrivateSignal filter from signals in its connect syntax does not port over to its slot argument. Therefore, you need a lambda for your Example: connect(other, &SimilarExampleClass::publicSignal, this, [this](){ emit privateSignal({}); });
62,286,390
69,661,412
Removing invalid URLs from MSHTML document before it is loaded
I use MSHTML (IHTMLDocument) to display offline HTML which may contain various links. These are loaded from email HTML. Some of them have URLs starting with // or / for example: <img src="//www.example.com/image.jpg"> <img src="/www.example.com/image.jpg"> This takes a lot of time to resolve and show the document becau...
After a long time this is the solution I used: Created an instance of CLSID_HTMLDocument to parse HTML: DelphiInterface<IHTMLDocument2> diDoc; OleCheck(CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&diDoc))); Write IHTMLDocument2 to diDoc using Document->write // Creates a new one-dimen...
62,286,460
62,286,912
C++ How to pass a parameter to an STL function
I had to pass an unordered map to the comparator function of a priority queue and using the link Passing a parameter to a comparison function? I decided to do it as follows: priority_queue < int, std::vector<int>, compare(freq) > pq; struct compare { compare( std::unordered_map<int,int>& freq1 ) ...
As the error message said, compare(freq) is not a type, it can't be specified as the type template argument. You should specify compare(freq) as the argument of the constructor of priority_queue, and specify compare as the type template argument. priority_queue < int, std::vector<int>, compare> pq{compare(freq)}; // ...
62,286,902
62,287,116
Inheritance - Operator overloading
I have two classes, base and derived. In main I have a vector which is *base type and contains one base object and one derived object. I have overloaded output operator for both classes, but when I print the vector for derived class, base output operator is called although I have overloaded it separately. What should I...
Dynamic dispatch, based on the underlying object, works only for virtual member functions. It does not work for non-member functions or non-virtual member functions. One way to get around the problem would be: Use the friend function using the base type. Change the argument type for obj to be a const reference. From t...
62,287,107
62,287,180
How to pass in the 'this' pointer to a C++ WinAPI thread?
I am trying to run a C++ thread but also pass in the instance to the class itself. I cannot seem to figure it out. I have a struct for parameters to the thread: struct CLASS_PARAMS { SomeClass* ptr; }; I then call my setup method: void SomeClass::setup() { CLASS_PARAMS params; params.ptr = this; Create...
You allocate CLASS_PARAMS on stack, so it is destroyed before used. Allocate it dynamically, pass pointer and free it in the thread. Alternatively, if you need to pass only this, pass it without wrapping structure, just cast to LPVOID and back (but be sure to use the same class pointer type to avoid pointer adjustment ...
62,287,600
62,307,231
Handling time in C++
I am writing a simulation program. I have some difficulties when handling the time. My program has a time period and a total elapsed time variables. I have traffic light objects. I want to change the color of them when the elapsed time is integer multiple of the period. For example, say total time starts from 0 and fi...
You can use the standard <chrono> library, but SFML has its own set of tools for handling time. You don't need any complicated calculations or threads. A simplified example of part of what you need: #include <SFML/Graphics.hpp> #include <vector> class Light : public sf::CircleShape { public: Light(std::vector<sf::...
62,287,927
62,348,582
Is there a way to enable/disable (grey out) the Rotation Lock in Action Center programmatically on a Windows 10 device without rebooting?
I'm developing a feature on a Surface Book that can control the Rotation Lock of the device. This involves turning Rotation Lock on/off, as well as disabling it alltogether. To clarify, my question here is not about turning Rotation Lock ON/OFF, which makes the icon turn blue or neutral. I'm talking about turning Rot...
After submitting the same question to the MSDN forums about this, the consensus appears to be that there is no API that exposes the capability to grey out the 'Rotation Lock' icon. However, the undocumented SetAutoRotation API can toggle the 'Rotation Lock' icon on and off.
62,288,463
62,288,559
change function defination based on type trait?
I would like to change my function definition based on type by using enable_if_t. Some thing similar to this: #include<type_traits> template<typename T> struct A; template<typename T> struct A{ std::enable_if_t<std::is_arithmetic<T>::value, bool> test() { return true; } std::enable_if_t<!st...
You can try with template <typename U = T> std::enable_if_t<std::is_arithmetic<U>::value, bool> test() { return true; } template <typename U = T> std::enable_if_t<!std::is_arithmetic<U>::value, bool> test() { return false; } I mean... SFINAE works over template parameter of the functions/methods, not over template...
62,288,640
62,305,063
Can't grab frames from an ip camera (rtsp) with a C++ dll using OpenCv 3.4.5
I'm building a simple application in c++ (32-bits) that uses opencv to grab frames from a rtsp camera. The function that grabs the camera frames run in a separated thread from the main program. I've testes this application with a mp4 video, and it works fine. I was able to grab frames and process them. However when I u...
Sorry for answering my own question. But after a lot of trial and error, and reading various SO threads regarding the issue of using cv::VideoCapture in in Windows. I found the issue, I was trying to statically link OpenCv in my application, and due to license issues ffmpeg cannot be compiled statically along with t...
62,288,643
62,296,854
InkCanvas manipulation event
When the only InputDeviceType of InkPresenter is CoreInputDeviceTypes::Pen then InkCanvas emits the ManipulationDelta event. When I change InputDeviceType to more types, then not. Why is that? InkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Touch | CoreInputDeviceTypes::P...
Based on the Remark part of InkCanvas, it mentions: The configuration of the InkPresenter determines the pointer event handling behavior of the InkCanvas. You must set InkPresenter.InputDeviceTypes to CoreInputDeviceTypes.None for the InkCanvas to process pointer events, otherwise they are passed to the InkPre...
62,288,947
62,289,280
Create vector of member variables from vector of class pointers
I have a std::vector containing pointers to instances of SomeClass. This class has (among other things) a member variable with type SomeOtherClass. I assume there should be a way (some kind of cast for instance) to efficiently create a new vector containing objects of SomeOtherClass. Currently I use the following: std:...
What you've got is the best you can do, if you need another vector. It can be made a bit more C++-like with std::transform and an insert iterator, but it's hard to see how that code would be any clearer than your simple loop. You cannot cast one vector type to another, even if their respective element types are related...
62,289,273
62,289,776
Why do I get non-object type 'char *(const char *, int) throw()' is not assignable
I implemented a minimal verifiable example below that replicates the issue. The problem I have is after that a QLabel count down arrives to 00:00, I would like the application to shut down automatically. But this is not happening and I obtain from compiler the following error: non-object type 'char *(const char *, int...
You seem to have some code that look like this: If you read the Qt documentation for QLabel::setText correctly, you'll see that there is a problem with the code you presented. The Qt documentation says that the setText returns void. In other words, that function return nothing. Yet, you try to get the result of the fun...
62,289,325
62,289,373
C++ pointer showing impossible memory location
I made a C++ variable and printed its address and it came out to be very large: 0x7ffdf584da2c. My code is as follows: #include <iostream> using namespace std; int main() { int var = 10; cout << "value: " << var << " address: " << &var << endl; return 0; } value: 10 address: 0x7ffec6f111c4 This type of Hex...
It's fine. Computers in 2020 are very complicated. Your process gets a virtual address space whose maximum "slot" will almost certainly exceed the size of the actual RAM on your system (and page file).
62,289,355
62,297,330
Reading a pointer from another process memory
I'm trying to read a pointer from another process. I can read the content of the pointer, and I actually receive an address, but what I want to do is to go one step beyond that and take the value inside the received address. I think i'm doing it wrong, or else I guess it's not possible the way I'm doing it? Here's my c...
I’m not sure if I misunderstood, you may have the process like below: #include <windows.h> #include <iostream> int main() { int data = 10; int* p = &data; int** pp = &p; printf("pid = %d\n", GetCurrentProcessId()); printf("p = %x\n",p); printf("pp = %x\n", pp); printf("address of pp = %x\n"...
62,289,481
62,289,518
write access violation when inserting array
I am defining a structer for my class. Basicly i want take an input and write it to member variable(array). class DynArray { int m_size; int* m_p_array; public: DynArray(){ std::cout << "Please enter size\n"; std::cin >> m_size; m_p_array[m_size]; for (int i{ 0 }; i < m_siz...
This is not how you allocate memory for the array: m_p_array[m_size]; You need to do this: m_p_array = new int[m_size]; later you need to free the memory in your destructor: delete[] m_p_array; but consider using std::vector instead because it is better.
62,289,756
62,293,867
How to find difference in time in seconds and nanoseconds between two dates?
I need to calculate the seconds and nanoseconds between the Unix Epoch (00:00:00 January 1st 1970 UTC) and some date in the future the user will select. Here is what I managed to find so far looking through other Stack Overflow answers: // seconds and nanoseconds past epoch auto now = std::chrono::system_clock::now().t...
In C++20 this looks like: using namespace std::chrono; nanoseconds now_ns = sys_days{July/1/2020}.time_since_epoch(); auto now_sec = duration_cast<seconds>(now_ns); now_ns -= now_sec; std::cout << now_sec << ", " << now_ns << '\n'; Output: 1593561600s, 0ns Finding a C++20 std::lib that can do this today is going to b...
62,289,941
62,289,951
pass const reference to thread
I need to pass some data to following method: thread::thread(_Fp&& __f, _Args&&... __args) However, my data is const& and there is no copy or move constructor. I am wondering how to make it work?
Use std::cref. This "wraps a reference" so you bypass std::thread's tendency to copy your arguments. It then becomes your responsibility to ensure that doing so is thread-safe. void foo(const int&); int main() { const int myThing = 42; std::thread t(&foo, std::cref(myThing)); t.join(); } This is mentioned o...
62,289,970
62,290,064
Why can't I have conditions like this in for loop? (C++)
Is this legal? int sum {0}; for (int i=1; (i % 2 != 0) and (i <= 15); i++) sum += i;
If you meant to add all odd numbers up to 15, this is what you should have instead. int sum {0}; for (int i = 1; i <= 15; i += 2) sum += i;
62,290,016
62,290,042
C++ is calculating wrong
i have an inexplicable problem. Here is my code: int result; result = 0 * 2 ^ 1; std::cout << result << std::endl; The result of this calculation is 1. But why? Actually it should be 0, shouldn't it? I've tried it with the pow-function of the math-library but there the result also is 1: int result; result = std::pow(0...
In C++, and many other computer programming languages, ^ means XOR not power-of. So it may not have the precedence you expected from mathematics. Use std::pow for exponents: const int result = std::pow(0 * 2, 1); std::cout << result << '\n';
62,290,688
62,308,352
Wrong OpenGL viewport of widget inside QDockWidget
I am drawing stuff on a widget which is inside a QDockWidget and has a 1:1 squared aspect ratio. However, the drawing surface is not properly resized. How it should work: How it works: The code just draws 4 points at corners (coords) and anotherone in the middle const float vertices[] = { 0.0f, 0.0f, 0.0f, -...
I forgot to put a QOpenGLWidget::resizeEvent(event); in the resizeEvent. Full code is in the answer.
62,290,758
62,291,886
unpredictable C++ sleep/wait behavior
I must be doing something stupid because I am getting the weirdest behavior from this simple sleep code. Originally I was using std::this_thread::sleep_for and got the same results but assumed it must have been some thread strangeness. However, I am getting the same seemingly out-of-order waiting with the code below. S...
Normally iostreams do not flush until a newline is encountered. Since you don't output an EOL character, you need to explicitly flush to get the output printed: std::cout << i << "... " << std::flush; Unrelated, but note also the CPU getting a bit hot when you run your program. To save energy, consider changi...
62,290,837
64,531,720
Pawn Class Hitting Itself With The On Begin Overlap Event Unreal Engine C++
I made a simple pawn class that's supposed to be a ball and move around and collect coins. For the coin collection system I made the on overlap event to notify the ball when it is hit. Here is the basic code (APlayerBall is the default pawn class that gets spawned into the game) : PlayerBall.h UCLASS() class ROLLINGBAL...
It looks like the mesh component is overlapping with the capsule component. Add the component to your logs to confirm. If you only want to know when your actor overlaps with another actor, you might want to use AActor::NotifyActorBeginOverlap instead. If you want to use component overlaps, but you want to ignore overla...
62,291,614
62,316,322
OpenCV Laplacian output in C++ excludes negative values, but not in Python
Performing the same Laplacian operation in C++ and Python appears to produce different results. Notably, the C++ variant does not report negative slopes in the result matrix. I am using (C++): Laplacian(img.clone(), img, CV_16S, 1, 1, 0, BORDER_DEFAULT); and (Python): img = cv2.Laplacian(img, ddepth=cv2.CV_16S, ksize...
Your C++ implementation is calling Mat::at<uchar> which means "interpret the data at this location as uchar (i.e. uint8_t)" but your data is of course short (i.e. int16), not uchar. From the docs on Mat::at, note that they specify: If matrix is of type CV_16S then use Mat.at<short>(y,x).
62,291,830
62,291,897
Big O-Notation of N-Dimensional array
What is the complexity of the two algorithms below (size is the length of each dimension)?: void a(int** arr, int size) { int k = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { arr[i][j] += 1; } } print(arr, size); } void b(int*** arr, int ...
Time Complexity : The time complexity of first function is - O(size^2) The time complexity of second function is - O(size^3) The time complexity of N-dimensional array each of size N for a similar function would be - O(N^N) since the iterations required would be N * N * N... upto N times. So, you were correct in the...
62,291,848
62,292,188
How to represent recursive Object structure of JSON Documents in C++?
I want to represent a json-like file, like the following ... { root_att_0: 23, root_att_1: { root_att_1_att_0: "Peter", root_att_1_att_1: 3.14f }, root_att_2: ["Hello", "World"], root_att_3: { root_att_3_att_0: 64, root_att_3_att_1: { root_...
JSONObject o { {"string", std::variant<JSONType, JSONObject>(JSONType(true))} }; Is missing a set of braces. You need one set for JSONObject, one for the attributes member and a final set for the map entry: JSONObject o { { {"string", std::variant<JSONType, JSONObject>(JSONType(true))...
62,291,976
62,292,014
private member data not being available to public member function
I have the code below. When I have main Run() function run the ResetTrackingTable() function. The ResetTrackingTable() calls 0 for my_n_rows and my_n_cols instead of accessing the existing numbers stored in the private member data. Why is that? It seems like it's making a new instance of the function... public: ...
These lines of code: int my_n_rows = gameBoard.numRows(); //Import number of rows int my_n_cols = gameBoard.numCols(); //Import number of cols are declaring new variables inside the Run function. If you want to refer to the member variables instead, drop the int declarator: my_n_rows = gameBoard.numRows(); //Import nu...
62,292,110
62,323,859
OpenGL 4.1 and lower Black Texture, Mac and Windows
I had this problem when compiling my OpenGL code on lower-end PC's that don't support OpenGL 4.5 and macs. In my regular code, I would use functions like glCreateTextures and glTextureStorage2D, but they are not supported in other versions so I went the other glGenTextures path. Here's the image generation code: Textur...
It turns out I had to specify GL_TEXTURE_2D in these places instead of texture ID: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_...
62,292,126
62,292,225
Creating template types without new/delete
I have a C++ Object class like this: class Component {}; template <typename T> concept component = std::is_base_of_v<Component, T>; class Object { std::map<std::type_index, Component*> components; public: template<component T> T* add() { if(components.find(typeid(T)) == components.cend()) { T* ...
I suppose, you think of this as the alternative way of creating your objects T value{std::forward<Args>(args)...}; components[typeid(T)] = static_cast<Component*>(&value); This creates a local variable on the stack. Doing the assignment then, stores a pointer to a local variable in the map. When you leave method add()...
62,292,386
62,292,538
How to write a macro that will be expanded to define an object with template parameters
Is it possible to write a macro, which, in turn, creates an object definition from it, for example: DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, 1.0, 1) should become: ObjectType a<double, int>(1.0, 1); and DEFINE_OBJECT_INVALID_VALUES(ObjectType, double, int, bool, 1.0, 1, false) should become: ObjectTyp...
You can overload a macro on number of arguments: #define DEFINE_OBJECT_INVALID_VALUES_2(T1, V1) \ a<T1>(V1) #define DEFINE_OBJECT_INVALID_VALUES_4(T1, T2, V1, V2) \ a<T1, T2>(V1, V2) #define DEFINE_OBJECT_INVALID_VALUES_6(T1, T2, T3, V1, V2, V3) \ a<T1, T2, T3>(V1, V2, V3) #define DEFINE_OBJE...
62,292,446
62,293,090
free invalid pointer disappeared after applying address sanitizer
I got a free: invalid pointer when running my project. But when I try to hunt the root cause using -fsanitize=address, the error disappears. When I remove the sanitizer, the error appears again. Can anyone give some hint about what was happening and how to pinpoint the problem in such a case? Thanks! Update: I understa...
Since you asked a vague and inspecific question, I'll provide a cliche and inspecific answer... Try not to allocate and de-allocate directly, yourself Read this SO question and its answers: Why should C++ programmers minimize use of 'new'? if you use containers (std::vector, std::array etc.), or smart pointers (std::un...
62,292,484
62,292,713
Pass a fold expression to a variadic template
consider the following function that prints the arguments using fold expressions. template <typename... T> void print(T &&... t) { (std::cout << ... << t) << '\n'; } Consider a second function that calls it : template <typename T, T... vals> void call_print(std::integer_sequence<T, vals...> &&) { print(vals......
print((vals, ...)) expands to print((0, 1, 2, 3, 4)). (0, 1, 2, 3, 4) is an expression using the comma operator. The comma operator evaluates both of its operands and discards the result of the left-hand side of the expression. That means that the expression (0, 1, 2, 3, 4) evaluates to the value 4. Thus print((val...
62,292,522
62,308,013
RAII equivalent for FIFO release order
RAII is quite comfortable and I am having difficulties to provide an equivalent design for resources that must be released in the same order they were acquired (FIFO) as opposed to in the reverse order (Stack) that naturally come out of RAII. In my specific case, I have a stream class as follow: template<typename T> cl...
Here's an alternative that uses a std::queue and works in C++11 and up: #include <queue> void test(stream<float> &fifo) { std::queue<stream_wslot> wslots; #if __cplusplus >= 201703L // C++17 and later: auto& even = wslots.emplace(fifo); auto& odd = wslots.emplace(fifo); #el...
62,292,813
62,312,420
What does it mean to "Implement an empty logic" for a function in ue4?
I'm following a tutorial for setting up a character interaction, and part of it says to make a header file with the following code: public: /*This property will be used in order to bind our subtitles Binding will make sure to notify the UI if the content of the following variable change.*/ UPROPERTY(BlueprintReadOnly) ...
It means to just leave the contents of the function blank or return an empty result such as: FString AMyCharacter::GetNickname() { return ""; } in the case where the return type isn't void.
62,292,910
62,293,249
How can I connect to my SQL Database through C++?
I've seen some similar questions but most are based around PHP, there was one based around C but the only answer was go to the SQLConnect() docs, which I've already done. https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlconnect-function?redirectedfrom=MSDN&view=sql-server-ver15 Seems to be little content ...
I have added the comments inside the code, which will help you to understand the code easily. Credits: Link /* Includes Standard C++ */ #include <stdlib.h> #include <iostream> /* Include directly the different headers from cppconn/ and mysql_driver.h + mysql_util.h (and mysql_connection.h). This will reduce yo...
62,292,927
62,293,380
How to instruct MS Visual C++ compiler to use an uninitialized __m512i register
How to instruct the Visual C++ compiler (1926) to use an uninitialized __m512i register. In the following code snippet a not(or(A,B)) is calculated, the content of dummy is irrelevant. __m512i dummy; const __m512i n8 = _mm512_ternarylogic_epi64(dummy, A, B, 0x11); Somehow the compiler assumes the register needs to hav...
and a stall xor-zeroing is dependency breaking. It's also literally as cheap as a NOP on current Intel CPUs, and avoids the risk of an output dependency coupling this dep chain into another one. It won't cause a stall (except indirectly, like from an I-cache miss), but it is a potential waste of one fused-domain uo...
62,292,962
62,292,991
Trying to figure out why I'm getting a runtime error?
This is code for the intersecting arrays. It seems to work for most of the cases until nums1 = [1] nums2 = [1,1] class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> temp; int i = 0; int j = 0; for (i = 0; i < nums1.size(); i++) { ...
The order of your checks are wrong. You need to check if i is a valid index before indexing, like this: else if ( (i < nums1.size()) && (nums1[i] == nums2[j]) ) { otherwise you invoke undefined behavior (which could cause a run-time error). Similarly, in all the cases where you are indexing into a vector, you need to ...
62,293,194
62,293,218
Where are these nullptr located?
int* x = nullptr; class_example* obj = nullptr; I understand what nullprt is, but where are these variables x and obj located? Heap? or Stack?
Pointers are just ordinary variables, that happen to have values that are addresses of other objects (and those addresses could be on the heap). So in this snippet: int main() { int* x = nullptr; class_example* obj = nullptr; } just like regular local variables, these pointers will be located on the stack.
62,293,326
62,293,583
static_cast does compile with no errors?
If I have two classes: 1) Employee 2) Engineer which is derived from Employee 3) Manager which is derived from Employee I was told (and tried myself) that the following doesn't compile: Employee employee("John Smith"); Engineer* ptr2 = &employee; // error Since an Employee is not an Engineer for sure. But why the foll...
Manager* m = ...; Employee* emp = m; This performs an implicit cast from Manager* to Employee*. This is allowed because a pointer to a derived class type can be implicitly converted to a pointer to its base class. (There are some caveats, none of which apply in your case. So I choose to stick to the simple version.)...
62,293,424
62,293,504
What is the difference between exit(0) and raise(SIGTERM)
I am trying to terminate my app on some particular event. Why would one use exit(0) or raise(SIGTERM) over the other? Also since exit(0) returns EXIT_SUCCESS to the host, what does SIGTERM do? Is it always failure?
exit causes the program to terminate with normal exit status, with value given by the argument to exit, in your case 0. raise raises a signal, which may be caught. If it's not caught or blocked then the default action is carried out. For SIGTERM, the default action is abnormal termination, and the signal that caused it...
62,293,683
62,293,806
Using placement new with an std::function doesn't work
This code crashes at (*function)(). I'm running Visual Studio 2019 and compiling C++17 for Windows 10 x86_64. I've tested it on Linux with GCC (-std=c++17) and it works fine. I'm wondering if this is a problem with Visual Studio's C++ compiler or something that I'm not seeing. #include <vector> #include <array> #includ...
When you append an element to a std::vector and that element would make the vector's size greater than its capacity the vector has to allocate new storage and copy/move all of its elements to the new space. While you've constructed complex std::function objects in the char arrays held in your vector, the vector doesn'...
62,293,820
62,294,344
Can you use an OR in a switch?
Can you use an OR operator in a switch case? I was trying to remove case sensitivity from a user input check (so there may be a better way to do this altogether, I'm a beginner after all), and this of course resulted in doubling my switch case (not including the default case). Would it be better to use an if/else at th...
If you do not plan to distinguish whether letters are lowercase or uppercase, then the best solution would be to "convert" your switch variable to lower/uppercase. By that you will get rid of unnecessary cases and save some time in future while implementing new ones. Depending on your decision, you may choose std::tol...
62,293,890
62,294,645
The meaning of "static char __ = []() -> char"
I saw the code from several solutions from LeetCode's problems. static char __ = []() -> char { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); return '\0'; }(); I understood that the following lines are for fast I/O. std::ios_base::sync_with_stdio(false); std::cin.tie(NULL)...
This code: []() -> char { return '\0'; }() is an expression which calls an unnamed lambda function. In fact it contains some redundant elements and could have been written []{ return '\0'; }(). Since empty argument list in lambdas can be omitted, and the return type can be deduced from the expression in the return stat...
62,294,007
62,294,075
Convert a Vcl::Controls::TCaption aka (System::UnicodeString) to a const char *
I'm currently using C++Builder to create an application that copies text to the user's clipboard. I've placed a TMemo control and I want to contain that in a const char * variable as seen in the code below: const char* output = TMemo1->Text; When I compile the program it throws the error no viable conversion from 'Vc...
The Text property returns a UnicodeString object, not a const char* pointer. And there is no implicit conversion from UnicodeString to const char* (nor do you want one). So you would have to convert the data manually, such as with WideCharToMultiByte() (or equivalent), eg: UnicodeString text = TMemo1->Text; const size...
62,294,091
62,294,284
How to ensure user inputs a first and last name when only prompting for input once on one line?
C++ beginner here. I am storing structs of playerData in a vector (referred to as the player bank). One member of the struct is the player's name (stored in the struct as 1 string like "Julio Jones"). While using my application, if the user inputs a name that is not in my program's premade bank of players, the user is ...
You are assuming that people have only 1 first name and 1 last name separated by 1 space. Names are not always that simple. You should prompt the user for 1 string, save that to the playerName, and then store the entire playerName as-is to your file followed by a delimiter that is guaranteed to never appear in any nam...
62,294,424
62,294,473
Why am I getting segfault?
I'm a beginner to C++, and am working on a class that grades a student's answer ("11 3 1133 22322314231432211231 34 2") by comparing it to an answer sheet ("112341423114322314231442314231223422"). I must compare each value of the student's answer and if they match, add 2 points; if they don't, subtract 1. Now, if the a...
Your for-loop conditions are not actually conditions. From w3schools: for (statement 1; statement 2; statement 3) { // code block to be executed } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (ever...
62,294,441
62,294,471
cout of string doesn't show anything
The cout of encrypted string doesn't show anything and sometimes the program crashes. And when i do cout << encrypted[i] in for loop , i got the correct result. Also if i do a for loop to read string char by char for(char c:encrypted) , cout << c << endl; => it doesn't work also and got garbage. #include <iostream> #in...
After string encrypted; encrypted is default-initialized as empty std::string which contains no elements. Then any access to non-existent elements like encrypted[i] leads to UB. You can use push_back (or operator+=) instead. //encrypting for (size_t i{}; i<message.length(); i++) { if (alphabet.find(message[i]) !...
62,294,879
62,296,965
Eigen, wrong use of comma initializer with different types
This is what I am trying to do: Eigen::MatrixXd extended_points(4,4); extended_points << Eigen::Vector3d(-0.8, -0.8, 1.0).normalized(), 1.0, Eigen::Vector3d( 0.8, -0.8, 1.0).normalized(), 1.0, Eigen::Vector3d( 0.8, 0.8, 1.0).normalized(), 1.0, Eigen::Vector3d(-0.8, 0.8, 1.0).normalized(), 1.0; This i...
A possible issue: Isn't Eigen::Vector3d a column vector? As a workaround, you can try RowVectorXd as in the documentation.
62,294,964
62,296,956
RtMidi - MidiInDummy: This class provides no functionality
I want to use Rtmidi to get input from launchpad. However, despite connecting the launchpad, 0 pods are available. "MidiInDummy: This class providers no functionality." There's also this phrase, so something seems to be wrong. Source: //Source : http://www.music.mcgill.ca/~gary/rtmidi/index.html#probing #define __WINDO...
Oh, I solved it. https://www.music.mcgill.ca/~gary/rtmidi/#compiling https://github.com/thestk/rtmidi/issues/85 keyword : __WINDOWS_MM__, winmm.lib
62,295,270
62,317,203
My wrapper function is missing a variable?
Due to a peculiar error I was having, I decided to wrap a function like so to resolve said error: UFUNCTION() void OnBoxOverlapWrapper(UPrimitiveComponent* /*ignored*/, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherIndex, bool bFromSweep, const FHitResult & SweepResult) { OnBoxOverlap(Othe...
It turned out you needed to write a body for the OnBoxOverlap function .
62,295,303
62,295,348
Finding minimum value in std::map
For a non-selfbalancing binary search tree, finding the minimum in the worst case can take O(N) and average case O(log(N)) to traverse to the corresponding leaf node. Per CPPreference, the time complexity of the function std::map::begin() is constant. Therefore extending this a little further, de-referencing std::map::...
The map object could simply maintain an internal pointer to the minimum element; if the tree is mutated in a way that changes which node is the minimum, the pointer to this element could be adjusted at that time. Returning an iterator from the pointer is therefore a constant-time operation since no tree traversal is n...
62,295,310
62,298,800
How is std::atomic<T>::notify_all ordered?
I expect the below program not to hang. If (2) and (3) are observed in reverse order in (1), it may hang due to lost notification: #include <atomic> #include <chrono> #include <thread> int main() { std::atomic<bool> go{ false }; std::thread thd([&go] { go.wait(false, std::memory_order_relaxed); // (1...
The standard states: A call to an atomic waiting operation on an atomic object M is eligible to be unblocked by a call to an atomic notifying operation on M if there exist side effects X and Y on M such that: the atomic waiting operation has blocked after observing the result of X, X precedes Y in the modification ord...
62,295,481
62,297,136
Only One of the pop up is Handled?
I am using win32 API to develop an Application.I am using WM_LBUTTONDOWN message to handle two operation . If a click on button X I want to perform operation A. a)If a double click occur on button X I want to perform operation C as well that is operation A followed by operation C. But while implementing I ca...
With the help of an answer from your previous case. Because your code logic uses if...else... conditional statements. The way I can think of is to add an additional timer in the case of double-click to complete the action when clicked. void CALLBACK f(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime) { EnableWindow...
62,295,511
62,295,772
Sqlite3: Store db table names in a vector
Note: c++98 I'm trying to retrieve the table names inside a database and store them inside a vector as strings. My code: typedef vector<string> dbTableTypes; static int callback1(void *handle, int argc, char **argv, char **azColName) { // FILE *f1 = (FILE *)handle; dbTableTypes *dbTables = (dbTableTypes*)handl...
Solved it myself. Solution for the curious: typedef vector<string> dbTableTypes; static int callback1(void *handle, int argc, char **argv, char **azColName) { dbTableTypes *dbTables = (dbTableTypes*)handle; int i; char *pEnd; const char *sep = "\t"; for (i = 0; i < argc; i++) { cout <<...
62,295,656
62,295,703
Implementing a class that uses a templated class without making original class a template
Sorry if the title is confusing. Hopefully the example code will make it more clear. Lets say I have a class: template <typename T> Class_A { //has some methods } Now I also have a class: Class_B { vector<Class_A *> array; void add( Class_A * arg) { array.push_back(arg); } } So right now Class...
Derive from class A_Base with destructor & relevant methods as virtual. Use this A_Base, wherever you don't want templates. E.g. template<typename T> class Class_A : public A_Base { ~Class_A() override; // Other virtual methods };
62,295,894
62,295,974
What is the difference between string1 == string2 and your own for-loop comparison?
Say you want to compare two strings in C++ to see if they are the same. Aside from less typing, is there any difference between the following? Is one faster than the other, and is there a better way to compare the strings than what is contained here? Version A: if( string1 == string2 ) { return true; } Version B: // C...
Is there any difference between the following? Yes. Your code doesn't check the length of the strings, so if the first string is longer than the second string you can end up reading past the end of the second string. If the first string is a proper prefix of the second string your code returns the wrong result. Is o...
62,295,988
62,420,147
How to transfer realsense data via ROS to other Device(s)
I want to make the program under " catkin_ws/src/realsense-ros-3.2.13/realsense2_camera " directory from the "ros wrapper site" transfer realsense data to other devices. I've chosen to use ".cpp file" since I've already made the program which uses C++ and realsense camera. I want to know the relationships of the files ...
Thank you for your information. I've been wandering why I couldn't get the D435's Data, but I solved it. Starting "realsense-viewer" when "roslaunch" the ".launch file" and restarting the "Terminal" SEVERAL TIME can make "default .launch file" launch, so re-writing the "launch file" might be able to move the C++/Python...
62,296,068
62,296,177
When should a function be inline or not?
Say I have the following class declared in a header file, with a friend function swap: // header.h class myClass { friend void swap(myClass &, myClass &); public: myClass(int ii = 0) : i(ii) {} private: int i; }; Now I want to define swap. If I define it later in the same header file like this, inline vo...
From the C++ Standard (9.1.6 The inline specifier) 6 If an inline function or variable is odr-used in a translation unit, a definition of it shall be reachable from the end of that translation unit, and it shall have exactly the same definition in every such translation unit (6.2). [Note: A call to the inline fu...
62,296,253
62,296,372
Returning Rvalue Reference and Temporary Materialization
Consider the following functions. I'd like answers for C++17. MyClass&& func() { return MyClass{}; } int main() { MyClass&& myRef = func(); } Questions: Is the expression func() an xvalue? Why? Why is myRef a dangling reference? Or, more specifically, why is func() returning a dangling reference? Wouldn't return...
func() is an xvalue because one of the rules of the language is that if a function is declared to have a return type of rvalue reference to object, then an expression consisting of calling that function is an xvalue . (C++17 expr.call/11). Temporary materialization occurs any time a reference is bound to a prvalue. Th...
62,296,641
62,382,231
Unable to implement Google Sign-In using QOAuth2AuthorizationCodeFlow
The issue is with redirect URIs, I don't know what to set it to. Hase ANYONE been able to figure this out? I get an error in Qt Creator's output pane that looks like this: qt.networkauth.oauth2: Unexpected call qt.networkauth.replyhandler: Error transferring https://oauth2.googleapis.com/token - server replied: Bad Req...
I had a hard time debugging it. But, I have realized that if you goto Google console and set the Redirect URI to http://127.0.0.1:some_port/ instead of http://localhost:some_port/ Remember to put '/' in the end it magically works. Rest here is my code this->google = new QOAuth2AuthorizationCodeFlow(this); t...
62,296,778
62,297,424
Why `vector<bool> v; for(auto&& e:v){e=false}` compiles(i.e. the element's value could be modified) whereas the ref of vector<bool> is a prvalue?
Why the code below compiles (i.e. the element's value could be modified) whereas the reference of vector<bool> is a prvalue? I would be very grateful to have some help with this question. Here is the related code: #include <vector> #include <iostream> int main() { std::vector<bool> v(10,true); for (auto&& e : ...
vector<bool> is special. Unlike vectors of other types, it doesn't store actual bools (that would require using 1 byte per bool). Instead, it stores them packed as bits in an array of integers (1 bit per value; for example, it might store an array of unsigned char and pack 8 bools as bits into a single unsigned char). ...
62,296,948
62,297,717
How to iterate over a multimap to satisfy an IF condition - C++
I have two multimaps, one with Dates and floats, the other with Times and floats. Both maps have duplicate values. In the multimap with dates as keys, i iterate over it and store the maximum float value for a date that was entered by the user. Then, in my next map I want to retrieve the times for the date where this va...
If Date and Time are not connected, then in no way. You cannot match time to a specific date. I would recommend creating a structure, like below and store your data in multimap<DateTime, float> struct DateTime { Date date; Time time; }; Afterwards you can write float maxVal = 0; for(const auto& [dateTime, valu...
62,297,003
62,299,735
How to test C++ code when using C functions
I wrote a c++ class, this class uses the c function library written by a third party. extern "C" { #include "nats/nats.h" } class NatsConnection { public: void Connect() { natsConnection_Connect(&natsConnection_, natsOptions_); natsConnection_SubscribeSync(&natsSubscription_, natsConnection_, ...
If you are to test the C++ class, then mock that one and treat it as one unit no matter what it calls internally. If you want to test the internals of the C++ class including C function calls, then C functions are commonly mocked by simple #define function-like macros. Example: #include <stdio.h> void function (int x)...
62,297,073
62,298,059
How to read a matrix from a file? (c++)
I've been trying a bunch of stuff and tried searching solutions but nothing I do works. This is not even a difficult thing to do but for the life of me I can' do it. Basically I have a .txt file generated by Matlab that's a 640*480 matrix. Each cell has 2 values separated by a coma. I want to read from that file to cr...
So, the solution is to use a Proxy class. An abstraction for your Cell. If you have a Cell, consisting of 2 values, then we will define a class with 2 values and overwrite the inserter and extractor operator for this class. Only the class should know, how to read and write its data. The extractor for reading something,...
62,298,087
62,298,320
Does C++ guarantee the atomicity of argument evaluation?
int a() { return 1; } int b() { return 2; } int c() { return 3; } int g(int, int) { return 0; } void f(int, int) {} int main() { f(g(a(), b()), c()); } I know the evaluation order of function arguments is unspecified as per the C++ standard. In other words, the actual evaluation order m...
I guess it is guaranteed since C++17. N4659 (March 2017 post-Kona working draft/C++17 DIS) [intro.execution]/18, reads: For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal hand...
62,298,456
62,298,551
Why I get this random weird number C++
I am new to using pointers with c++, so I am trying this small code but the problem is that when i try to print name i get this random weird number \364\277\357\376\326\241+\310\364\277\357\376\310. This is not the memory address, which is confusing and what confuses me more that when i replace name with getName() it ...
Person::name looks like it is a std::string *. In Person::Person(string Name, int Age) you pass the paramater Name by value and then store the address of this local variable in name. When Name goes out of scope you have a dangling pointer. (This also applies to void Person::setName(string Name)) Dereferencing Person::...
62,298,560
62,298,854
How to return reference of unique_ptr<Derived> from unique_ptr<Base>?
I work with unique_ptr on derived structs, and I return references to maintain ownership and keep minimal overhead. Basically, I want a get function to turn unique_ptr<Base> into unique_ptr<Derived>&. I can't use dynamic_pointer_cast as it copies and fails : no matching function for call to 'dynamic_pointer_cast<Deriv...
You can still just do a regular dynamic_cast with the raw pointer, ie.: template<typename T> T* get() { std::unique_ptr<Base> &p = obj; return dynamic_cast<T*>(p.get()); } Semanticly that is ok as raw pointer is taken to mean non-owning.
62,298,948
62,300,025
What happens if future.get() is called after promise.set_value()?
I create a promise and future objects: Promise<int> p = promise<int>(); Future<int> f = p.get_future(); I pass the promise to the background thread, which eventually calls p.set_value(myInt). In the main thread, I call f.get(). What if f.get() is called after p.set_value(myInt) is called? Would f.get() immediately re...
According to the documentation it calls wait - in order to wait for a result. According to that description in turn, it is stated that: Blocks until the result becomes available. That seems to imply it should not block (even for a short while) if there is a result already. So except for some sanity checks, mutex hand...
62,299,297
62,299,403
Is there any way to cast const class* to non const class
Is there any way to cast const class* to non-const class*? Background is that QModelIndex->model() returns const pointer to model. I need to access model::setData. But I can't.
Is there any way to cast const class* to non const class Yes. That is what const_cast is for. However, note that if you modify (non-mutable) state of a const object, then behaviour of the program is undefined. const_cast should not be used unless you can prove that the pointed object is non-const, or that the object ...
62,299,514
62,299,615
Is std::is_standard_layout_v<T> always true if std::is_trivial_v<T> is true?
template<typename T> void f() { if constexpr (std::is_trivial_v<T>) { // Does the following line never fail? static_assert(std::is_standard_layout_v<T>); } } Is std::is_standard_layout_v<T> always true if std::is_trivial_v<T> is true? If no, is there any counterexamples?
#include <type_traits> class type { public: int x; private: int y; }; static_assert(std::is_trivial_v< type >); // not standard layout because different access level of x and y static_assert(not std::is_standard_layout_v< type >); https://godbolt.org/z/xz3xLy
62,299,816
62,305,286
How to use/include the QtNetwork Module
I'm trying to develop a simple application in C++ that sends Files between two computers over LAN. After some research i found out that the QtNetwork Module is the way to go. I do include the QTcpServer and QTcpSocket in my solution. #include <QTcpServer> #include <QTcpSocket> I added the following path to the Additio...
Update So if someone is ever using qt in visual studio and wants to add the Qt Network Module or any other Qt Module to the Vs Project you just have to add the Path to the Qt lib to your additional Library Directories. In my Case it was C:\Qt\5.14.2\msvc2017_64\lib Under C/C++-> General add the Path to the Header of ...
62,300,237
62,300,370
does adding libraries in eclipse work the same way as in visual studio?
I used to code using visual studio,when linking boost libraries I just added the folder having libraries e.g boost/lib and vs automatically choose the required lib files and link against them. Now I am trying to link to boost lib in eclipse.I added the /usr/loca/lib folder which has boost library files. But undefined...
I assume by Eclipse you mean Eclipse with MinGW or Cygwin (both GCC-based toolchains). Auto-linking (#pragma comment(lib ...)) is a Visual C++ feature that is not available in GCC. With GCC you have to specify all the boost libraries that you're using when linking the program (including any libraries used by those libr...
62,300,307
62,300,342
Is there any way to remove constexpr
I got a pointer of constexpr const class*. Is there any way to remove constexpr, so I can access a variable editing member of class. Thank you (Yes, I ask a similar question removing const flag, butI think breaking down to the individual facts, combined with a general question, helps subsequent users)
There is no way to remove constexpr from a variable. constexpr variables are treated as literal types which are fundamentally constant. You can copy the variable and modify that instead. constexpr const T* var = ... const T* copy = var; Note that the constexpr here applies to the pointer, not the data pointed at.
62,300,380
62,300,485
Calling a virtual function from a destructor of a derived class in c++
Here is a snippet of my c++ code class A { public: virtual void method() { cout << "A::method" << endl; } virtual ~A() { cout << "A::destructor" << endl; } }; class B : public A { public: virtual void method() { cout << "B::method" << endl; } virtual ~B() { ...
Conceptually all the virtual functions in B are accessible in the destructor body, so your code is fine and well-defined as it is. But your code is extremely brittle: it would be a different matter if there was a child class of B which had method overridden. In that case writing B::method(); in the destructor body of B...
62,300,510
62,303,976
Why can't open a file via emscriptens fopen() saved in IndexedDB?
I'm trying out the Emscriptens IndexedDB, but can't get it running. The file can't be loaded, "cannot open file". With EMSCRIPTEN_FETCH_LOAD_TO_MEMORY everthing works fine. Download file via emscripten's emscripten_fetch_t Save file directly in IndexedDB via EMSCRIPTEN_FETCH_PERSIST_FILE Load it later into memory #in...
EMSCRIPTEN_FETCH_PERSIST_FILE actually does two things: Check whether the file is already stored in the IndexDB. If yes, retrieve it from there and do not bother the server at all. If the file is not in the local IndexDB, download it from the server and cache there. In particular, there is very little cache control: ...
62,300,511
62,300,590
How to fill a std::vector<int64_t> with text
I have a std::vector<int64_t> myVec in which I want to store a string (text). My understanding is that i cannot reserve space and write to myVec.data(), as this would be undefined behavior. What would be the non-hackish way to do this? I'm assuming the last int64_t will have to be filled with padding zeroes. I'm using ...
If you are constrained to vector the only solution is resize() to required size and strcpy/memcpy into data()
62,300,729
62,574,356
runtime error: reference binding to misaligned address 0xbebebebebebebec6 for type 'int', which requires 4 byte alignment (stl_vector.h)
i am writing code to solve this problem on leetcode my strategy to solve this is: run dfs for each cell index (x,y) on each dfs call check if cell is a destination cell accordingly set the flags if both flags are true then add this cell to "ans" vector else carry on with the next dfs class Solution { public: voi...
i found my error ! it was because of a missing boundary check for the newly calculated coordinate and improper boundary check for a coordinate in the beginning of psUtil. instead of this: if(x == m || y == n) . . . if(x1 < 0 || y1 < 0) continue; it should be this: if(x == m-1 || y == n-1) . . . if(x1 < 0 || y1 < 0 |...
62,300,750
62,300,803
How to cast, in C++, a byte vector (std::vector<uint8_t>) into different uint32_t, uint16_t and uint8_t variables
I have vector of bytes, std::vector, and I want to extract its information to some integers of different length. For example I could have a vector of 7 bytes and I would like to read a uint32_t at the beginning, then a uint16_t and last a uint8_t. I need a way to specify at which element of the vector should it start r...
You can take the address of the element in the vector to achieve what you want: std::memcpy(&a, &bytes[0], sizeof(std::uint32_t)); // ^ //or use .data() instead std::memcpy(&a, bytes.data() + 0, sizeof(std::uint32_t));
62,301,318
62,301,582
Recursive function for finding power returns zero for large exponents
The function bellow works fine for small positive exponents and base. If the exponent is large then memory wouldn't be enough and the program should be terminated. Instead, if that function is called for large exponents, zero is returned.Why? One guess is that a multiplication with zero occurred but there is no such ca...
Aside from filling memory, you should also worry about overflowing the result. 2^64 is 1<<64, which is 1 bit above the size of a 64-bit integer, so due to unsigned modulo arithmetic, that bit ceases to exist, and you end up with 0. Not relevant in your case, as you shift by smaller amounts, but left-shifting by a numbe...
62,301,478
62,301,596
The correct way to convert malloc to new
I am changing c code to c++ code and this is how how i have converted malloc to new frame.p_data = (uint8_t*)malloc(xres * yres * 4); free(frame.p_data); frame.p_data = (uint8_t*)operator new(xres * yres * 4); delete(frame.p_data); Is this the correct way to change from malloc to new and would the delete release all...
No, you should write frame.pdata = new uint8_t[xres * yres * 4]; delete [] frame.pdata; It is very rare to call the allocation function operator new explicitly, but if you do, you need to match it with the deallocation function, operator delete, otherwise the behaviour is undefined: frame.p_data = (uint8_t*)operator n...
62,301,648
62,302,861
Form a fibonacci triangle such that each number is the sum of two numbers above in either left diagonal or the right diagonal
The first few rows are: 1 1 1 2 1 2 3 2 2 3 5 3 4 3 5 8 5 6 6 5 8 13 8 10 9 10 8 13 21 13 16 15 16 13 21 34 21 26 24 25 24 26 21 34 ... I tried in C the following codes: Try 1: #include<stdio.h> #include<stdlib.h> int main(){ int a=0,b=1,i,c,n,j; system("cls"); printf("Enter the limit:"); ...
(EDITED to include an efficient iterative approach in Python). The triangle you are looking for is the Hosoya's Triangle. A mathematical formulation of this is provided in the original paper: H(0, 0) = H(1, 0) = H(1, 1) = H(2, 1) = 1 H(i, j) = H(i − 1, j − 1) + H(i − 2, j − 2) (j >= 2) = H(i − 1, j) + H(i − 2...
62,301,700
62,304,004
Complexity of a recursive function c++
*I'm trying to calculate the complexity Big-Theta-Notation of the following function: variable i is constant == 3 * void g(int i, int n) { if (i>0) { for (int j=n+10; j>0; j-=5) { g(i-2, n); } } } Because it's a recursive function, I thought I should calculate it with Master Theore...
The recurrence relation is T(i, n) = (n+10)T(i-2, n)/5. The terms for both odd and even i are geometric progressions with the multiplication factor (n+10)/5. This solves to T(i, n) = O((n/5)^(i/2)), or O(sqrt(n/5)^i) if you prefer.
62,301,746
62,302,079
Constructors taking initializer lists
I get the idea behind uniform initialization with curly braces. But why is that using this syntax on types that have a constructor that takes an initializer list, calls that specific constructor, even though the arguments are only wrapped in a single pair of curly braces, i.e. int main(int argc, const char ** argv) { ...
It sounds like you're asking for motivation, as opposed to where in the standard it says this must be done. For that you can look at the original proposal N1919 for intializer lists by Bjarne Stroustrup, the C++ language creator. He lists four ways to intialise an object: X t1 = v; // “copy initialization” possibly cop...
62,301,901
62,302,533
C2440 Create 2D Array with Shared_ptr
I'm trying to create 2D array with shared_ptr, but I have an error C2440. I think I write right codes, but error occured.. Please help me, thank you. #include <iostream> #include <memory> int main() { int size; std::cout << "Input size : "; std::cin >> size; std::shared_ptr<std::shared_ptr<int[]>[]> myA...
I changed follwoing code : for (int i = 0; i < size; i++) myArr[i] = std::make_shared<int[]>(size); // error.. into : myArr[i] = std::shared_ptr<int[]>(new int[size]); Making array with shared_ptr, you cannot use make_shared.
62,301,944
62,303,773
MFC: How can we switch from CTreeCtrl to CTreeView easly?
I have an graphics MFC application which historically was developed by using a CTreeCtrl. I want to add a CSplitterWnd to improve its graphical interface. However, I found that the CTreeCtrl is not compatible with CSplitterWnd. Apparently i must use a CTreeView. CSplitterWnd m_wndSplitter; // Runtime error on Crea...
The CTreeView class has member function CTreeCtrl& GetTreeCtrl() const. Replace all occurrences of SelectItem(foo); by GetTreeCtrl().SelectItem(foo);
62,302,120
62,303,301
C++: strod() and atof() are not returning double as expected
I am trying to make strings into doubles using the values that I obtained from a .txt file. The doubles I am obtaining have no decimals. I believe that this is because, in the .txt, the decimals of the numbers are separated by a comma instead of a dot. But I don't know how to solve that. This is a simplification of my ...
To avoid messing around with the global locale you can just replace , with . before calling strtod() std::replace(u10st.begin(), u10st.end(), ',', '.'); u10 = strtod(u10st.c_str(), nullptr); But in the program shown above you can also read from ifstream directly into double using operator >>, if you use a loca...
62,302,444
62,302,952
What do I need to do to display the shortest path using this BFS code?
I've written a C++ program to find out the shortest path using BFS algorithm. However, I can't find a way to print out the path, as in, the nodes which make the shortest path. What should I add so that it's possible for me to print out that path? #include<bits/stdc++.h> using namespace std; using ll = long long; using...
The shortest path from source to destination can be found by keeping track of parent for each node traversed. Create an array parent[node+1] and assign parent of source as zero. While doing bfs from source update parent array. Now you can get the path from destination to source by accessing parent of destination and pa...
62,302,849
62,303,038
I need help in structure in c++
The program is to take a structure with object name "st" will take age and then first and last name than standard But it is saying this error (main.cpp:33:10: error: invalid use of non-static member function ‘void Student::age(int)’) #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <alg...
Right now it's really unclear what you're trying to achieve with your code. First of all, your problem is because trying to to put some input into member functions that take arguments, you need to get your input into temporary arguments and pass them, you should also rename your member function to set_age, set_first_n...
62,303,027
62,303,603
How to initialize a 2D array with all values same?
I want to initialize a 2D array with -1 as all the value. I used memset() for this. #include <bits/stdc++.h> using namespace std; int dp[100][100]; memset(dp, -1, sizeof(dp)); int dynamicProgramming(some parameters) { //I want to use dp[][] array here } int main() { cout<<dp[99][99]; return 0; } But I a...
As others have said, you can't call memset in the global scope. The most correct and clear vay is probably going to be something like #include <iostream> using namespace std; const int D1 = 100; const int D2 = 100; int dp[D1][D2]; void initializeDp() { for (int i = 0; i < D1; i++) { for (int j = 0; j < D2...
62,303,657
62,304,578
How to make linked list with localy declared head?
I need to make a program which connects two linked lists before I used global pointer for the head of the list, but now I need to make it locally so I can insert new element(node) to each of them, but I have a problem with double-pointer, not sure when to use **, when * and when &. I can find any example similar to tha...
There is nothing from C++ in the program except the operator new. So if to substitute the operator new for a call of malloc then you will get a pure C program. So a C looking function insert can be defined like void insert(element **head, int x) { element *new_ = new element; new_->x = x; new_->next = NUL...
62,304,148
62,304,338
What is the easiest way to fill std::array of int with elements of std::array of double with proper casting?
I want to use std::array<double, 4> in function that uses std::array<int, 4>? So, what is the easiest / shortest(both of them) way to achieve that. E.g. #include <array> #include <iostream> void printInts(std::array<int, 4> someInts) { for(int someInt : someInts) { std::cout << someInt << std::endl; ...
If you can't change the function PrintInts, then you could just create an int version of the array, and call the function with that: std::array<int, 4> ints; std::copy(std::begin(someDoubles), std::end(someDoubles), std::begin(ints)); printInts(ints); Be aware that converting from double to int could lose precision du...
62,304,213
62,304,254
How did I get a segmentation fault here while using vectors in c++?
#include <bits/stdc++.h> using namespace std; int main() { vector<int> vect; vect[0]=1; vect[1]=1; vect[2]=1; for (int x : vect) cout << x << " "; return 0; } I would like to know my fault here. I am new to c++ programming. Vectors is a very new concept to me.
vect is an empty vector, so indexing into it invokes undefined behavior. You could allocate enough space for vect, like this: vector<int> vect(3); Or you could push_back the elements: vector<int> vect; vect.push_back(1); vect.push_back(1); vect.push_back(1);
62,304,473
62,305,515
How to pass different variables to same type of QML
I need to pass two different variable to same type of QML, but i did not have success. The variables are "dataTelemetry.target1Trajectory" and "dataTelemetry.target2Trajectory". The following code is a representation of a instantiation of these two same components. Components.SimulatorItem {id: componentTarget1; name:...
If you don't have direct control over dataTelemetry you can use Binding (see qt docs) as such: Components.SimulatorItem {id: componentTarget1} Components.SimulatorItem {id: componentTarget2} Binding { target: dataTelemetry property: "target1Trajectory" value: componentTarget1.trajectory } Binding { ...
62,304,795
62,305,393
Why does std::vector call the destructor while leaving a different scope?
I have some code like this std::vector<cuarl_path::Path> RoverPlanner::get_paths(const char *filename) const { pugi::xml_document doc; doc.load_file(filename); pugi::xml_node root = doc.document_element(); std::vector<cuarl_path::Path> paths; for (auto path_node : root.children()) { std::v...
paths.push_back(*path); this does a few things. It constructs a Path copy from the heap-allocated *path object. It resizes the paths vector. This can sometimes involve just increasing an integer, but at other times it involves moving every existing Path object and destroying the old ones. In the first point, you ha...