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,385,107
62,385,201
Completely lost with C++ (First week learning)
I just started learning C++ in my Into to C++ class. My professor is not in the slightest bit helpful or return emailed questions. So here I am , looking for help on my first assignment. I truly want to learn, and don't want anyone "doing" my assignment for me, but I desperately need help trying to figure out where I ...
Must prompt for the name of the gaming programs, and their prices. You want to input the name of the games, so you must be reading the input into a string and not int datatype as you did in your program. Just change the variable a, c, e to the datatype string instead of int and your program would run fine. Next, it...
62,385,120
62,385,232
Cmake: setting rpath
I'm trying to switch from GNU Make to CMake on a C++ project. My plan is to distribute alongside the source code of my library, also the code of two external libraries that are needed. The project is structured as follows ├── CMakeLists.txt ├── lib │   ├── lib1 │   └── lib2 ├── main.cpp └── src ├── CMakeLists.txt ...
The commands in cmake are rather literal. Try: target_link_directories(bayesmix PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/lib/lib1/lib/tbb ) target_link_libraries(bayesmix PRIVATE tbb pthread ${PROTO_LIBRARIES} )
62,385,131
62,385,372
Passing 2D array as an argument
I am running my code but getting this error and I don't know how to deal with it. My code: #include<bits/stdc++.h> using namespace std; #define ll long long int #define LIMIT 5 int m; void dfs(int i,int j,int k,int kk,int mat[][1000],bool vis[101][101],int n,int m) { if(i<0 || i>n-1 || j<0 || j>m-1) return...
You have a typo in the function call, it's missing a parameter, 4 int parameters are necessary before the 5th parameter, a 2D array, I'm guessing you forgot to include the 4th parameter kk. That what's causing that compilation error. Fixing that won't solve your problem because you can't pass an array with dimensions (...
62,385,274
62,385,617
Use universal reference for operator= instead of multiple overloads
Have a simple wrapper struct template<typename T> struct named_value { using type = T; T value{}; string_view name = "unnamed_value"; constexpr explicit operator T&(){ return value; } constexpr explicit operator T const&()const{ return value; } constexpr explicit operator T &&()&&{ return std::...
It's a problematic implementation. The problem is that it may interfere with regular assignment. The compiler generates operator=(name_value const&v) for you, and it takes by a const reference. But when the source object is non-const, the overload generated from the template specialization becomes a better match. For i...
62,385,357
72,572,178
C++20 modules on clang (Windows): typeinfo error in simplest example
File first_module.cppm export module first_module; int foo(int x) { return x; } export int e = 42; export int bar() { return foo(e); } Pre-compiling (no problems): $ clang++ --std=c++20 -fmodules --precompile first_module.cppm -o first_module.pcm Compiler information: $ clang++ -v clang version 10.0.0 Target: ...
The core problem resides in that your current Clang installation it's working with the MSVC toolchain and there's a known issue when you compile using #include directives with the Microsoft toolchain with Clang using the modules feature. You can find it here, opened since 2018 https://github.com/llvm/llvm-project/issue...
62,385,485
62,792,237
Not able to cross compile gRPC for QNX platform using aarch64-unknown-nto-qnx7.0.0-g++-5.4.0 compiler
I am trying to cross compile gRPC code with QNX aarch64-unknown-nto-qnx7.0.0-g++-5.4.0 compiler. I am using a toolchain.cmake file to compile. toolchain.cmake: SET(CMAKE_SYSTEM_NAME QNX) SET(CMAKE_SYSTEM_PROCESSOR arm) set(CMAKE_CROSSCOMPILING 1) set(CMAKE_SYSROOT "$ENV{TOOLCHAIN_PATH}") set(CMAKE_C_COMPILER "$ENV{TOOL...
There was some licencing issue, with which I was unable to build the code. After updating the license this issue got resolved.
62,385,680
62,385,891
Why is explicit instantiaion of template function nothing working
Problem Description We have the following files: RetrieveValues.hpp: Class RetrieveValues { public: RetrieveValues(){} template<typename Comp> static int getMinAmount(){...} }; RetrieveValues.cpp we have: template RetrieveValues::<std::less<int>>getMinAmount(){...} ComputeAmounts.cpp int x = RetrieveValues::...
Explicit instantiation looks like this: template int RetrieveValues::getMinAmount<std::less<int>>(); You forgot the return type. RetrieveValues::getMinAmount is the fully qualified name of the function. Then comes the type you want to instantiate (std::less<int>). Explicit instantiation doesn't have a function body. H...
62,385,847
62,386,046
C++: Convert multiple command line arguments from a single std::stringstream
I have a program which inputs multiple string and numeric variables from the command line. As I want to convert few inputs to numeric types, I have been using std::stringstream as suggested at learncpp. Presently, my code looks something like: main.cpp int main(int argc, char* argv[]) { if (argc != 7) { std::cout ...
You can write the required argv values into a single stringstream (separated by spaces), then read each out into the corresponding variables: //... std::stringstream convert; convert << argv[4] << " " << argv[5] << " " argv[6]; // Add more "argv" strings convert >> gaussianBlur >> kValue >> minimumComponentSize; // Rea...
62,385,878
62,387,373
How to statically assert if enumeration constant is defined?
I've this C++14 code: #include <type_traits> struct f1 { enum struct e { a }; }; struct f2 { enum struct e {}; }; template <typename T> struct my_struct { using e = typename T::e; my_struct() : _e{e::a} {} // e::a used here e _e; }; int main() { my_struct<f1> a; my_struct<f2> b; // c...
The same way as you would detect any nested declaration: template <typename T, typename = void> struct enum_defines_a : std::false_type {}; template <typename T> struct enum_defines_a<T, decltype(void(T::a))> : std::is_enum<T> {}; static_assert(enum_defines_a<e>::value, "Enum doesn't define 'a'");
62,385,884
62,386,202
Is Assign a Value Out of Range to a Signed Var Undefined in C++ Standard
I've been read C++ Primer, it said if I assign a value out of range to a signed var will make the var be undefined, but the result of experiment in Visual C++ compiler is same as unsigned var, it will drop higher bits in binary, is that feature in C++ standard? Visual C++ broke it?
The behaviour of integral conversions is defined in C++17 [conv.integral]: If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined. There is no undefined behaviour. Furthermore, results of experiments can never tell you...
62,386,443
62,386,742
How to pass private class member by constant reference?
This is my class #include <vector> class MyClass { public: void print(); // prints X to console private: std::vector<int> X (4, 100); }; When I call the print() method I want X to be passed by constant reference to print(). How can I do that? Currently is looks like as X is passed by value.
Ok, maybe this will help you to start thinking in c++, even if you did not make clear explanation what you need, if I may guess, what you probably think of is that you want to be able to call print() member function on const instances of MyClass, or rvalue has been bound to const lvalue reference, so you need to mark p...
62,386,920
62,387,110
Socket server receiving data at buffer size
I send packets of different sizes one after the other, how can I receive the packets separately at the size I send, not cumulated in the buffer. It seems that now the server adds to the buffer until it fills it and then I can process them. Example: Buffer size: 84. Send from client: 84 bytes, 76 bytes, 76 bytes, 80 by...
No, stream sockets don't work that way. A stream socket is an unstructured byte stream, without any structure to it, whatsoever. In this respect it is no different from a plain file. If you wrote your records, of varying sizes, to a plain file and you are now prepared to read them back, how do you expect to read the yo...
62,386,944
62,392,479
boost::process::child will not exit after closing input stream
In the following example I try to write some data to a child process, which processes the data and writes it to a file. After closing the stream the parent process waits indefinitely for the child to finish. I am at a loss to know how to indicate that I’m done writing the data and would like the child process to stop r...
After inspecting the source code, I found out that closing the stream did not close the associated pipe at least in this case. Doing that manually did solve the issue: ... in.close(); in.pipe().close(); child.wait(); // Does not hang.
62,386,962
62,387,288
Should I catch exceptions without meaningful recovery?
I am trying to read a file: void read_file(std::string_view file_name); The definition of this function is not important, however this function may throw (file may not exist, file may be corrupted, etc.). Successful file read is very crucial to my program, but I don't want to do any meaningful recovery (trying differen...
Usually, no. Many people I 've seen do a try/catch on errors like std::bad_alloc, only to realize that they just can't do anything apart from a clean exit. When new[] fails, either the OS is very unstable or (99,999%) the program has a bug that has to be fixed. Most times you only need a top level exception handler tha...
62,387,004
62,399,155
MSVC command-line option to remove debug information
I have the following simple C++ program in a file called "hw.cpp": #include <stdio.h> int main(int argc, char* args[]) { printf("Hello, world!\n"); return 0; } Compiling with gcc 9.3.0 (Ubuntu), gives the following results: gcc -g0 hw.cpp -o hw.out (disable debug info) => size is 17k (same if -g0 is removed) ...
These are the hw.exe sizes I am seeing for the combinations of static/dynamic linking of the C runtime vs. debug/release builds for a default 32b compile of your hw.cpp with VC++ 2019. debug release static (cl /MTd) 279,040 (cl /MT) 101,888 dynamic (cl /MDd) 10,240 ...
62,387,214
62,387,329
Prevent temporary object files hitting disk in MSVC
Say I have a CPP file called test.cpp. On Ubuntu using gcc 9.3.0 I can use these commands: gcc -c test.cpp (creates object file test.o) gcc test.o -o test.out (creates executable test.out from object file test.o) gcc test.cpp -o test.out (creates only the final executable test.out) The last option is great since no i...
No. The best you can do is use the /Fo flag to dump the .obj file under %TMPDIR% or so. Don't do this for large builds, as foo/Bar.cpp and qux/Bar.cpp will map to Bar.obj and give you very interesting compilation/linking errors.
62,387,234
62,388,134
Best choice for passing float arrays in Cython
Say there is a C++ class in which we would like to define a function to be called in python. On the python side the goal is being able to call this function with: Input: of type 2D numpy-array(float32), or list of lists, or other suggestions Output: of type 2D numpy-array(float32), or list of lists, or other suggesti...
Cython Input The most natural Cython type to use for the input interface between Python and Cython would be a 2D typed memoryview. This will take a 2D numpy array, as well as any other 2D array type that exports the buffer interface (there aren't too many other types since Numpy is pretty ubiquitous, but some image-han...
62,387,746
62,387,904
Substring console output using std::string_view
Is it possible to substring console output of an std::string using std::string_view? For example: std::string toolong {"this is a string too long for me"}; std::string_view(toolong); // do something... expected console output: this is a string
Yes, it's called substring-ing. std::string toolong {"this is a string too long for me"}; std::string_view view(toolong); std::cout << view.substr(0, 16); Alternatively, you can use the remove_prefix() and remove_suffix() methods as well. Example: view.remove_suffix(16); // view is now "this is a string" view.remo...
62,387,894
62,387,897
Is there a generic way to find the length of any null-terminated string?
I am writing my own Range class in c++17 to allow iterating over any range of integers, characters or elements in any container. I have already written constructors for containers, arrays and integers. Now I need a constructor that can take any string pointer type, assumed to be null-terminated, and initialize the m_st...
Yes! I looked up how std::basic_string_view does it, and it uses std::char_traits<T>::length. This function is constexpr since c++17, so the constructor can keep its constexpr specifier! The code simply becomes: template<typename T> constexpr Range(T* p_string) noexcept : m_start{p_string}, m_end{p_string + std...
62,388,034
62,497,226
How to change already created folder/directory security permission using Windows API C++
I have to change directory permission of already created directory. If the directory does not exists,I am able to create new directory using CreateDirectoryEx with given security access attributes,however when the directory already exists ,I have to change security access attributes of directory For ex:Admin -Full acce...
I was able to change directory permisison using this article https://learn.microsoft.com/en-us/windows/win32/secauthz/modifying-the-acls-of-an-object-in-c--
62,388,181
62,388,838
How to completely stop QTimer
How could i completely stop a QTimer ? when i call QTimer::stop() it doesn't correctly stopped. For example i create a QTimer: QTimer timer; timer.singleShot(10000, this, [] { emit work_is_down(); }); and when i stopped: timer.stop(); the lambda [] { emit work_is_down(); } is still run after 10000ms. how to complet...
QTimer::singleShot is a static method of the QTimer class. You can call it on an instance but it will be fundamentally disconnected from that instance. You need to do the full QTimer dance, as said in the comments above: QTimer *timer = new QTimer(); QObject::connect(timer, &QTimer::timeout, this, [](){ emit work_is_do...
62,388,452
62,389,422
Error while regrowing an array: Buffer overrun while writing to
So I was trying to regrow this 1D dynamic array and I am unable to fix this error: Buffer overrun while writing to 'new_arr': the writable size is 'newLength*1' bytes, but 2 bytes might be written void regrow(char *&arr, int &length,int newLength) //Funcion to regrow an array { char* new_arr = new char[newLengt...
A buffer overrun error generally detects if you try to write in a not allocated space that is probably due to a newLength smaller than the length itself that can be avoided with an if-return check: #include <iostream> void regrow(char *&arr, int &length,int newLength) //Funcion to regrow an array { if(length >= ne...
62,388,540
62,389,925
Enums and binary or operator (MISRA C++ 2008, 4-5-2)
MISRA C++ 2008, 4-5-2 states: Expressions with type enum shall not be used as operands to built-in operators other than the subscript operator [ ], the assignment operator =, the equality operators == and !=, the unary & operator, and the relational operators <, <=, >, >=. If one can use & why it is not allowed to use ...
As pointed out in another answer, you are mixing up binary & with unary &. The reason why you can't use binary | and other bitwise operators on enums is that enumerated types (variables of enum type) have implementation-defined size and signedness. And enumeration constants (the values in the enumeration list) always h...
62,388,673
62,925,645
One thread waiting for multiple thread events
I have one thread waiting for some event from various number of other thread, which depend on an event from this one thread to continue processing. How can I code to avoid busy looping? More specifically, I have multiple threads that process their respective video frame and write it to a screen buffer (at different loc...
I sort of figuring out a working solution const int processThreadCount; std::atomic<int> ready_count{}; std::shared_mutex drawing_mutex; std::conditional_variable_any can_draw; void drawThread() { while(true) { std::unique_lock lk{drawing_mutex}; canDraw.wait(lk, [&]{return ready_count==process...
62,389,200
62,389,886
Copy, Cut, Paste, Rename, Undo and Redo in Qt
I have a window that has two widgets as QTreeView and QListView. I select a folder in QTreeView and show its contents in QTreeView. void MainWindow::ListDirectory(QString arg_smb_path) { o_directorySystemModel = new QFileSystemModel(this); o_directorySystemModel->setFilter(QDir::NoDotAndDotDot | QDir::AllDirs)...
QFile offers copy, remove, rename and moveToTrash functions which you can use to implement the file manipulation you wanted. To implement your copy/cut and paste actions, you can save the filepath on copy in some variable as well as a bool copyFile (as opposed to moving), and within the paste action you (can) clear tha...
62,389,303
62,389,533
Can one clear a variable in a recursive function?
I'm trying to build a program in which it takes your name and surname as input (so far) and passes it on to upcoming functions. Now I'm trying to do something with resetting the variable in a recursive function because I thought of the following scenario: if someone somehow messes up writing their name/surname I want t...
When you need to correct the data, you call name_data();, hence it executes and then comes back to the scope where the data is bad. Instead, you need to make the scope where the data is bad return the data in the new scope, so do as follows. make it return not only call if(confirmation=="no"){ cout<<"Back to beginni...
62,389,409
62,389,522
Why does my array values not match with the global variables here?
I have a problem here :( I create here multiple global variables and put them into an array. In funktion extractLabel() I fill these variables with binary code values per variable = binarycode. I print them out and everything is alright. Then I print the same variables out from the array. But there the variables have t...
C++ has copy semantics. When you do: static std::array<long long, 8> c_tokens = {c_label1, c_label2, c_label3, c_label4, c_label5, c_label6, c_label7, c_label8}; (this gets executed early on) The value of the variables are copied into a new c_tokens variable. From this point on, changing either c_tokens or c_label... ...
62,389,487
62,390,364
C++ outputs strange characters instead of numbers (Windows)
I need to program a lotto generator for my education that will randomly roll numbers and check for duplicate entries and replace them otherwise. When I start the program there are no error messages and the program runs but I only see strange characters instead of numbers. A picture of the problem What is wrong with my ...
There are several ways of doing what you want, printing char as integer/decimal value: using casging int(): std::cout << int(lottoGlueck) << "\n"; using good old (C style) printf(), some would say do not use this, but there are advantages and disadvantages to using printf(). printf("%d\n", lottoGlueck); As suggested...
62,389,534
62,389,752
How to sort std::set of indices according to the vector of sorted indices?
I have a class MyClass, which operates with some double values beta, stored as a class member, in it's member function g. It sorts them and stores the permutation in the class member std::vector<int> sorted_beta_ind: double MyClass::g() { // ... sorted_beta_ind.resize(n); for(unsigned int i=0; i<n; ++i) { sor...
Capturing lambda expressions, like yours, are not DefaultConstructible. And that's exactly what std::set tries to do unless it receives a comparator object that can be copied from as a constructor call argument. That is: std::set<int, decltype(ind_comp)> d0, d1; Here std::set knows only the type of the comparator, an...
62,390,082
62,390,374
Thread cannot run again in while loop after restart
I have a C++ code here that will make a game where it will generate random number base on keyboard input, if the number is even, score will increase. If the score is 10, you win and you can restart or exit the game. using namespace std; int score = 0, run = 1; char inp = 'z'; void the_game() { int x = 0; while...
When you set r to zero, the while loop will stop and the thread function (in your case, the_game) will exit, which means that the thread will stop. That is, when the player wins, your code stops the thread instead of suspending it. And you won't be able to revive the thread by calling ResumeThread on it. You can either...
62,390,190
62,390,327
Modifying const reference argument via non-const reference argument
Consider the following code: #include <iostream> void f(int const& a, int& b) { b = a+1; } int main() { int c=2; f(c,c); std::cout << c << std::endl; } Function f takes two reference arguments: int const& a and int& b. Therefore, f is supposed not to modify a, but it can modify b, and indeed it does. Howev...
However, in main, I pass the same variable, referenced both by a and by b. As f modifies b, it also modifies a, which it supposedly shouldn't When f modifies what b refers to, it does not modify a. It modifies what a refers to, but that is okay since b is not const. It's only when you try to modify what a refers to...
62,390,541
62,390,702
pointer attribute changes when reexamined
I am new to C++, currently working on a networking project, faced an unusual error with a vector of object pointers. State class: struct State { public: int reject_percent_; int fill_percent_; int partial_fill_; bool is_logged_in_; struct order { long id; long p...
You didn't allocate memory for the order and you didn't initialize the pointer State::order* o; Dereferencing this pointer to write into it o->id = (obj->ClOrdID); // obj->ClOrdID = 1 o->price = (obj->Price); // obj->Price = 1 o->quantity = (obj->OrderQty); // obj->OrderQty = 1 to read from it std::cout<<o->id<<"\...
62,390,786
62,391,918
Ensure memory mapped page is in memory
I have a read-only Win32 memory mapped file with no sharing open. Is there any way to tell Windows to load some page into memory, making sure that it was loaded successfully, and keep it in memory until I release it? The reason I want this is because reading from memory mapped memory can throw an exception in case the ...
If you need to just guarantee there will be no network access, you can read required regions to a private memory using ReadFile (may be done asynchronously). Another (hacky) way is to use copy-on-write (FILE_MAP_COPY) mapping and cause fake page modification. This allows you to have a contiguous memory mapping that mig...
62,390,906
62,403,845
Can concepts be used with CRTP idiom?
Given following curiously recurring template pattern (CRTP) code example: template<typename X> struct Base { X f() const { return X{}; } }; template<template<typename> typename T> struct Derived : T<Derived<T>> {}; const Derived<Base> d0{}; const Derived<Base> d1 = d0.f(); I started to wonder whether it is possibl...
I have read a proposal that proposed to define constraint on class definition. But it is not merged in the standard. So if you want to constrain a class definition the only work-around I know is to use a static assertion in a context where the class is completly defined, so inside member function body: template <cl...
62,390,922
62,391,306
Endian conversion for negative number?
Currently I am working on a networking project where I am converting the long data (64 bits) to big endian before sending on a socket. For this I am using htobe64(x) function. And on receiving side client I am converting from big endian to host machine byte order using be64toh(x) function. This is working fine for posi...
The line cout << "be64toh = " << be64toh(b) << endl; the function be64toh accepts and returns base64_t therefore cout prints the bit sequence as unsigned. Therefore what you see the unsigned interpretation of the bit sequence. In general signed numbers are represented in the 2's compliment method (although it can vary ...
62,391,020
62,391,368
Should I initialize a variable in a function or globally?
I'm writing my own game engine in C++ and I was wondering where should I initialize variables which I need every frame, for example, every time mouse pointer is getting moved, the coordinates of pointer position should be saved in a variable. Should I initialize the variable for that globally or in the function where i...
Variables should be defined as closely as possible to where they are used. The longer the distance between declaration and initialization, the more error prone the code will be. A good thing about having the variables defined in the function, is that you can mark them as const(!). Then you notify the readers of the cod...
62,391,083
62,391,318
custom std::fstream, std::filebuf's overflow and underflow function not invoked for every character
I'm trying to make a custom std::fstream, which would encode/decode the data while reading. template <class T> class _filebuf : public std::filebuf { public: using transform_type = T; int_type underflow() override { auto c = std::filebuf::underflow(); return c < 0 ? c : transform.decode(c); ...
std::streambuf<CharT,Traits>::underflow makes sure that at least one character is available in the get area, an efficient implementation of std::filebuf will always attempt to read a full buffers worth of characters into the get area. Unless you seek the stream underflow won't be called again until the get area is empt...
62,391,178
62,391,590
Custom tray menu for the application
I have a Qt5 application and I want to add custom menu for the tray icon, but I don't want to make it look like a simple selection menu with list of actions, I want to make a complex widget which will contain several other widgets in custom layout (e.g. few buttons, additional menu, list of values with filtering option...
Yes. You create a QWidget (not QWindow) that you show() on QSystemTrayIcon's activated signal. A QWidget behaves like a standalone window when it has no parent. You can check the given reason or just show it in any case. You might also want to position the widget based on either tray icon geometry or current mouse posi...
62,391,414
62,391,707
Embed .exe file into C++ program?
I wrote a c++ program and I want to execute my second program inside it, which is a exe file. The problem is I want to share my program to others as one single file. When I search on the internet, I found this solution. Just store the second .exe file as a binary resource inside the main .exe using an .rc file at co...
In your project's resource script (the .rc file in which icons, dialogs, etc. are defined), you can add a binary resource with a line like the following: IDB_EMBEDEXE BINARY "<path>\\EmbedProgram.exe" Where the IDB_EMBEDEXE token/macro should be defined in a header file that is included by both that resource s...
62,391,529
62,392,720
VTK Image Data, access 1 image in an array
If I have vtkImageData of size 100x100x5, is there a quick way of getting the 3rd image in the array (i.e. the 3rd 100x100 image in the 5 image array)? All I have found so far is: uint16_t* newIm = static_cast<uint16_t*>(newImData->GetScalarPointer()); uint16_t* num; int index = 0; int frameNum = 3; f...
You can use the vtkExtractVOI filter to extract out a subsection of your vtkImageData. Note that although you are thinking of your image as 5 100x100 images, in VTK it is a single 5x100x100 3-d image. To select a 2-d Z slice out of a 3-d image, you'd do something like this: vtkSmartPointer<vtkExtractVOI> extractVOI = ...
62,391,921
62,395,891
How to iterate over dynamically named objects in Cheerp/js?
Cheerp is a C++ to js/wasm transpiler. Using C++, I am able to interface with extern Javascript objects by statically defining a type and name of an object (and it's members). Take the following object as an example: var example1 = { "itemA" : { value : 3 }, "itemB" : { value : 1 }, ...
IF you need to handle properties with unknown structure (= you do not known at compile time the structure of a JavaScript struct) you better iterate through its entries: #include <cheerp/types.h> #include <cheerp/client.h> namespace client { struct CustomItem : public Object { int get_v...
62,392,275
62,392,946
Should I avoid recursion everywhere it's possible?
This is not a case where I can use both without problems, because I'm already convinced that loops are much easier to understand and I try to always use them. But then I stumble upon this (C++ function for binary search tree): Node* Insert(Node* &rootptr,Node* data) { if (rootptr == nullptr) { rootptr = dat...
Recursion can be a lot more clear. The only worry with recursion is that you can smash the stack if you use it too much. For example linux typically has a 2MB stack so you don't want to recurse millions of lines deep. Recursing a binary tree that is only O(log n) deep is probably fine. In this case it is fairly simple ...
62,392,321
62,397,318
Creating a function that takes a container "X" as a parameter, which passes X.size() parameters to a variadic function that it calls
I am currently working on an HTTP API that I want to use to perform CRUD operations on a database. I try to write the code for it as generic and modular as possible. I am using the MySQL X DevAPI. Currently, I am stuck on the following problem: mysqlx::Result MySQLDatabaseHandler::jsonToCUDOperation (const nlohmann::js...
You can actually just pass STL containers to the CRUD functions provided by MySQL's X DevAPI
62,392,414
62,392,444
Why does the C++ function without a return statement return a value?
I implemented fixed-point iteration in C++, and I forgot the return statement: double fixedpoint(double g(double), double p0, double tol, double max_iter) { double p, error, i = 1; do { p = g(p0); error = std::abs(p - p0); i++; p0 = p; } while (i < max_iter && error > tol); // No return st...
Not returning from a non-void function is undefined behavior. This means anything can happen. One of those things is actually returning a value. However, this is not behavior you can rely upon. Crashing the program, printing garbage, etc, are all valid behaviors. Turn on compiler warnings, they will tell you that you a...
62,392,460
62,393,045
C++: function call expression with braced-init-list - does standard prescribe to ignore braces in a trivial case of a single element list?
Consider the following example: class X; void f(const X &); void g() { X x; f({x}); } Does standard require that an implementation ignored curly braces in that case? Without any optimization involved. If yes, than since which version? On a first glance, it looks like by rules there should be a temporary crea...
The initialization of X const &x (the argument of f) in f({x}) is list initialization in a copy initialization context, by [dcl.init]/15. Thus, we can drop the function and just ask what this means: int main() { X x; X const &y = {x}; // still copy list initialization } Now, the first clause in [dcl.init.list]...
62,392,468
62,392,563
Error : expected primary-expression before 'int' and many similar errors like this in the code
PS: I'm a beginner. The full code I was trying is as follows: this_is_the_tree_I_Was_trying_to_code_up Errors were on line 30,50,63,74 and 82, like on: line 30: expected primary-expression before 'int';expected primary-expression before 'char'; line 50: expected primary-expression before 'int';expected primary-expressi...
On this line: teacher(int code1,char *name1,char *sub1,char *pub1): staff(int code1,char *name1) { you are using the wrong syntax to call the base class constructor. You need to pass along only the variables, not the types. This is how to write it correctly: teacher(int code1,char *name1,char *sub1,char *pub1)...
62,393,076
62,393,125
Linker problem in QtCreator with C library
I have a a project with the following structure: 3rd_party - heatmap.c - heatmap.h - lodepng.cpp - lodepng.h CMakeLists.txt data.cpp data.hpp main.cpp When running the project I get the following error: error: Undefined symbols for architecture x86_64: "_heatmap_add_weighted_point", referenced from: Da...
Change project(trial LANGUAGES CXX) to project(trial LANGUAGES C CXX) or don't specify a language at all: project(trial) Alternatively, you can build it separately as a library and then link it to your target executable: add_library(heatmap 3rd_party/heatmap.h 3rd_party/heatmap.c ) #... target_link_librar...
62,393,423
62,393,653
Flex/Bison - How can I resolvev "Multiple definition of `symtab'"
I've recreated the advanced calculator from the book "flex & bison" and made some minor adaptations for c++. But what I cannot solve is that I get following error when compiling. C:\..\BisonFlexCalculator/Includes/calc.hpp:17: multiple definition of 'symtab' C:\..\BisonFlexCalculator/Includes/calc.hpp:17: first defined...
The problem is that you have a definition of the variable symbol symtab[NHASH] in the header file. Each source file that includes this header, will define that symbol. Since all your source files include this header file, you will have multiple definitions of the same object and thus violate the ODR (One Definition Rul...
62,393,504
62,394,980
C++ unordered_map default allocator
I have an abstract class (parent) and just created derived class (child) from it as below: class parent { public: virtual string print()=0; }; template<class T> class child: public parent{ private: unordered_map<string, parent*> children; public: parent *&operator[](string name) { return children[n...
unordered_map<std::string, parent *>::operator[] won't create instances of any class, as its values are pointers, not class instances. So if you use it to access a key that was not previously inserted in the map, it will default-initialize a pointer (which initializes it to nullptr) and store that in the map. If you w...
62,393,834
62,394,399
c++ template with "infinite" arguments
so i have this struct: template <typename T> struct _vect2 { T x; T y; _vect2(T x, T y) : x(x), y(y) { } _vect2() { } }; And i want to create a function that takes an "infinite" amount of those structs. template <typename T, _vect2<T>... Args> double vect_distance(Args... arguments) {} How it should w...
You can deduce the first argument's type, and force others to derive from/be a vector of the same deduced T type. In c++20: #include <concepts> template <typename T> double vect_distance(const vect2<T>& head, const std::derived_from<vect2<T>> auto&... tail); In c++17: #include <type_traits> templa...
62,394,041
62,394,638
How can I register a class member as callback function to a queue?
The minimal example code is the following : #include <iostream> #include <string> #include <vector> #include <functional> #include <queue> #include <thread> // Queue from : https://stackoverflow.com/questions/2721421 template<typename T> class Queue { public: void Push ( T x ) { theQueue.push( x ); for (auto ...
What's wrong with this: ConsoleModule() :sendQ{}, recvQ{} { recvQ.Register([this](Queue<std::string>& q) { recvData(q); }); std::thread t([this]() { cinFct(recvQ, sendQ); }); cinThread = std::move(t); }
62,394,106
62,394,270
How can I initialize an array of objects?
I've written this code but I have some errors when I try to initialize an array of Critter objects and don't know what they're about. My code: #include <iostream> #include <string> #include <vector> using namespace std; class Critter { private: string crName; public: Critter(string = "Poochie"); string get...
Critter c[10] = { "bob","neo","judy","patrik","popo" }; This defines an array of const char *. To initialize an array of Critter with those strings, instead: Critter c[10] = { {"bob"}, {"neo"}, {"judy"}, {"patrik"}, {"popo"} }; [ EDIT ] It was pointed out that the same answer was first posted in a comment, only it...
62,394,351
62,394,437
Is it a good habit to empty data structures after you're done using them?
I use various data structures in my programming, and I often transfer data from one structure to another. // assume that I want to transfer all data from v to Q vector <int> v = {1, 2, 3, 4}; queue <int> Q; for(int item : v){ Q.push(item); } // after this point, v is no longer used After you are done using a stru...
No, that would be completely pointless. Instead, minimise the scope of your variables to the places where you need them, so that you literally cannot accidentally use them after you intended to; your build will fail. Do that with functions (preferable), or with additional block scopes: queue <int> Q; { vector <int>...
62,394,493
62,394,511
Improve C++ style for simple conditions
I am new to programming. I am doing my homework and the codes work so I won't post my whole codes out. I just wonder if it is possible to add "&&" and "||" in the same condition - my condition is a must be equal to 16 and b equal to any number from 5-9. Any suggestions? e.g. if ( a == 16) { if (b == 5 || b...
Yes; just do it, and use parentheses to make it unambiguous: if ((a == 16) && (b == 5 || b == 6 || b == 7 || b == 8 || b == 9)) or, if b is an integer: if (a == 16 && b >= 5 && b <= 9) Ideally, though, you would describe the meaning of these chains of conditions using names, then come up with a much more expressive b...
62,394,594
62,394,787
Converting an ANSI C-String to UNICODE
Note: I am trying to write my own function that performs this conversion I understand that a char is 1 byte, while a wchar_t is 2 bytes. So this is how a conversion would happen: 1) Input a text Hello, world 2) Get the bytes of the string 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 3) Allocate memory twice the number of b...
I thought the ASCII character codes were all the same everywhere, but this argument seems to say otherwise if I am understanding correctly from the fact it has values for Mac and Windows there. The ASCII codes are, yes, but the high bit of an "Extended ASCII" string (spoiler: there's no such thing) maps to any of a l...
62,394,881
62,395,022
Can't convert memory address to value
thanks for visiting my question! Currently, when I run this code (an implementation of the Set data structure in c++), the memory address of each element in the set is printed instead of the values in the set. To help with debugging, here's my code: #include <iostream> #include <algorithm> #include <string> #include <v...
Inside printSet(), you use &in[i] to print each element. The & operator returns the address of the object you are referencing. So, instead of getting the value, you are getting its address. You should remove it, eg: void printSet(Set *in) { for (int i = 0; i < in->size(); i++) { std::cout << (*in)[i] <...
62,395,175
62,396,028
I can't see why Im getting segmentation fault error
I'm currently trying to learn Quick Sort, and here is my code: #include<iostream> #include<vector> #include<cmath> using namespace std; void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } int partition(vector<int> &A, int low, int high) { int pivot = A[low]; int i = low; int j = high; ...
You have infinite recursion in your QuickSort function. Whenever it gets called, it'll call itself and there is no condition there to break the cycle. Also, your swap function does not work. As it is written, the values in the A bins will be supplied to the function and interpreted as addresses. That should not compile...
62,395,303
62,396,785
Boost program_options partial key match
I'm trying to read config files with Boost::program_options. The config files look like: hier.arch.y.option_name = 0x5 another.hier.archy.setting_name = 0x1E I want to be able to search by just "option_name" or "setting_name". I'm not worried too much about duplicates but if there's a way optionally to match 2 substri...
Q. What does enumerate the parsed options mean? A. Live On Coliru for (auto& opt : parsed_opts.options) { for (auto& val : opt.value) { std::cout << std::quoted(opt.string_key) << "\t-> " << std::quoted(val) << std::endl; } } Prints "foo.bar.setting0" -> "0x5" "foo.notbar.s...
62,395,446
62,397,435
Is alignas legal when used for an inline static member?
MSVC throws an error when alignas is used with an inline static member variable while Clang does not. Which one is correct? Flags for clang: -O2 -std=c++2a. Flags for MSVC: /std:c++latest. The error: error C2024: 'alignas' attribute applies to variables, data members and tag types only #include <iostream> //https://g...
In C++17 [dcl.align]/1 it says: An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, or an exception-declaration. In your code, state is a data member (static data members are data members), so the alignment-specifier is all...
62,395,578
62,395,766
g++ std::visit leaking into global namespace?
I just bounced into something subtle in the vicinity of std::visit and std::function that baffles me. I'm not alone, but the only other folks I could find did the "workaround and move on" dance, and that's not enough for me: https://github.com/fmtlib/fmt/issues/851 https://github.com/jamboree/bustache/issues/11 This...
The argument visitor is an std::function, which is in the namespace std, so argument-dependent lookup finds visit in the namespace std as well. If you always want the visit in the global namespace, say so with ::visit.
62,395,621
62,412,353
Call python function with C++ pointers
I want to pass a callable object from Python to C++ and then call it from C++ with arguments for which I have registered base_. Example: namespace bpy = boost::python; bpy::class_<X, X*, boost::noncopyable>("X", bpy::no_init); bpy::def("f", +[](bpy::object fn) { fn(new X()); }); Then from python: from example impo...
According to Argument Handling in Calling Python Functions and Methods: Arguments are converted to Python according to their type. By default, the arguments a1...aN are copied into new Python objects, but this behavior can be overridden by the use of ptr() and ref(): class X : boost::noncopyable { ... }; void a...
62,395,636
62,396,291
Concatenate string and integer in c++ for reading multiple file in case of C++ 11 not supporting computer
I would like to hear if there is a solution to this problem. my computer does not support C++ 11 so I can not join string and integer by std::string to_string... instead, I used a string stream. I want C++ part in ROOT program to read each all files by loop them and from each file read the three columns by ifstream. i...
Problem ifstream get(input); is also a C++11-ism. Before C++11, you cannot use a std::string as an argument to the std::ifstream constructor. It only accepts file names as a pointer to a null-terminated char array. Quick Fix: ifstream get(input.c_str());// c_str provides a null-terminated character array Smarter Fix: ...
62,395,801
62,395,903
Using templates to specify member variable
Here I have a binary search tree class with a class template: template <class T> class Tree { T* root_ptr; public: void Insert(T* ptr_to_value); }; template <typename T> void Tree<T>::Insert(T* ptr_to_value) { T** temp = &root_ptr; while (*temp) { if (ptr_to_value->name <= (*temp)->name) ...
Template parameters don't have to be types; they can be certain non-types too, as long as they're compile-constants. Pointers-to-members qualify! template <class T, auto Ptr> class Tree { T* root_ptr; public: void Insert(T* ptr_to_value); }; template <typename T> void Tree<T>::Insert(T* ptr_to_value) { T**...
62,396,117
62,396,118
Integrating Crashpad with a Windows Qt application
We are trying to integrate Crashpad with our Qt application and have run into several errors. We built Crashpad and attempted to link it to our application using the following snippet from the .pro file: # Crashpad rules for Windows win32 { LIBS += -L$$PWD/Crashpad/Libraries/Windows/ -lbase LIBS += -L$$PWD/Cras...
The issue here ended up being a toolset mismatch. Ninja built Crashpad using the MSVC 2019 toolset. The version of Qt installed on the machine in question was 5.14.2 which used a MSVC 2017 toolset. Once we installed the 5.15.0 kits and built with the MSVC 2019 build configuration this error went away. Additionally, onc...
62,396,188
62,396,407
How to organize your github repository when syncing with Visual Studios (c++)?
Edit: Using windows. Hopefully this is not too off-topic or silly, but I've uploaded a decently large project to my Github (around 40-50 source/header files each) by using the functionality in Visual Studios that allows you to push your project to the repository directly and be able to push/pull in what seems like a pr...
You need at a minimum a src folder to move the code away from the root. We need the README more readily visible. If needed, create the directory locally, with mkdir, use notepad or even echo "FOO" > src/file.cpp to create the file in the right folder and then import it into Visual Studio, if the UI gives you trouble. L...
62,396,615
62,481,290
Is creating an extra node when solving linked list question a good habit?
Lately, I've been working on linked list questions on LeetCode, and I noticed that when dealing with linked lists (like sorting linked lists), people sometimes create a dummy node and return dummy->next. It is a pretty convenient act, but are there any bad outcomes from doing this (say, if I will delete it in the end t...
No, creating a new node has no problem. Because all it matters in solving LeetCode questions is the efficiency of your algorithm (time and memory complexity). Adding one new node is constant time and memory and would not change the complexity of your solution. Here is an O(N) time and O(1) space solution that would pas...
62,396,687
62,396,764
Behavior of placement new and uninitialized_fill()
I see placement new used in the following implementation of uninitialized_fill. Does anyone know the underlying implementation of placement new or where to find it in g++? I'm assuming the operator takes a pointer to where the object should be placed and a reference to Value(value) which is an rvalue after invoking th...
placement-new constructs an object at a specified address, yes. In the expression ::new (static_cast<void*>(std::addressof(*current))) Value(value);, *current returns a reference to an element in the specified iterator range, then the address of that element is being casted to void* and passed to placement-new, which t...
62,397,175
62,467,361
Variadic Function Pointer definition is unclear for VxWorks spyLib
I'm using VxWorks 6.9 and am trying to use some spyLib.h functions but I'm having issues finding what signature to expect given that the type is variadic. in vxTypesOld.h I find my type: typedef int (*FUNCPTR) (...); and in spyLib.h i have my function call : extern void spyReportCommon (FUNCPTR printRtn); But what func...
That looks like a bad design. The print function cannot print if it does not know what the parameters are. At least one parameter is needed to specify what the rest of the parameters are. Looking at the source and searching for "printRtn" I see that all calls to the print function are expecting a printf like function w...
62,397,205
62,397,572
How stable is C/C++ structure padding under the AAPCS (ARM ABI)?
Question The C99 standard tells us: There may be unnamed padding within a structure object, but not at its beginning. and There may be unnamed padding at the end of a structure or union. I am assuming this applies to any of the C++ standards too, but I have not checked them. Let's assume a C/C++ application (i.e. b...
You can never by 100% sure that the compiler won't introduce padding in some capacity. However, you can mitigate the risks by following a few rules: Use fixed size types for all members, i.e. uint32_t, int64_t, etc. Start each member at an offset that is a multiple of the member's size (or if the member is an array /...
62,397,376
62,566,775
Setting GL_TEXTURE_CUBE_MAP cause GL_INVALID_OPERATION in glUseProgram
I am using the following function to load my cube map. Without loading, there is no error. Whenever I set me cube map texture next glUseProgram() function causes GL_INVALID_OPERATION error; unsigned int Model::loadCubemap(std::vector<std::string> faces){ GLuint CubeMapOrder[] = { GL_TEXTURE_CUBE_MAP_POS...
If you have something like uniform samplerCube PointShadowMapTexture[MAX_POINT_LIGHT]; you have to uniform all elements in samplerCube array. Otherwise, there will be a black screen. Or your clear color.Also following draw calls may cause invalid operation. Better to uniform all unused sampler types with blank 1x1 text...
62,397,477
62,397,507
How does failure to allocate memory in constructor bubble up
I am trying to understand what would occur if I failed to allocate memory in a constructor for an object which is itself dynamic. Example: Say I am dynamically allocating an object and I am checking whether the object was allocated: Object* object = new(nothrow) Object(); if (object == nullptr) { // handle stuff } Now...
In this case an exception is thrown. The new(nothrow) only means that failure to allocate storage for the object will not throw, it does not place constraint on the object constructor (nor constructors of subobjects).
62,398,252
62,398,827
Why [[likely]] attribute in C++20 raises a warning here?
#include <iostream> int foo(int a, int b) { if(a < b) [[likely]] { return a; } return b; } int main() { std::cout << foo(3,1) << std::endl; } Demo According to the reference, it seems like this is how we're supposed to decorate if clauses with [[likely]] or [[unlikely]] attributes. It's also ...
There's nothing wrong with your code. This is due to GCC's implementer overlooking the fact that attributes on compound-statements are a thing. [[likely]] if (whatever) {} means something else entirely - it means that the if statement itself is "likely", not a branch of it.
62,398,339
62,413,058
SamplerState issue in the pixel shader
I have a problem with the pixel shader, it compiles but does not renders anything and instead Directx gives out this error: D3D11 ERROR: ID3D11DeviceContext::DrawIndexed: The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0, but the sampler bound at this slot is configured for c...
You are declaring your sampler as a comparison sampler : samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; It should be : samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; Comparison sampler are used mostly for shadow maps, and declare as following in hlsl : SamplerComparisonState myComparisonSampl...
62,398,478
62,404,212
Can we control two independent processes with hardware timers in stm32f
I am trying to implement firmware for STM32 based micrrocontroller Two tasks, Task A & Task B both independent of each other. Is it possible to generate interrupts at different time instances so that the firmware switches back to the task once the time is reached Eg : taskA should run once every 500us, and taskB should...
Edit: This answer assumes not using any RTOS, as not mentioned in question – ignoring the (possibly inappropriately!) set tag. Using RTOS, solution will look differently! taskA should run once every 500us, and taskB should run once every 100us This does not sound like you actually rely on task preemption, rather tha...
62,398,864
62,399,307
How to draw a thick line using a rectangle?
Hello I'm trying to achieve the following: My current code for achieving this in OpenGL is the following: void draw_thick_line(vec2 start, vec2 end, GLfloat thickness) { GLfloat slope_angle = atanf((end.y-start.y)/(end.x-start.x)); GLfloat b = (M_PI/2) - slope_angle; GLfloat y_shift = thickness*sinf(b)/2.0...
Your angle calculation is not quite correct: GLfloat b = (M_PI/2) - slope_angle; This gives you the complement of slope_angle within the same quandrant but is not the correct angle relative to the coordinate system and doesn't transform you to the line segment you need. I think the correct angle calculation would be: ...
62,398,866
62,399,638
Check if a class has a possibly-overloaded function call operator
I am wondering whether it would be possible to implement a trait in C++20 to check if a type T is such that it has a possibly overloaded/possibly templated function call operator: operator(). // Declaration template <class T> struct has_function_call_operator; // Definition ??? // Variable template template <class ...
&T::operator() is ambiguous for the 3 failing cases. So your traits found is there is an unambiguous operator() As you allow T to be not final, we might apply your traits to (fake) class with existing inherited operator() and class to test: template <class T> struct has_one_function_call_operator: std::false_type {}; ...
62,398,873
62,400,083
Clang gives me a warning of signedness change, however the code still produces correct output
I was analyzing some warnings in a codebase and got puzzled by this one generated by Clang Consider the following C++ code: #include <iostream> int main(int , char *[]) { uint32_t val1 = 10; int32_t val2 = -20; int32_t result = val1 + val2; std::cout << "Result is " << result << "\n"; return 0; } Clang ...
What is the actual danger that this warning is warning me against? The potential danger is that you may have been unaware of the implicit sign conversion, and have made it by accident. If it is intentional and behaves as desired, then there is no danger). How can I trigger this behaviour? You already have triggered...
62,398,932
62,398,978
Function definition not found for #define
I am getting a weird error for one of my macros. The names are changed, but besides that the code is exactly the same as the one in my project. Its purpose is automatic a process I write many times troughout my code. #ifdef add #undef add #endif #define add(name, temp) \ struct name<temp> ...
I think you've forgotten bool keyword as compiler message suggested but as int #ifdef add #undef add #endif #define add(name, temp) \ struct name<temp> \ { \ static constexpr bool r = true; \ }
62,399,140
62,401,499
Why does my code stop running when it comes to pointers?
I need to make a simple program with linked lists but my code just stops running. Down below are to codes, first is the main .cpp file, and the second is header where the problematic function is defined. The code stops when it comes to assigning "new_" pointer attributes (marked with arrows). The function, as its name ...
you also have to change A[I] to A[i], because I doesn't exist
62,399,203
62,399,265
Function of _kbhit()
I am a beginner at C++ and trying to code a C++ console based snake game. I was stuck when I cannot move the snake without continuously pressing a key. Now I can do by just pressing the key once but I still do not understand the function of _kbhit() which has helped me do it. void snake_movement(){ if(_kbhit()) ...
The _getch() is a blocking function. If no keypresses are available in the input buffer, it will wait for a keypress to become available in the input buffer. So your program gets stuck inside of _getch() until a key is pressed - and that's why it wouldn't "work" unless you keep the key pressed, so that _getch() can kee...
62,399,549
62,399,559
I'm trying to use a while loop to remove letters from a string until there are none left. What am I doing wrong here?
#include<iostream> #include<string> using namespace std; int main() { string word; cout << "please enter a word: "; getline(cin, word); int str_size; word.size() = str_size; // the line above says "word must be modifiable". new to coding so not sure how to fix it? // also haven't tested anything be...
On this line: word.size() = str_size; you are trying to assign a value to the temporary value returned by .size(). However, the operator= needs an lvalue (i.e. a variable that has a name) on the left hand side. So what you need is: str_size = word.size(); To actually remove letters from a string, you could use some a...
62,399,668
62,399,869
Macro behind constructor. What does it mean?
#define _GLIBCXX_TXN_SAFE class out_of_range : public logic_error { public: explicit out_of_range(const string& __arg)_GLIBCXX_TXN_SAFE; }; What does _GLIBCXX_TXN_SAFE mean here?
The C++ standard committee has some groups that research and propose some experimental features. One of these is the transactional Memory study group (SG5). Their main work result is Technical Specification for C++ Extensions for Transactional Memory. You can read a simple version on Transactional memory. Part of this ...
62,399,762
62,399,934
How find the count integers that are divisible by 7 in the given range using only While loop
---How write a program that will get A and B inputs and the numbers in the [A, B] range will be divisible by 7 without the remainder... using while loop in C++...--- For Example: Input data: 7 13 console result: 1 Input data 5 21 console result: 3 Input data -8 -5 console result: 1 C++ code example with for loop int ...
I'm not sure if this is pseudo-code or actual code, but the main mistake I see here is that you've used 'input' and I'm not sure what that's supposed to be. See the following example: #include <iostream> using namespace std; int main() { int count=0; int a = 0; int b = 0; cin >> a >> b; for(int i ...
62,400,038
62,413,840
C++: grammar of move assignment operator
I have a C++ grammar question related to X x = X();, which results in the move constructor being invoked using special compilation flags below. Is the grammar not in a form which one would expect the move assignment operator to be called? There is an rvalue on the right hand side of the equals sign. Curious if ther...
The object does not exist yet, it is being constructed, therefore requires a constructor. In this case the move constructor is called because of an rvalue on the RHS. A temporary object is constructed using the default constructor and this temporary object is then used to construct the object on the LHS using the mov...
62,400,340
62,400,592
vector going out of bounds depending on a swap statement
For this piece of code- vector<int> v{ 417, 929, 845, 462, 675, 175, 73, 867, 14, 201, 777, 407, 80, 882, 785, 563, 209, 261, 776, 362, 730, 74, 649, 465, 353, 801, 503, 154, 998, 286, 520, 692, 68, 805, 835, 210, 819, 341, 564, 215, 984, 643, 381, 793, 726, 213, 866, 706, 97, 538, 308, 797, 883, 59, 328, 743, 694, 607...
In the first loop iteration: i is 0 A.at(i) is 417 A.at(A.at(i)-1) is A.at(416) which is 589 Then you swap A.at(0) with A.at(416), so now A.at(0) is 589 and A.at(416) is 417. Then you execute if(A.at(i)!=A.at(A.at(i)-1)). But since A.at(i)-1 is 588, so this does if(589 != A.at(588)) which accesses out of bounds. Per...
62,400,637
62,400,648
Why use `std::map::find` for checking if maps have a key?
I recently found out (not through research, so if this is wrong please tell me and I will correct this) that the following somehow works: std::map<T*, U*> map; std::cout << map[key_that_is_not_in_map] << std::endl; // OUTPUT: // 0 However a lot of people recommend using std::map::find(key_.....) != std::map::end(). Is...
Is there something about the latter that makes it safer, or is the first only applicable to pointers keys and values? Yes, std::map::operator[] performs an insertion if no key exists. And the std::map::find does not. From cppreference.com the std::map::operator[] Returns a reference to the value that is mapped to ...
62,400,700
62,402,730
How to safely pass a C++ string to Rust?
I have this Rust function: pub extern "C" fn do_something(my_string: &str) { let s = String::from(my_string); } That I call on C++ with this: std::string my_string("hello"); do_something(my_string.c_str()); Signature: extern "C" void* do_something(const char*); I get this error right on the String::from line: me...
That I call on C++ with this: do_something(my_string.c_str()); So on the C++ side you're calling a function with a C string as input (not an std::string, which is a very relevant distinction). This means the Rust function should take a C string as input, which &str definitely isn't. Thus do_something should be decla...
62,400,746
62,479,849
CGAL: Why is halfplane represented by six rays?
I've just started playing with Nef polyhedrons on the plane - the simple program below creates a halfplane, defined by a line y=0, and then this halfplane is explored by the CGAL Explorer. #include <iostream> #include <CGAL/Exact_integer.h> #include <CGAL/Extended_cartesian.h> #include <CGAL/Nef_polyhedron_2.h> using...
I'm answering my own question. According to these explanations from the CGAL online manual, each 2D polyhedron is bounded by an infinitely large frame, which is represented by four infinitely remoted vertices. These boundary vertices have extended coordinates (+infinity, +infinity), (+infinity, -infinity), (-infinity, ...
62,401,405
62,401,742
Why does "weak.lock()" return "nullptr" with the definition of "auto weak=std::make_shared<int>(42);"?
Why does weak.lock() return nullptr in this code snippest: std::weak_ptr<int> weakPtr1 = std::make_shared<int>(6); std::cout << weakPtr1.lock() << std::endl; whereas it works in the following one: std::shared_ptr<int> sharedPtr = std::make_shared<int>(99); std::weak_ptr<int> weakPtr2 = sharedPtr; std::c...
Smart pointers, in order to do their work properly, maintain a so called control block which serves as a metadata storage, in particular, use counters. That is, each resource has an associated control block in memory (consisting of e.g. two integers) that smart pointers can refer to to know how many of them are still u...
62,402,165
62,420,559
OpenCV subdivision-consistent Rect2f to Rect2i rounding
In OpenCV, when making cv::Rect2i from cv::Rect2f, the library just rounds each component of cv::Rect2f, i.e. x, y, width, height. This causes holes and overlays when converting a set of subdivision rects, for example, intervals 0.4..1.6 and 1.6..3.2 would be rounded to 0..1 and 2..4, while the desired integer subdivis...
You can use like rect3. cv::Rect2f rect1(0.4, 1.4, 1.6, 3.2); cv::Rect2i rect2 = rect1; cv::Rect2i rect3(rect1.tl(), rect1.br()); // tl for top-left and br for bottom-right cout << rect1 << endl; cout << rect2 << endl; cout << rect3 << endl; outputs [1.6 x 3.2 from (0.4, 1.4)] [2 x 3 from (0, 1)] [2 x 4 from (0, 1)] ...
62,402,451
62,402,517
Go to next iterator in range-based for loop
for my project I need to make the iterators from the loop to go to the next item in the container, do some operations, and return again back to the same iterator and just continue, however, for some reason neither advance nor next and then using prev seem to work. So how could I get the next iterator and just return to...
Range-based for loop iterates over elements. The name it is confusing here; it's not iterator but element, that's why std::next and std::prev don't work with it. Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in ...
62,402,464
62,402,620
Is there a better way to handle exceptions ? try-catch block is really ugly
I read this and find out it's important to handle exceptions, i use nlohmann::json (from github) and nearly in most of my member functions is use nlohmann::json::parse and nlohmann::json::dump which make a chance to throw exceptions if the input has a problem. So I need to handle those chance of throwing exception som...
I would go like this: set a "sequence pointer" to keep the record of where/what are you trying to parse, like with a string with the pattern trying to parse a... so you can know/notify where exactly was the faulty element in the json. look in the example below, if "name is faulty, then r is holding the value "trying to...
62,402,670
62,403,029
Inserting a node at the end of Linked List in C++
I have written this code to insert node at the end of singly linked-list. It compiles without errors but upon execution no output shows. Where have i gone wrong? void insert_n(int x){ node* temp1 = new node(); temp1->data=x; temp1->next=NULL; node* temp2 = head; while(temp2->next!=NULL){ temp2 = temp2->next; } temp...
Yes, You are right. If head == NULL then your insert function can't work. Following is the correction of your insert_n() function: void insert_n(int x) { node* temp1 = new node(); temp1->data = x; temp1->next = NULL; if (head == NULL) { head = temp1; } else { node* temp2 = head; while (temp2->next...
62,402,895
62,403,337
How to tell if type punning is ok on my platform?
I have a bunch of code taking binary blobs from network. On knowing the type of the blob I've so far used type punning (pseudo): uint8_t* data = network.get(); if(type == "A") { uint32_t* var = reinterpret_cast<uint32_t*>(data); ... } else if (type == "B") { float* var = reinterpret_cast<float*>(data); ... } A...
Q1: Is there a way to test if type punning is supported and behaves as expected on my platform? Yes, read the compiler manual. There is usually a chapter about non-standard extensions. For example gcc C extensions or gcc C++ extensions. If there is no documented non-standard extension (or in case you compile for stri...
62,403,191
62,404,307
Input being skipped and outputing garabge values
I'm making a simple shopping cart program that will output the cost of items based on the cost and the quantity. After compiling, the program ran successfully, however, when I got to item 2, it skipped the input on the item name and went straight to the item cost. Additionally, when I outputted what was available I go...
there are 2 problems: 1: I think you indented to assign some default values to ItemToPurchase's member variables within the constructor. But what you did is to assign it to local variables. To assign it to the object's member variables you should not use the type identifier: ItemToPurchase::ItemToPurchase() { itemNam...
62,403,834
62,404,148
Implementing random partition point in partition function with pointers
I'm trying to convert my partition function shown below from choosing the second last element as the partition to a random element. My original idea was to use the rand function something along the lines of int *pivot = rand() % last; However i've realised this wont work trying to parse an integer to a pointer integer...
You need to pick a distance in the range [0, std::distance(first, last)), and add that to first. Note that rand produces low quality pseudorandom numbers, and rand() % N does not uniformly pick numbers. int * random_pivot(int * first, int * last) { thread_local std::mt19937 random_engine(std::random_device{}()); ...
62,404,209
62,728,466
Why does clang handle exceptions for this trivial std::variant code?
If we have code like this: #include <variant> int main(){ using V = std::variant<int, double>; V a = 5; V b = 5.6; a.swap(b); } https://gcc.godbolt.org/z/oqGiHs If you compile with clang, it emits code that handle exception during swap. Why is that? Both variants are non empty and underlying types ar...
This turns out to be clang bug. https://bugs.llvm.org/show_bug.cgi?id=46342 It appears to be fixed, but I can not find the version where is fixed.
62,404,438
62,404,855
How does constexpr new allocate memory?
How can we dynamically allocate at compile time? Does the constexpr operator new just allocate memory on the stack?
There is no constexpr new operator. Since C++20, you can use new operator in constexpr expressions in the condition that you only use a replaceable global allocation function (it means that you don't use a placement new or user-defined allocation function) and that you deallocate the data in the same expression. So, in...
62,404,648
62,405,467
Arithmetic on invalidated iterators
Is behavior of std::distance undefined when called on a pair of std::vector iterators that have been invalidated by moving the vector? For context: I'm writing copy and move constructors for a class that has a vector of data and a vector of iterators that point to that data. Once I move the data to its destination, I n...
Is behavior of std::distance undefined when called on a pair of std::vector iterators that have been invalidated by moving the vector? If the iterators are valid before the move, they will remain valid after the move - so you don't need to recalculate them using std::distance. (emphasis mine below) std::vector::vecto...
62,405,311
62,405,406
C++ Why numeric limits doesn't work for uint8_t and int8_t?
I recently noticed numeric_limits::max() and numeric_limits::min() don't seem to work for uint8_t and int8_t. Is there a reason for this or could it be a bug? I tried on my own computer using gcc compiler: #include <iostream> #include <limits> using namespace std; int main() { std::cout << "numeric_limits<uint8_...
It does work. The output is interpreted as ASCII characters though. If you cast to int before you print, you will see the correct values: std::cout << "numeric_limits<uint8_t>::max() = " << static_cast<int>(numeric_limits<uint8_t>::max()) << std::endl; std::cout << "numeric_limits<int8_t>::max() = " << static_cast<int...