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
63,421,525
63,422,035
Can I use custom color for a specific wx[Aui]Notebook tab
I'm triying to color each tab on wxWidgets with a different color, like when you tag an Excel Sheet, is there a way to do that in the C++ version of wxWidgets, with or without AUI?
I don't think there is anything that will let you do this out of the box; but with an Aui notebook, you can write a custom tab art to color the tabs as you see fit. Here's a hideous example that I just threw together to demonstrate one way to do this: // For compilers that support precompilation, includes "wx/wx.h". #...
63,421,630
65,801,667
Where to look at source code of Flutter/Dart "UInt8List"
I am learning and exploring the source code of Flutter. I see UInt8List (and its friends) in sky_engine/lib/typed_data/typed_data.dart. However, there is only declarations (like an interface) without any implementations. I am very curious about its actual implementation, so I wonder where can I see them? My guesses: Th...
Answer by @jonahwilliams: There is additional dart code in *_patch.dart files as part of the Dart SDK. For example: https://github.com/dart-lang/sdk/blob/master/sdk/lib/_internal/vm/lib/typed_data_patch.dart This code contains native declarations like: factory Uint8List(int length) native "TypedData_Uint8Array_new"; W...
63,421,806
63,422,813
Why was std::ranges::less introduced?
On cppreference on std::ranges::less, in notes we can see that: Unlike std::less, std::ranges::less requires all six comparison operators <, <=, >, >=, == and != to be valid (via the totally_ordered_with constraint). But... why? Why would we use std::ranges::less{} instead of std::less{}? What is the practical situat...
What is the practical situation in which we want to less{} only if there are other comparison operators defined, not only the < one? Not everything about the Ranges library is based purely on what is "practical". Much of it is about making the language and library make logical sense. Concepts as a language feature gi...
63,421,926
63,421,979
What is wrong with this C++ main method driver to run this method?
I'm doing C++ this semester (just finished learning Java) and using Codewars to get some practice (this has been my most effective way of practicing but it only requires the method not the driver) with my C++ coding but unsure how to create the driver for this method so I can practice in my IDE. What am I missing here ...
At the point where you try to use is_isogram() in main(), it has not actually been declared yet, hence the "use of undeclared identifier" (a). You can solve this in one of two ways, the first being to declare it with a function prototype before use, such as with: bool is_isogram(std::string); # declare int ma...
63,421,949
63,422,084
How can I use cmake to compile multiple source files and generate multiple executable files named after these file names
Currently, I need help either creating a CMakeList.txt, or simply figuring out the cmake command for the following. I have some source files in the same directory, called A.cpp, B.cpp, C.cpp, D.cpp. I need to compile these such that the executables are named as A, B, C, D, respectively. I want to use CMake to automatic...
This is a bit of an odd request. Usually I'd suggest manually writing add_executable where needed since it's more maintainable. In CMake, there isn't really a good way to collect all files in a directory. You can use file(GLOB ...) to grab all files; but this gets done at configure time, and if you introduce new source...
63,422,124
63,422,207
Initializing a dynamic array with a raw array
I have a dynamic array class, for which I would like to implement a functionality of initializing the dynamic array directly with a raw array, similar to std::vector. struct Array { int *ptr = NULL; int size; int capacity; Array() : size(0), capacity(0) {} Array(int capacity) : size(0), capacity(capa...
This Array array = {1, 2, 3, 4}; is not initializing using a raw array. this uses an initializer list or a uniform initializer. If you want to use a raw array, you must define it firstly, like what follows. I used templates and passing by reference to deduce the size. #include <iostream> #include <algorithm> struct A...
63,422,172
63,422,204
if statement inside of for loop not being executed
Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex: #include <iostream> int reverseNumber(int testNum) { int reversedNum, remainder = 0; int temp = testNum; while(temp != 0) { remainder = temp % 1...
int reversedNum, remainder = 0; You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule. In other words, it should probably be: int reversedNum = 0, ...
63,422,318
63,422,443
How do you input a string of a specific length?
Let's say I were to allow the user to input n. They would then be able to input a string that must have n characters. I don't want to use a loop because the string must be on one line. Would there be a way to do this? This format is what I would prefer. int n; cin >> n; string test; cin >> test[n]; Any help would be ...
You could truncate whatever they input to the first n many characters. #include <string> #include <iostream> int n; std::cin >> n; std::string test; std::cin >> test; test = test.substring(0, n); You could also test the validity of their input, and prompt them to re-enter it if they enter too many characters. int n;...
63,422,324
63,422,373
Is there a way to get the line number with out a macro in c++?
I am writing a logger and I would like the logger to also record which line, function, and file called it. I have tried #define my_logger(format, ...) _log(format, __LINE__, __PRETTY_FUNCTION__, __FILE__, __VA_ARGS__) which works however, this leads to several problems for me (I can't easily overload it, I can't put it...
There cannot be such macro as __LINE_FUNCTION_WAS_CALLED_FROM__. There's no way it could work. Since C++20, there is a way to get the line, function, etc. into a normal function by passing default initialised std::source_location: void log(std::string_view message, std::source_location location = std::source_l...
63,422,467
63,422,482
Unmatched template for simple variadic function in C++?
I am writing a Scheme to C++ compiler (although Scheme is not so related to this question), and I have a set of functions that are invoked in the Scheme code that can be used equivalently in the resulting C++ code. I generated the C++ function "f" (seen below), and I cannot figure out for the life of me why it doesn't ...
The template arguments could be deduced only from function arguments. In this case the 1st template parameter T of f can't be deduced, it's only used to specify function's return type. When possible, the compiler will deduce the missing template arguments from the function arguments. You have to specify the argument ...
63,422,516
63,423,482
Constexpr functions not called at compile-time if result is ignored
I was investigating some rather weird code-coverage results of constexpr functions (compile-time calls can't get instrumented by the code-coverage tool I use), and noticed that some constexpr functions were getting called as runtime functions, if the results of the function call were not stored. It seems that, for cons...
It might be confusing, but constexpr functions should be called at compile time only in constexpr contexts (assignation to constexpr variable, use for array size or template parameter, ...). In regular context, functions are called at runtime. Optimizer might resolve that function at compile time (as for any other func...
63,422,854
63,423,206
Difference between reference binding and type conversion in cpp
If the reference binding(initialization or pass into as function argument) is implicit type conversion. if not, why some casting expression(static_cast, const_cast...) support to cast a non-reference entity to reference and I think it's reasonable to put everything unified. And further more, if reference is a part of t...
C++ is designed considering that coders never make any mistake, so when one pass an argument to a function or initialize a variable, the compiler try to find a conversion that will make the code compile. Those conversions are also considered for reference binding. In the best case, the reference is directly bound to th...
63,423,017
63,423,067
What is the order of execution in these type of cases?
I have defined a macro to find the square of a number. #include<iostream> #define square(x) x*x using namespace std; int main() { int a = square(2+3); cout<<a<<endl; } The output in the above case is 11. I have replaced the expression in the brackets with (3+2) then also the output is 11. Similarly for (4+2) a...
With #define square(x) x*x, this square(2+3) turns into 2+3*2+3. Which of course causes unexpected results because of preference of * over +. The problem does not occur with *, because the order of preference in that case does not matter. You probably want #define square(x) (x)*(x), in order to get (2+3)*(2+3). Or, les...
63,423,659
63,423,825
Getting C2027 use of undefined type 'dlib::image_traits<image_type>' error when using dlib::frontal_face_detector
I am using the latest version of dlib and trying to build a DLL that detects faces using its dlib::frontal_face_detector and dlib::shape_predictor predictor. However, upon trying to use the detector by simply doing : auto faces = this->detector(img, 0); I get this compilation error : Severity Code Description Pr...
The error was kind of misleading, The issue was caused by feeding a cv::Mat to the dlib::get_frontal_face_detector() and dlib::shape_predictor objects, resulting in the stated error. Converting it to the expected type solved the issue: dlib::array2d<dlib::rgb_pixel> img_dlib; dlib::assign_image(img_dlib, dlib::cv_imag...
63,424,326
63,425,267
Why isn't this program crashing? (shallow copy)
I am learning about copy constructor and shallow and deep copy. I was following this video: Copying and Copy Constructors in C++ The following code is copied directly from the video and demonstrates shallow copying... (at 9:30 in the video) This code is supposed to crash after running because the deconstructor will try...
For me (Fedora 32 x86_64) it does crash: $ g++ -o q q.C -Wall -g;./q My string free(): double free detected in tcache 2 Aborted But I definitely agree such code may look running fine. This is why there is ASAN: $ g++ -o q q.C -Wall -g -fsanitize=address;./q My string ===================================================...
63,424,573
63,424,897
User-defined deduction guide for std types
For some reason there is still lack of expected CTAD for std::initializer_list in clang: std::initializer_list l{1,2,3}; // error in clang Adding a user-defined guide like the following can fix the issue: namespace std { template<class T> initializer_list(const initializer_list<T>&) -> initializer_list<T>; }...
Adding a deduction guide to a standard library type is UB [namespace std]§4.4: The behavior of a C++ program is undefined if it declares : [...] a deduction guide for any standard library class template.
63,425,035
63,425,165
How to name class identifier in assignment in c++?
From here: Difference between 'struct' and 'typedef struct' in C++?, I found I need class identifier if there is name collision (for example if class name is the same as function name): #include <iostream> using namespace std; class foo { public: foo() {} operator char const *() const { return "cl...
One of the possible solutions: using bar = class foo; p = bar();
63,425,078
63,440,100
PostgreSQL unable to access
I can't access database from C++ every time it just throws error: FATAL: Ident authentication failed for user "testuser" I had tried: Reinstalling postgresql11 to postgresql12 Creating user Creating database with owner testuser Changing pg_hba.conf localhost from peer to md5 Changing the password of user multiple time...
The problem was that uninstalling Postgres11 and installing Postgres12 left pg_hba.conf with different setting after I restarted service so I needed to change everything to trust in pg_hba.conf to get it to work
63,425,296
63,425,341
Is it possible to create a list of values of member fields using iterators?
Consider the following struct struct Pair { int a; std::string b; }; I have a std::vector<Pair> pairs but I want a std::vector<std::string> listOfBFromPairs which contains all the values of b from the list of pairs. I would like to do this in a one-liner. I have used OpenGL before and I have previously created ...
I want a std::vector<std::string> listOfBFromPairs which contains all the values of b from the list of pairs. I would like to do this in a one-liner? Sure you can. You can use std::transform from <algorithm> header like this #include <algorithm> // std::transform #include <iterator> // std::back_inserter std::vecto...
63,425,357
63,425,654
is there any inbuilt function in c++ for linkedlist that works similiar to indexOf function provided by java?
I am using c++ inbuilt "list", I need to find an index of a value "target", in java there is a function indexOf that solves this problem, is there anything similar in c++? I tried using std::find() but it returns the "target" value itself instead of the index? but I need index of the target value. question: I am given ...
std::list doesn't have random access iterators. What you're looking for is likely the iterator to the object. E.g., #include <iostream> #include <list> using namespace std; int main() { list<int> l{1, 2, 3, 4, 5}; for (auto i: {3, 1, 2, 1}) { auto it = l.begin(); for (auto index = 1; it != ...
63,425,380
63,425,427
Easy way to copy the first nth values of a set into a vector in C++
Simple question, let's say I save a set with 5 values and I want to copy the first 3 values into a vector, is there a fast easy way to do that? I know that if I want to copy an entire set into a vector I can just use something like this: set <int> test = {0,1,2,3,4,5}; vector<int> vect(test.begin(),test.end()); Can I ...
To get an iterator n steps from the begin of a std::set, std::next yields the abstraction you need. std::vector<int> vec(test.cbegin(), std::next(test.cbegin(), 5)); This is due to std::set providing bidirectional iterators, so you can't use arithmetics like test.cbegin() + 5. std::next solves this for you.
63,425,583
63,559,401
RTSP Streaming Server C++
I would like to write a RTSP streaming server using C++. Multiple clients will be connected to this server for receiving the streamed data. What I understand is that I need to do socket programming in C++ for client server architecture. I know FFMPEG has command line support for streaming audio/video. But my requiremen...
I think I will use gstreamer RTSP server. Gstreamer is easy to use. I tried sample example and I was able to stream a video over RTSP.
63,425,723
63,425,752
is there any way to define dynamic array without Determine the size of it
I need a dynamic array that I don't have to scale(Determine) to a fixed number like the following string* s; I have this code so far, but obviously it doesn't work. #include <iostream> #include <string> #include <fstream> using namespace std; int main() { fstream f; f.open("resa.txt"); string* s; int...
It's not automatic, you have to allocate more memory every time you want to resize, copy elements into new array and delete the old one. Fortunately, standard library got you covered with std::vector - an automatically resizable array. #include <iostream> #include <string> #include <fstream> #include <vector> using na...
63,426,071
63,426,305
Eigen RowVector out of scope produces "Run-Time Check Failure #2 - Stack around the variable X was corrupted"
I'm using Eigen library and get this very strange exception: Run-Time Check Failure #2 - Stack around the variable 'myVariableCopy' was corrupted. It's from the following code: void get_new_handle_locations() { int count = 0; for (long vi = 0; vi < V.rows(); ++vi) { if (handle_id[vi] >= 0) ...
The cause of the corruption is that igl::rotate_by_quat calls igl::quat_mult which expects goalPositionCopy.data() to have 4 dimensions, but it's declared as a 3-dimenional vector.
63,426,332
63,426,375
Are preprocessor directives safe for sensitive information?
I am creating an archive which contains HTML/CSS/JS files for my C++ application, and I don't want users to have access to these files. So, i decided to encrypt archive with password. My first thought was to store a password inside a program via preprocessor macro (through CMake). But, is it safe? Can you access the pa...
If the macro is actually used in the application then yes, it's accessible in the executable file -- it has to be for the program to use it. Any credential you embed in your program can be recovered by a sufficiently-motivated attacker. There is no encryption mechanism you can use to prevent this, as you would need to...
63,426,444
63,426,503
C++ what's the best way to make some functions inside source file private?
// myclass.h #pragma once void publicFunction(); //------ // myclass.cpp #include "myclass.h" #include <iostream> void privateFunction() { std::cout << "Hello world\n"; } void publicFunction() { privateFunction(); } //------- // main.cpp #include "myclass.h" #include <iostream> void privateFunction() { ...
If you declare a function in a header file, it's not that private to begin with. If privateFunction is supposed to be an implementation detail, consider declaring it only in the translation unit. To this end, you have two common options. Use an anonymous namespace in the implementation file. namespace { void private...
63,426,460
63,426,514
Problem in writing Goldbach conjecture program
I'm just learning programming and my task was to writce a code in C++ that for given even number would return this number as a sum of two primes. Previously I managed to write a code checking if number is prime or not but as I tried to apply this, my program failed. #include <iostream> using namespace std; int main() ...
Only one small change needed that I can see, you need to set s1 and s2 to zero inside your loop, not just once at the beginning of main. for(int i=0;i<a;++i) { s1=s2=0; ... Now (if you feel like it) rewrite the code using a function called is_prime. This function takes one integer parameter and returns true if...
63,426,740
63,428,588
What are the requirements for window to be blurred, except SetWindowCompositionAttribute call?
I have a dll library that deals with windows: you can simply create windows, draw graphics, etc. Also this library provides you to make blurred windows for Win7 and Win10. I have two almost same builds of library - one , older without sources, and one newer with sources. I am writing some app in Win10 and have been usi...
I do not really understand what I did, but now it works. First of all, I should say, that library provides not just function, but an interface - abstract class. The second one - HWND of created window is actually doesn’t returns, because function that creates window is void. I found window by FindWindow(). GetLastError...
63,426,840
63,427,778
C++ after declaring header file my struct is not recognized
I had this code in a simple file yesterday and it worked perfectly. But now I need to separate the header and the source file. And I did but code gives an error and I don't know why. This is my header #ifndef LISTE_HPP #define LISTE_HPP #include <malloc.h> #include <stdio.h> class Liste { public: struct node { ...
There are a couple of things that you could fix and improve in your code: class Liste { public: // Have a consistent naming scheme. // If Liste is capitalized, why isn't Node? struct Node { int veri; // You don't have to write struct Node, just Node is enough. Node *sonraki; Node *onceki; }; ...
63,426,897
63,427,042
overloading copy assignment operator with classes without a reference parameter name
I wanted to ask a question about operator overloading in C++. I am a beginner in C++ and have been learning OOP. Consider the following overloaded copy assignment operator: class Base { private: int value; public: Base () : value {0} { cout << "Base No-args constructor" << endl; } Base (in...
How does this copy assignment operator work? Redacted: Base& operator=(Base const& rhs) { cout << "Base operator=\n"; value = rhs.value; return *this; } The assignment operator is just a function call. In this particular class's case, the compiler will synthesize one that does the right thing, but if you ...
63,427,188
63,612,774
soci gives fatal error: mysql.h: No such file or directory
When I am trying to compile a program that is using SOCI library I get: /usr/local/include/soci/mysql/soci-mysql.h:31:10: fatal error: mysql.h: No such file or directory I've checked and I have mysql.h in: /usr/include/mysql My CMakeLists file is: cmake_minimum_required(VERSION 3.10) add_definitions(-DUNICODE -D_UNI...
I've solved this problem by using this: https://github.com/Gancc123/flame-sp/blob/c8108823dea205e25abac03942534996710109f3/cmake/modules/Findmysql.cmake
63,427,510
63,427,518
iterators after element deletion in cpp
In c++ , what happens to the iterators when an element is added or deleted. For example, vector is :{1,2,3,4,5,6} and suppose two iterators a and b point to element '2', and '5'. If I delete 3rd item i.e. delete '3', what will the iterators be pointing to ? And if the iterator points to the last element, and that ele...
i guess what you are looking for is iterator invalidation: https://www.geeksforgeeks.org/iterator-invalidation-cpp/#:~:text=Resizing-,a.,it%20is%20supposed%20to%20point. check this link. The summary is: if you delete element in vector, all the iterators pointing to the elements after deleted element gets changed. The ...
63,427,915
63,427,950
What does comparing the result of the three-way comparison operator with nullptr do?
Given the example from cppreference on <=>, we can simplify the example code to: struct person { std::string name; std::string surname; auto operator <=> (const person& p) const { if (const auto result = name <=> p.name; result != 0) { return result; } else { return ...
But my IDE (CLion 2020.2), via clang-tidy, warns that result != 0 should actually be result != nullptr. This is wrong. It should be result != 0. The comparison categories are specified to only be comparable against the literal 0. The check likely comes from the fact that the only real way to implement comparing again...
63,428,344
63,428,453
Counting palindromes
The question was: A contest closes in n days hh hours, mm minutes and ss seconds. Given two values of n, how many palindromes of the format nhhmmss would we find in the indicated interval? Example 1 Input 1 2 Output 472 Explanation We need to check the numbers 1000000 through 2235959 including only numbers where the la...
The std::to_string function does not include leading zeros in the result. Your current code assumes the string is 7 digits but that might not be true and is likely why std::string::substr is throwing an exception for an invalid position.
63,428,352
63,428,476
Using functions with unclear parameters
I want to implement a walk(x,y) function that lets a sprite move up, down, left, or right exactly one unit. The gameboard is stored in an array where each tile is at the index y*width+x. So only knowing the current position, width and x and y, I can instantly calculate the new position (and check for obstacles or other...
If your walk(x, y) function allows putting in more than 1 in distance, this case should also be implemented. Otherwise you would have to check for bad inputs. I would definitely say that it is a bad practice to write functions that are only partially implemented. If you just want to move a single tile, there is a very ...
63,428,620
63,428,831
How to pass an object of a class with a string data member to another class in C++
#include <iostream> using namespace std; class fruit{ private: string name; int amount; float price; public: void getData(){ cout <<"Enter name of fruit: "; cin.ignore(); getline(cin, name); cout <<"Enter amount: "; cin >>amount; cout <<"Enter price: $...
These three variables: fruit obj1; seller obj2; buyer obj3; are created from scratch everytime you loop. Hence the values you enter in iteration 1 are not preserved in the second iteration. The fact that you are getting price and amount correctly is just a coincidence. To fix this quickly, just...
63,428,756
63,428,771
Custom structure as key in unordered_map
I want to use structure Item as key in unordered_map I implemented structures for hash and equal operations. But I have an error hashtable_policy.h:1384:16: error: no match for call to '(const ItemHash) (const Item&)' solution.cpp:28:12: note: candidate: 'size_t ItemHash::operator()(Item)' 32 | size_t operator()(...
You need to const-qualify ItemHash::operator()(Item), i.e., struct ItemHash { size_t operator()(Item item) const // ^^^^ here { // as before... } Note that as @JeJo pointed out in the comments, you need the same fix for ItemEqual.
63,428,818
63,429,284
Building Tensorflow Lite for Edge TPU fails
I am trying to get Tensorflow Lite + EdgeTpu running on ARM in C++, but having issues building Tensorflow Lite with the specified commit from the EdgeTpu Docs. (I have Tensorflow Lite working on latest master of Tensorflow). According to the EdgeTpu docs (https://coral.ai/docs/edgetpu/tflite-cpp), tensorflow lite needs...
Got an answer over the github issues. Putting it here for future reference. Turns out the specified commit has a missing file in the MAKEFILE. Apply this patch: https://github.com/google-coral/edgetpu/issues/201 and build is working.
63,428,829
63,430,981
How can I link 2 files in CodeBlocks without having a project?
I want to use headerfiles (header.h and header.cpp), but I'm not using a project. Is there any way to link these files together, or is making a project the only solution? The problem I encountered right now: main.cpp #include "class.h" int main() { MyClass test; } class.h class MyClass { public: int x; M...
If you are not using a project, then you can't compile it using CodeBlocks. You can compile the code manually, using g++, for example, would be like this: g++ -o myprog main.cpp class.cpp. If you are using another compiler, then you will have to look for the command for it.
63,428,912
63,429,189
How to move a non-copyable element from std::set to std::map using extract?
Consider the following: #include <set> #include <map> struct MyClass { MyClass(int i); MyClass(MyClass const&) = delete; ~MyClass(); bool operator<(const MyClass& r) const { return v < r.v; } int v; }; void map_set_move_test() { std::set<MyClass> s1, s2; std::map<int, MyClass> m1; s1...
This is a problematic example, because MyClass is not merely non-copyable, but implicitly non-movable - which is probably not what you meant. (I think MyClass becomes immovable as a result of you explicitly deleting the copy constructor; see this answer.) If you do make MyClass movable, like so: class MyClass : NonCopy...
63,429,142
63,429,228
How ccache improves building speed?
I am using cmake to setup my project and when I change a file in a project, I found my cmake knows to only recompile the changed file and then relink everything together for the final executable/lib. I then read through the documentation about ccache, what I don't understand is: what is the difference between ccache's ...
Consider the case where you switch to some older branch of your project - that you did compile in the past and that ccache has cached, but CMake sees as "almost all files have changed and must be recompiled" - that's where you see a massive gain. Another situation is where you have deleted your build directory (for som...
63,429,179
63,429,367
Eigen and glm products produce different results
I am trying to replace glm with eigen in an application I am writing, but I am running into an esoteric problem. This would be the relevant code: glm::mat4 EigenToGlmMat(const Eigen::Matrix4f& v) { glm::mat4 ret; ret[0][0] = v(0,0); ret[0][1] = v(0,1); ret[0][2] = v(0,2); ret[0][3] = v(0,3); re...
You are unknowingly transposing matrices. When accessing an Eigen::Matrix4f using (i, j), you are accessing row i and column j. glm::mat4's subscript operator returns you a column, so with [i][j] you are accessing column i and row j. Here's the solution: glm::mat4 EigenToGlmMat(const Eigen::Matrix4f& v) { glm::mat4...
63,429,337
63,429,618
Limit fps in loop c++
I have a simple fps limiter, it work: Clock.h #include <chrono> using namespace std::chrono; class Clock { high_resolution_clock::time_point startTime; public: Clock(); duration<double> restart(); }; Clock.cpp #include "Clock.h" Clock::Clock() : startTime(high_resolution_clock::now()) { } duratio...
Don't use sleep_for. Use sleep_until instead. This will average your drift from the desired frame rate out to zero. This is done by sleeping until the start of the current plus the desired frame duration. Use system_clock so that your frame rate stays accurate over a long period of time. No clock is perfect. But...
63,429,610
63,429,672
C++ while loop not terminating even after condition becomes false
I have written a heap building function that builds a max heap in an array. It starts from the last node and checks for each node moving up. It its on node 'a' currently, it checks for left and right children and if they exist and have value greater than 'a' then 'a' is swapped with largest of the immediate child nodes...
Inside the loop, you have int l= (2*i<=n)?arr[2*i-1]:INT_MIN; int r= (2*i+1<=n)?arr[2*i]:INT_MIN; This declares and initializes new variables l and r, local to the loop's body, and distinct from and unrelated to variables with the same name declared outside the loop. Those "outer" variables remain unchanged. Your comm...
63,429,620
63,429,742
Why do we need function definition before calling it in C++?
Hello to all I am new to C++ language and I came across with interesting fact that we cannot call function before defining it. I have searched on stackoverflow but couldn't find proper answer. I am thinking why just declarations are not enough to call a function because linker can check the parameter list from declara...
Short answer: You don't need a function definition to compile your code, but you do need a function definition to link it (and execute it of course!). Some clarifications, trying to keep things simple: The declaration of a function is what it takes, what it returns The definition of a function is its content Compilin...
63,429,760
63,429,828
Can a concept be checked against incomplete type
I stumbled upon this: #include <type_traits> #include <concepts> template<class T> concept IsFoo = requires(T a) { {a.a} -> std::same_as<int>; }; #if 1 // Will not compile, because Foo currently has incomplete type template<IsFoo AFoo> struct AcceptsFoo {}; #else template<class AFoo> struct AcceptsFoo {}; #endif ...
You can check a concept against an incomplete type - but if that concept check requires actually doing anything with the type that requires it to complete, that's going to fail the concept check. And even there, you have to be careful since implementations are allowed to (and will) cache concept checks to compile faste...
63,429,875
63,639,421
No instance of overloaded function winrt::Windows::UI::Xaml::Controls::Primitives::SelectorItem::Content matches the argument list
In C++/CX, I was able to do: Windows::UI::Xaml::Controls::Primitives::SelectorItem item; const wchar_t* str = L"someString"; item->Content = str; But, when I do the equivalent in C++/WinRT, winrt::Windows::UI::Xaml::Controls::Primitives::SelectorItem item; const wchar_t* str = L"someString"; item.Content(str); I get ...
The Content function expects something of type IInspectable, wchar_t is this not though. If you pass "primitives", you need to box them. The following works: winrt::Windows::UI::Xaml::Controls::Primitives::SelectorItem item; const wchar_t* str = L"someString"; item.Content(box_value(str));
63,430,570
63,430,582
Empty string after passing through the function
I got an empty string on the first element of the array ("") while the others are correct. It seems that the string object is destroyed right after exiting the function. Is it not related to Dangling pointer? How to solve it? void func(const char**&ptr) { std::string errorstring = "Test1"; ptr = (const char **)...
ptr[0] is set to point to a buffer managed by errorstring. When the function returns, errorstring goes out of scope and is destroyed, deallocating that buffer. ptr[0] becomes a dangling pointer. Any attempt by the caller to dereference it would exhibit undefined behavior.
63,430,704
63,430,933
C++ Reading text file line by line
I want to read a txt file and I want to process each number on the line one by one, apply some functions and pass to the other line. When the line is over, I don't know how to apply the same operations to the lines below. Methods will get a different output from each line that is why I have to handle each line separate...
Working C++ Code To clear doubts Test it in https://www.tutorialspoint.com/compile_cpp11_online.php Just copy-paste execute #include <iostream> #include <string> #include <sstream> #include <fstream> int main () { //code create a file with numbers std::ofstream myfile; myfile.open ("file.txt"); my...
63,430,871
63,431,015
How to put a string of numbers seperated by whitespaces to an array?
I have a code that gets a string of numbers that is separated by whitespace like: "19 210 67" And separates them and prints them out. But the thing is I want to put three them into an array one by one so I have an array of strings like: ["19","210","67"] How can I achieve that? Thanks. Heres my C++ code: std::strin...
Try boost split (found in #include <boost/algorithm/string.hpp> ), here is an example with tab delimiters: string input("hello world"); vector<string> result; boost::split(result, input, ' '); Alternative just declare a vector and push_back the tokens in the for loop of your code?
63,431,071
63,431,128
Why standard does not provide specialization for hashing c strings with content examination
I am reading about hashing and I found following statement in here: There is no specialization for C strings. std::hash<const char*> produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array. Why there is no mechanism that hashes C strings that examine t...
A specialization is not possible because "C-strings" are just pointers with the implication that they're null-terminated. A const char * could just as well be a pointer to some raw byte data, not necessarily a C-string. You simply can't assume that all const char * are null-terminated. Your suggestion with std::string_...
63,431,099
63,431,317
Is it possible to create new funcitonality for classes in a library (Eigen) without editing the source file? (C++)
Context I was forced to switch from glm to Eigen only because eigen can handle dimensions beyond 4 and I don;t want to have 2 different lin alg libraries at the same time. As far as usability goes, Eigen is infinitely times worse than glm. Consider the simple operation of concatenating 2 vectors: GLM: vec4(v1, v2); Eig...
The functionality you are looking for is Extension Functions. Some languages such as Kotlin have them, but C++ doesn't. So you're out of luck. If you created your own vector library, it would be no problem, because you could then create a constructor that implicitly converts from other vectors and an operator that impl...
63,431,283
63,431,453
Duktape - error with for of loop when evaluating
With the following code duktape gives me a parse error for the for of loop. string script = u8R"(var foo = [ "foo", "bar" ] for (var bar of foo) { print(bar); } )"; if (duk_peval_string(ctx, script.c_str()) != 0) { printf("eval failed: %s\...
The solution to this was to run it through BabelJS. This was due to for...of being added in Es6 which is not supported in Duktape.
63,431,332
63,431,363
C++ no default constructor error when passing one class into another's constructor
I'm writing some C++ classes where one class has an instance of another class as an attribute. When writing the class constructors I keep getting the error "no default constructor exists for class Foo". Here's a small example reproducing the error: class Foo { int size; char name; Foo(int s,char n) { ...
You should be initializing via initialization lists, not via assignment. // You probably want these to be a struct, not class. // This way all members are public by default. struct Foo { int size; char name; Foo(int s,char n) : size{s}, name{n} {} }; struct Bar { int size; char name; Foo foo; ...
63,431,365
63,431,471
Is the a way to compare vector to be equal to part of another vector in C++?
If I have: A = {"one", "two", "three"} B = {"one", "two"} I want to avoid creating a new vector from A. Is there a way to use [A.begin(), A.begin()+1] to compare with B?
There is a version of std::equal that could do: template< class InputIt1, class InputIt2 > bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); https://en.cppreference.com/w/cpp/algorithm/equal
63,431,466
63,431,507
Why does iterating unordered::map and adding new elements does not lead to an infinte loop?
I am iterating through a std::unordered_map std::unordered_map<int, char> mp; mp[0] = 'a'; int i = 1; for(auto it=mp.begin();it!=mp.end();it++) { cout<<it->second<<" "; mp[i++] = (char)(97+i); } Output a Now as a new element is being added at the end of each iteration I assumed...
Inserting new elements invalidates your iterators at some point, however, you use them again, hence UB For details, See Iterator invalidation rules and iterator invalidation in map C++ To see such behavior, use the following code #include <iostream> #include <unordered_map> int main(){ std::unordered_map<int, cha...
63,431,741
63,431,836
Invoking a function on a QThread that is already running
I have seen a lot of examples on the internet (and the Qt documentation) where to use QThread, a subclass of the class is made and then a worker object is moved to that thread. Then essentially the QThread::started() signal is connected to some slot of the worker class object to run a certain function. Now I would like...
If "doStuff" is a slot then you can use QMetaObject::invokeMethod: QMetaObject::invokeMethod(&worker, "doStuff", Qt::QueuedConnection, Q_ARG(int, 5));
63,431,813
63,431,853
sizeof union giving unexpected results
I have read that the sizeof union gives the largest size of member in the union.But when i do this:i'm getting unexpected results: #include <iostream> using namespace std; union RecordType { int arr[9]; double x; }; int main() { RecordType t; cout << sizeof(t); //output is 40,instead of 36 (9*4bytes...
Because double is a 64-bit type on your backend, the compiler will pad the size of the union with additional 32 bits or 4 bytes to align the ints and double. This way the union is aligned to 64 bits, regardless of what member is active. If you created a union with a float instead, it would most likely have a size of 36...
63,431,833
63,432,587
Getting data into a uint8_t array (C/C++) on Arduino
I'm working in C/C++ on Arduino and am having trouble getting what I need into an array of type uint8_t. C/C++ is not a language I'm familiar with (I'm a python / php / basic guy), so I'm struggling with finding the right terms / docs at the moment. Basically, the following is show in an example, and works: static uint...
For embedded code, compactness is the key. Use user-defined structure like so. struct Temperature{ uint8_t temp[7]; uint8_t humi[7]; Temperature(){temp[0] = humi[0] ='\0';} Temperature(uint8_t * t, uint8_t *h){strcpy(temp,t); strcpy(humi,h);} void reset(){ temp[0] = humi[0] ='\0';} void setTemp(uint8_t* t...
63,431,915
63,431,951
C++ Separate "if" statements don't work but nested "if" statements do
I'm working through Programming Principles and Practice Using C++ and have run into an issue with multiple "if" statements within a while statement. In short, I run the following and the final "if" statement outputs each iteration regardless of input: int main() { int i = 0; double a; double b; constexp...
Ratio value is 0.01. Any 1 of A-B or B-A will result in a negative value which will anyways be less than ratio. if (((a-b) < ratio) || ((b-a) < ratio)) You might need to change this condition to absolute value. #include <cstdlib> // for abs()function if (abs(a-b) < ratio)) { cout << "Also, the numbers are almost ...
63,431,928
63,507,482
persistent overflow error with 64bit dll in ctypes
I am trying to work with a 3rd party DLL file to control a hardware (translation stage in my case). I have windows 10, 64 bit python (with Jupyter notebook). I have imported the correct version (64-bit) of dll file like this: import ctypes, sys PiUsbDll = ctypes.WinDLL("PiUsb") I have a copy of C++ header file for the...
I figured the problem was related to the 64 bit 3rd party DLL files in my case. I have switched to 32 bit DLL files where the same python code works.
63,432,176
63,432,202
how can l-values be passed to std::make_pair
In std::make_pair there is only one implementation C++14 onwards template< class T1, class T2 > constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u ); Both parameters are R-value references and according to this R-values references cannot be initialized with l-values. int i = 1; char ch = 'a'; std::uno...
The parameters of make_pair are not declared as rvalue-reference, but forwarding reference. Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward. Forwarding references are either: function parameter of...
63,432,669
63,432,718
Why does std::pair have two different constructors for both const reference and forwarding reference parameter?
From ISO standard (precisely N4860) std::pair synopsis: constexpr explicit(see below) pair(const T1& x, const T2& y); // first constructor template<class U1, class U2> constexpr explicit(see below) pair(U1&& x, U2&& y); // second constructor I can't seem to find any reason why the first constructor should be defined ...
In which case does first constructor win in overload resolution? It wins when being passed const lvalues with the exact same type with members of the std::pair, i.e. const T1 and const T2. Both the constructors are exact match and non-template one would win. E.g. const int i = 0; const int j = 0; std::pair<int, int> ...
63,432,962
63,432,998
How to work : sort function's third argument. [arr], []
sort(arr.begin(), arr.end(), [arr](int& a, int& b) {}); // #1 - TLE sort(arr.begin(), arr.end(), [](int& a, int& b) {}); // #2 - not TLE What is the difference between [] and [arr], and why does TLE #1 occur?
Assuming TLE is time limit exceeded for some online coding/competition site, [arr] will capture the collection as a copy so that it's accessible to the lambda (a comparator for the sorting logic). For a big enough collection (or a small enough timeout), this could cause an issue. You really don't need to capture the ar...
63,433,069
63,434,237
VkWin32SurfaceCreateInfoKHR not available after specifying extensions with glfwGetRequiredInstanceExtensions
I'm using Visual Studio 2019 Community with C++17 and Vulkan SDK 1.2.148.1 #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> //other vulkan stuff here VkInstance instance; uint32_t count; VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.ppEnabledExtensionName...
VkWin32SurfaceCreateInfoKHRis platform specific for windows, so in order to use it you need to define VK_USE_PLATFORM_WIN32_KHR somewhere in your project.
63,433,171
63,433,366
Picking lexicographically smaller
Question : https://www.geeksforgeeks.org/find-winner-election-votes-represented-candidate-names/ Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller nam...
winner>key is a lexicographical comparison. It's true if key is lexicographically less than winner (I do think it would have been less confusing to write it the other way around key<winner). So the code is saying that if the score just found is equal to the best score found so far and if the candidate just found is lex...
63,433,214
63,433,393
How does setting a variable inside while parenthesis work?
I found a piece of code that I'm debugging and it looks like I don't understand how a while loop works entirely on C++. Take a look: while (_content_len == 0 && _remain_data_size > 0 && (index = onSearchPacketTail(ptr,_remain_data_size)) != nullptr) { std::cout << "hello" << std::endl; } If I see 10 h...
How does setting a variable inside while parenthesis work? Parentheses work similarly to how they work in mathematics. The operators within parentheses have higher precedence than the operators outside. If I see 10 hello on the output, is it true that onSearchPacketTail got called 10 times? Yes, it is potentially t...
63,433,446
63,434,087
Rotate Matrix and Delete Characters and Find largest Square
A company manufactures walls which can be directly implanted at the site. The company uses small square bricks of material C and material D which have similar looks but have huge difference in quality. The company manufactures walls of square shapes only to optimize their costs. A novice employee created a square wall ...
I don't know exactly what data structure you get the wall in, but assuming it is: std::vector<std::vector<char>> wall; To be able to perform melting using std::sort, it is best to have columns in the outer vector and rows in the inner vectors. // melting bricks for (int col = 0; col < wall.size(); ++col) //column of b...
63,434,281
63,434,333
Assign object to a member variable in C++ class constructor
I'm getting error: use of deleted function ‘PropertyLink& PropertyLink::operator=(PropertyLink&&)’ When I try to assign an object to a member variable in the class constructed. I have 2 class definitions, PropertyLink and NodeBlock. and I want to create an object of PropertyLink inside NodeBlock when constructing a No...
It seems the copy/move assignment operator of PropertyLink is not usable. You can (and should) initialize properties directly instead of assigning it in constructor's body. You can use member initializer list. class NodeBlock { public: PropertyLink properties; NodeBlock(unsigned int propRef) : properties(pro...
63,434,407
63,434,534
Convert std::string to STRSAFE_LPCWSTR in an utility method
I'm relatively new to C++ and I'm trying out Windows Notification using Win32 API. This is the method I have: BOOL Notification::ShowNotification(std::string title, std::string info) { NOTIFYICONDATA nid = { sizeof(nid) }; nid.uFlags = NIF_INFO | NIF_GUID; nid.guidItem = __uuidof(AppIcon); nid.dwInfoFlags...
You need to move all three lines of the repeated code into a small utility function. static void Notification::ConvertToLPCWSTR(const std::string& input, LPWSTR result, size_t result_max_size) { std::wstring wInfo = std::wstring(input.begin(), input.end()); const wchar_t * wchar_Info = (STRSAFE_LPCWSTR) wInfo.c_str...
63,434,440
63,434,656
Create a template to iterate map in C++11 like C++17's structured bindings
C++17 brought us a nicer way to iterate through map using the Structured binding, as shown in this example . I am bound to use C++14 but have a lot of repeating code that iterates over maps. In C++14 it looks like this: for (auto const& item : myMap) { std::string key = x.first; int value = x.second; //Code...
You cannot initialize variables inside the range-based loop until C++20, so the best option, that I can see to use such macro: #define STRUCTURED_BINDING(a, b, map_item) \ const auto &a = map_item.first; \ const auto &b = map_item.second; So then in your code, you can write something like that: for(c...
63,434,478
63,434,552
How does the output operator know the size of an array of chars?
The book C++ Primer states the following: Because arrays are passed as pointers, functions ordinarily don't know the size of the array they are given. They must rely on additional information provided by the caller. The options described include using an end marker character, using a pointer to the position one pas t...
You just got lucky with the memory layout and had an accidental null-terminator. On VS2019 I get an output of: foo bar╠╠╠╠╠CÌ╦À<³3☺33Ò Try popping in: std::cout << sizeof(line) << '\n'; and std::cout << sizeof(str) << '\n'; and you'll see the difference between the pointer size and the array size. Further explanatio...
63,434,544
63,439,342
qt opencv can't read the image
I'm quite new around the qt creator and I'm sick of it's building errors and tones of undefined errors. Eventually i installed opencv3.2 with no error. Noti can use opencv libraries but i can't read the files like "image.jpg". I tried everything. Path is %100 correct slashes are correct. There were no error during the ...
I solved the problem by installing Opencv 4.4.0 . It was a little bit hard to install but i figured it out thanks for replies.
63,434,605
63,434,846
Problems returning const char* from function
First, thanks for taking some time helping me. I am working on Arduino, and the thing is that I need to return a const char* on a function. What I need to do is to create a String and send the response back. Things like this are not working: ... String myVar= "Return Message"; return RPC_Response(myVar); } This didn't...
First of all, you could simplify your code to the following: std::string myVar= "Return Message"; return RPC_Response(myVar.c_str()); This will not work though, because the result of c_str() gets invalidated when a string gets modified, including the string being destroyed. The reason using a string literal w...
63,434,710
63,467,707
Why inplace Tensor methods are const in Torch C++ API?
I see that many inplace Tensor operations like mul_ and div_ are const in PyTorch C++ frontend: Tensor &mul_(Scalar other) const It seems to be strange since inplace operations are supposed to modify the tensor data, right? Does anyone know what is the rationale behind making them const? I've found some discussions on...
As underlined by the comment and by this thread, this const is disingenuous because it applies to the pointer to the underlying TensorImpl, not to the data itself. This is just for compiling optimization and carry no real semantics here. This is similar to the difference between const int*(pointer to const int) and int...
63,434,750
63,434,831
Sort array using Recursion segmentation fault core dumped
I have been using recursion lately and tried to sort array using the same, though using recursion to understand it well. I have declared all the neccesary functions here #include<iostream> #include<stdlib.h> #include<vector> void insert(std::vector<int>&,int); void sort(std::vector<int>&); void getArray(std::vector<in...
in insert when ((array.size()==0)||array.at(array.size()-1)<=temp) is true you need to only array.push_back(temp) and not to do the rest of the function else you recurse without ending and have a stack overflow so for instance : void insert(std::vector<int>& array,int temp) { if ((array.size()==0)||array.at(array.siz...
63,434,800
63,458,943
What is a C++ implementation or analogue of the local peak detector skimage.feature.peak_local_max?
I need to find local peaks on the depth image to generate the markers for a watershed algorithm in C++. My Python implementation uses skimage.feature.peak_local_max to generate the markers for a watershed algorithm. Can't find a C++ implementation or C++ analogue of the skimage.feature.peak_local_max function. Some alg...
If you want a pure C++ implementation, I would suggest taking a look at ITK. The RegionalMaximalImageFilter class from ITK will produce a binary image with the foreground representing local maxima. It even works for "flat" regions where the local maximum is constant. This link shows an example: RegionalMaximal Original...
63,435,065
63,435,153
What purpose do access specifiers for nested class serve?
Suppose I have a class A with a private nested class B. As I understand it, that means B is not part of the public API. Does that mean that the public and private access specifiers only server the programmer rather than the user? Are there ways that I might accidentally give the user access to public data members of a ...
Having a private nested class does not mean that you can't accidentally make it available to the "user": #include <iostream> #include <type_traits> class A { private: class B { public: int x = 2; }; public: B getB() { return B(); } }; int main() { A a; // a returns B so you have access to the pub...
63,435,253
63,435,528
functor and function at priority_queue and sort of C++
I try to understand use of functor and function at C++ Please see the code below #include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; bool mySort(int a, int b){ if(a > b) return true; return false; } class myClass{ public: bool operator()(int a, int b){ ...
When you instantiate a priority_queue, the third argument must be a type. greater<int> and myClass are types; greater<int>() and mySort are not. If you create a default priority_queue, it will default-initialise an ordering of the indicated type. priority_queue<int, vector<int>, greater<int>> aa; is equivalent to prio...
63,435,484
63,471,284
MSVC: Invalid memcpy optimization?
Consider the following code: void MemMove8(void* dst, void* src) { char tmp[8]; memcpy(tmp, src, 8); memcpy(dst, tmp, 8); } MSVC (16.7.1) x86 with /O2 generates the following assembly for this function: ; _dst$ = ecx ; _src$ = edx mov eax, DWORD PTR [edx] mov DWORD PTR [ecx], eax mov eax, DWORD...
It's a bug. https://developercommunity.visualstudio.com/content/problem/1151407/incorrect-memcpy-optimization.html This seems to have been fixed in VS 16.8.
63,436,151
63,437,158
Increase global memory for variables in Windows
#include <iostream> int mainarr[500000050]; int P[500000050]; int main() { cout << p[100000]; } Above code works fine on MAC but crashes in windows. Why Does mac happen to have more memory space for global variables than windows(Not tested on linux till now). How can I increase the size on windows.
Global and static variables are defined in the Data Segment of the program's memory. I suggest reading about it on wiki. Allocating such big buffers, either on the stack or in the data segment is a really bad practice. (sorry for not being more polite, but it should be avoided at all costs!) Probably Mac-OS allows big...
63,436,316
63,480,678
Multiplying 1xn Eigen::Array with 2xn Eigen::Array, with each column in the 1xn array behaving like a scalar
I have two Eigen::Array which have the same number of columns. One of them, a, has one row, and the other, b, has two rows. What I want to do, is to multiply every column of b with the entry in the respective column in a, so that it behaves like this: ArrayXXd result; result.resizeLike(b); for (int i=0; i<a.cols(); ++i...
Eigen provides the possibility to use broadcasting for such cases. However, the one-dimensional array should first be converted into a Vector: broadcasting operations can only be applied with an object of type Vector This will work in your case: RowVectorXd av = a; ArrayXXd expr = b.rowwise() * av.array(); Edit To...
63,436,383
63,439,098
Are there any mechanisms other than copy elision that can optimize out excessive construction in C++?
My function has a switch-case statement. There is an object that is used only in some of its branches. Can I put an initialization of this object before the switch-case statement and expect that it will be created only when it is actually being used. By that, I mean, is there any difference in performance between this ...
Can I put an initialization of this object before the switch-case statement and expect that it will be created only when it is actually being used. No. There is no mechanism in the C++ standard that will permit an object which is stated in the text to be created to only actually be created based on runtime informatio...
63,436,972
63,437,054
Calculating height of binary tree as a void function
I'm learning C++ and trying to write a void function that will calculate the height of a Node. The function has to be of void type so it cannot return anything but should calculate the height of the node correctly. Below is my code: void computeHeight(Node *n) { if (!n->left && !n->right){ n->height = 0; } e...
I assume you are not allowed to change function return type (even though it enforces a rather strange implementation) You cannot add 1 to result of computeHeight, because the latter returns nothing at all. However, computeHeight does something. It has so called side effect. This effect is "after completion of computeH...
63,437,091
63,437,382
How does the '->' operator work and is it a good implementation to modify a large string?
I want to begin with saying that I have worked with pointers before and I assumed I understood how they worked. As in, int x = 5; int *y = &x; *y = 3; std::cout << x; // Would output 3 But then I wanted to make a method which modifies a rather large string and I believe therefore it would be better to pass a reference...
str is a pointer to std::string object. The arrow operator, ->, is used to dereference the pointer and then access its member. Alternatively, you can also write (*str).replace(0,1,"s"); here, * dereferences the pointer and then . access the member function replace(). Pointers are often confusing; it is better to use re...
63,437,236
63,437,296
Why passing local object to initialize another object is fine but passing reference of a local object to initialize another object is not
I wrote the following code. #include <iostream> using namespace std; class Cat { public: int itsage; }; Cat myFunction() { Cat Frisky; Frisky.itsage=2; return Frisky; } int main() { Cat Mani=myFunction(); cout << Mani.itsage; cout << endl; return 0; } Output 2 Then I wrote the following code. #include...
You have a misconception in steps 2 and 3 in both descriptions. The actual order is: return Frisky is executed which returns a copy of (code 1) or reference to (code 2) the local variable. The function ends and all local variables are destroyed. This does not affect the return value in code 1. Mani is initialized with...
63,437,314
63,437,516
TCP/IP socket receives random big number
I am trying to make a client-server application in C++ using TCP/IP sockets, but when I am trying to receive data from the server the client receives a random big number, even if the server didn't send it. On the server side I am first receiving client's user and after I am sending server's name and user's role: std::s...
Within send_message, you are using sizeof(message_left.c_str()) for the message length. That's the size of a pointer. You probably want message_left.size() instead: bytes_sent = send(socket, message_left.c_str(), message_left.size(), 0); Within recv_message, you're using message_size where you probably want to use the...
63,437,513
63,437,654
Why cant I use std::copy with std::string to another std::string?
The following code prints an empty string and i am unable to understand why it is so? #include <string> #include <algorithm> #include <iostream> int main() { std::string s="hello"; std::string r; std::copy(s.rbegin(),s.rend(), r.begin()); std::cout<<r; return 0; }
The problem is r is an empty std::string, it contains no chars. std::copy is trying to copy-assign chars since r.begin(), which leads to UB. You can make r containing 5 elements in advance. std::string r(5, '\0'); Or std::string r; r.resize(5); Or use std::back_inserter. std::string r; std::copy(s.rbegin(),s.rend(), ...
63,437,538
63,438,091
Error:Line 924: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
I am trying to solve the leetcode problem maximum profit scheduling. I think there is no mistake in my logic but I don't understand why I am getting the above error.I have spent quite some time on it trying to understand the error I have run it on my local ide and I get a segmentation fault but I wasn't able to spot w...
This'll pass, similarly O(N Log N) runtime and O(N) space using map: // The following block might trivially improve the exec time; // Can be removed; static const auto __optimize__ = []() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); return 0; }(); // Most of headers are ...
63,437,726
63,448,527
MinGW GLEW undefined references
When I compile my OpenGL project, I get warnings, then errors: (Note: The log is too large for Stack Overflow, so I had to submit it to Pastebin, but it also exceeds the 512k limit for Free users, so I had to split it into multiple pastes: https://pastebin.com/4P8HrVs9 https://pastebin.com/NyLn2KWZ https://pastebin.com...
The problem that causes those warnings is that you are including a .c file, specifically #include <glew.c>. You should always only include .h files, unless you know what you are doing and even then it's not advisable. There is difference between definitions and declarations in C++. Each variable, function and class can...
63,437,728
63,439,344
How to reference package from Conan recipe on github
I have a C++ (Windows, MSVC) project and I'm using Conan to manage external dependencies. So far, I've been adding dependencies by including them under [requires] in my conanfile.txt. I'm relatively new to Conan. Now I'm trying to reference the following package: https://github.com/firefalcom/bgfx-conan This package is...
Figured it out. You need to clone the repository locally, then run: conan create . To install the package. Then you can reference it in your conanfile.txt based on the package name and version specified in the conanfile.py. So for me, it is bgfx/7188.
63,437,992
63,438,267
C++ - Return by value behavior
I'm trying to learn how copies work when a function returns by value. I'm confused by the following piece of code: #include <iostream> using namespace std; class X { public: virtual ~X() { cout << "~X() " ; } X() { cout << "X() "; } X(X const& other) { cout << "X(X const&) "; ...
Here's the optimization that I believe is taking place for g() but not for f(). Non-mandatory elision of copy/move (since C++11) operations: In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and wh...
63,438,262
63,438,451
No output from cout When assertion Fails
Cout fails to print anything even though it is on a line before the assertion. It behaves so when I compile and run the code through linux shell. But it prints when tried with an online compiler. ex- for(int i =0;i<n;i++) { std::cout << "should print"; assert(2==1); } I should see "should print" at least once r...
Output from std::cout is probably being buffered here. Explicitly emptying the buffer should make it print before the assertion fails. (std::endl,std::flush, std::unitbuf manipulators should do) for(int i =0;i<n;i++) { std::cout << "should print" << std::endl; assert(2==1); }
63,438,685
63,438,727
warning: character constant too long for its type car.second = 'Sarim';
I want to make a pair of int and string. As: pair<int,string> car ; car.first = 10; car.second = 'Sarim'; cout<<car.first<<endl; cout<<car.second; "sarim" is converted into 'm' in output?
Use car.second = "Sarim"; The second of the pair is an std::string, not a character, hence you can provide an std::string or const char* to be used to construct one. Note that the single quotes are for characters while the double ones I used make a const char* which can be used to construct an std::string Demo
63,438,899
63,440,756
LLVM ERROR: MCJIT::runFunction does not support full-featured argument passing
I have got an example from here and I faced with a run error LLVM ERROR: Target does not support MC emission! which I fixed it by this. nevertheless, I still observe runtime problem: ./example 3 5 LLVM ERROR: MCJIT::runFunction does not support full-featured argument passing. Please use ExecutionEngine::getFunctio...
From the documentation of MCJIT::runFunction: For MCJIT execution engines, clients are encouraged to use the "GetFunctionAddress" method (rather than runFunction) and cast the returned uint64_t to the desired function pointer type. However, for backwards compatibility MCJIT's implementation can execute 'main-like' fun...
63,438,975
63,439,105
How to use mutex in loops properly in c++?
I'm new for threads and mutex and ı trying to learn them. I write some code that generally create a queue that enqueue all of the numbers from the file ( this file has nearly 20.000 lines and lots of information) since this file contains a lots of information for procees ı need to have multithreads, at the beginning us...
Note: std::this_thread::get_id() is a function, so you should be calling it. I assume this is just a copy/paste error. If I add some work between opening and closing the queue, i clearly see two threads using the queue. I don't think you have any issue with the code shown. #include <iostream> #include <thread> #include...
63,439,263
63,439,321
Why compiler cannot deduce template template argument?
I want to write a function that takes a generic container with any type and prints it. Let's leave for a moment that it won't work for some associative containers and focus on the issue: template<template<typename> typename Cont, typename T> void print(const Cont<T>& cont) { for (const auto it : cont) { cou...
std::vector has more than one class-template-args. template< class T, // -----------> you have mentioned! class Allocator = std::allocator<T> // -----> this didn't! > class vector; But you have provided only one. This is the reason for the no matching overloaded compiler error. In order to fix ...
63,439,725
63,440,186
quick sort not working returning same array
Part method is not doing anything it outputs same array as entered and i don't know whats wrong void part(int array[100], int start, int end){ int pivot = array[start]; int i = start; int j = end; int temp, temp2; // i to swap elements greater than pivot // j to swap elements less than or equal to pivot w...
You call part only if if(start < end){ part(array, start, end); but then you do int i = start; int j = end; while(i > j){ So, it is expected this will do nothiong. The while will never enter.
63,439,855
63,440,203
How do destructors work in a simple program?
I don't understand the output of this program : class A { public : A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } }; A f (A & a) { return a; } int main() { A a ; a = f(a); return 0; } I expected A() ~A() because I only created one A object : a. However, the output is A()...
You only created one object explicitly, but you are creating one object here: A f (A & a) { return a ;} //when returning A as you are copying the object to pass it back from f, that copy is being constructed by the default copy constructor as you didn't provide one. If you change your class to this: class A { public :...
63,440,160
63,445,022
Update a QLabel (several times) inside long running on click button function (slot)
I am creating a graphical interface to a console program. The program executes orders and periodically updates a QLabel. The problem is that I can't get it to update dynamically, the function executes correctly but the QLabel is not updated until the end of the execution. void MainWindow::on_pushButton_10_clicked() { ...
The problem is that I can't get it to update dynamically, the function executes correctly but the QLabel is not updated until the end of the execution Widgets execute in the same thread, something Qt refers to as main thread. Which means when you call sleep, you freeze the graphic thread. This explain why nothing hap...