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,505,019
62,505,354
Assign std::vector<std::byte> to std::vector<char> WITHOUT copying memory
I have a function that returns a std::vector<std::byte> I am aware that std::byte is not a character type nor an integral type, and that converting it to char is only possible through a typecast. So far so good. So I would like (in cases where I know that the vector only contains character data) to transfer ownership o...
You can achieve this with a cast, as shown below. This is legal because the cast is to a char reference (if casting to any other type it would be UB) but, with gcc at least, you still have to compile it with -fno-strict-aliasing to silence the compiler warning. Anyway, here's the cast: std::vector <char> char_vector ...
62,505,025
62,505,063
Second for loop is not being executed
I am solving one competitive programming problem where I'm trying to traverse an array in reverse and inside it again traverse it in reverse direction. I've included this snippet from my code which doesn't seem to be working. The second loop is just ignored. It just outputs: loop3 loop2 loop1 for(int i=n;i>0;i--) { ...
Instead of if(!checked[a]) continue; checked[a] = 1; You might mean if(checked[a]) continue; checked[a] = 1;
62,505,445
62,505,676
Avoiding code repetition when iterating through an IShellItemArray
I'm writing a large library of functions that act on IShellItemArrays. Practically all of the functions need to access each IShellItem (and more specifically, each IShellItem2) in the array individually. So unless I'm overlooking something in the documentation, I believe I have to do something like this: void SomeFun...
There are things you can do with std::function and a capturing lambda. Thus, given: void ForEachShellItem(IShellItemArray*, std::function <HRESULT (IShellItem2 *)> fn) { ... fn (si); } Then to pass an additional parameter to your lambda, you can do: void ForEachShellItem(IShellItemArray *isa, std::function <H...
62,505,873
62,505,935
C++: Are local automatic variables initialized or not? Stroustrup example
The following example is from Stroustrup C++ 4th Ed. Page 519. It was my understanding from K&R C and earlier in the Stroustrup book that local automatic variables of primitive types are undefined or not known to be initialized. Static variables of primitive types or automatic variables of a class with a default cons...
It's easy. You can leave the built-in type variables uninitialized or you can ask the compiler to zero-initialize them. S s1; // string is default initialized, int is left uninitialized S s2{}; // All fields are initialized. Notice the {}. That (in this case) asks the compiler to initialize all fields.
62,505,922
62,506,057
C++ program returns "abort() has been called" with no other errors?
I'm trying to make a program that will request a string from the user and transform it into a letter pyramid (example below). Ex: If the user enters the string "12345" the program should display: 1 1...
There are some logical errors in second loop. strElement might be less than 0, because in int strElement = layerNum - 2, layerNum starts from 1. strElement Element decreases by 1 every loop, so it MUST be less than zero after several rounds. loop condition should be strElement> -1, so loop would be break once strEleme...
62,506,452
62,506,763
How to use winapi ReadProcessMemory with vector to read buffer from another process?
std::byte *ReadBytes(PVOID address, SIZE_T length) { std::byte *buffer = new std::byte[length]; std::cout << "length" << sizeof(buffer) << std::endl; ReadProcessMemory(this->processHandle, address, buffer, length, NULL); return buffer; }; I'm trying to read memory regions of a process into std::byte ...
Since C++11, std::vector::data will provide a pointer to the backing array. If you're using older tools without support for C++ 11, &buffer[0] probably works, I've never seen it not work, but is not guaranteed by the Standard. Looking at the code again, if you've got std::byte, C++11 support is not an issue. So... std:...
62,506,816
62,507,090
Compiler stating error 2059 for struct and int description
I'm (probably obviously) very new, and am attempting to build a calculator for my first project. I wanted to test my first concept, but upon compiling I get the 2059 error for the end brace of my InterFace struct as well as the first brace of my int AddUp. These seem like totally random errors. If it helps, the errors ...
You do not have the correct core concepts right, and should probably work through some C++ tutorials or courses before writing a program like this. A few things: The ± symbol is a unicode character. char in C++ refers to a single byte, usually an ASCII value if it's referring to text data. So it can't store the unicod...
62,508,064
62,508,231
How does count become 5 here?
I am learning the use of get() and put() in c++. I have the following two doubts: As we are in the while loop, why don't the characters get printed as soon as I enter them as there is a put right after the get? Why does count has the value 5 instead of 4? When I hit the Enter key, I will exit the loop(at least that's...
The loop first enters cin.get() and does not continue until you enter all your 4 characters. It has to have a new line to continue. After you enter all your 4 characters, the loop continues and reads the characters one by one. The value of count is 5 because it also gets incremented when you enter the new line. The new...
62,508,124
62,511,817
Sending encrypted message from php to a C++ App and decrypting then with CryptoPP
i am trying to send an encrypted message with AES-256-CRT that need to be encoded with a base16 hex cause CryptoPP HexDecoder does it in that way, but i can't decrypt the encrypted text in my C++ application how i can solve this? PS: I am using libcurl to make the requests from c++. Here is the code's: PHP File: <?php ...
I changed the file reading method and added a decryption function just to check that encryption is working properly. Please keep in mind that this method of reading is not good for large file encryption (it reads the complete file into memory) - in this situation you may need another solution. This is a very basic exam...
62,508,202
62,508,243
Understanding how C++ can return reference and bind to reference
#include <iostream> class A { public: int x = 0; }; A& a_returner() { A a; return a; } int main() { A& a = a_returner(); std::cout << a.x << std::endl; } In this code, a_returner() returns a reference to a variable a in the stack. If we called like this: A a = a_returner(); this wouldn't be a p...
You have a wrong mental model of what "works" mean. The code you have in the question does NOT work. It didn't crash when you tried and the result was what you were expecting, but that doesn't imply (in C++) that everything is fine. What you just discovered is the worst side of "undefined behavior", i.e. when you make ...
62,508,476
62,508,776
String as member of container which is a member of a C++ class
I have a class that has a set member variable. This set is going to hold a bunch of std::strings which are added to it throughout the life of the object. The strings are passed in from a calling function (they are created in the calling function). My understanding is that in C++ string objects have their destructors ca...
My understanding is that in C++ string objects have their destructors called as soon as they leave scope. So if I understand correctly, when the calling method which created the string exits scope, the destructor should be called. Yes, your understanding here is correct. But, in case of this line here: myStrings.inse...
62,508,522
62,508,663
How to skip the space and the new line from stringstream and put them in a vector?
I'm trying to read a text file that contains information of a person (name, age, occupation) as follows: name 20 occupation name 25 occupation name 34 occupation I read the whole file and for each line I used istringstream to skip the space between the name and the age. std::vector<string> readfile(std::vector<std::st...
You can do string mystr; while(file >> myStr) { string name = mystr; file >> mystr; int age = stoi(mystr); file >> mystr; int occupation = stoi(mystr); } As long as you know the order of information you are getting from your file you can follow the idea above. When you do file >> mystr it will get the n...
62,508,803
62,509,038
Updating label from another function in MainWindow in QT
I am new to QT. I created an application by a wizard. Its UI backend was created as below. QTimer *timer; // NEW void TimerSlot(); // NEW slot MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { //saveSetting(); loadSettings(); ui->setupUi(this); // this->l...
In this auto-creation of MainWindow class how can I declare private and public data and member functions, You can do that in the mainwindow.h file. class MainWindow { public: //... private: //... } How can I access this currentDateTime label from myFunc(). You cannot access it because TimerSlot function is not a m...
62,509,233
62,509,295
Break while()-loop using UDP
Is it possible to do some work, such as increment a counter, in a while()-loop, and then break this while()-loop with a UDP message? I have a Raspberry Pi 4, that is setup as a UDP-server. The programming language i'm using is C++. UDP.hpp: #pragma once #include <sys/socket.h> #include <netinet/in.h> #include <unistd....
Sure. Just set the socket non-blocking and periodically check if there's data received on the socket. If there is, check if it's a command to stop and, if so, stop. You can check every iteration of the loop or, if the loop repeats very quickly, every 10 or every 100 iterations.
62,509,347
62,509,726
Is new stack frame allocated for the block(conditional or unconditional) code in c/c++?
I looked at posts which differentiate between stack and heap allocations. I understand that stack frame is allocated for each function calls. But my question lies around the blocks inside the functions? How is memory managed/allocated for such code? How is the local storage size for such a stack frame created? class A;...
First, note this is a pure implementation detail, the compiler is free to do what it will so long as the result behaves as-if the original code were executed. Stack frames are simply a detail real hardware use to get there. That said, most real-world compilers will simply calculate all the stack space a given function ...
62,509,424
62,519,728
Libreoffice API (UNO) : text and data from xTextField
How can I get xTextFields from .odt document properly? I tried something like that, but it doesn't work (Any returns a nullptr address): Reference <XTextFieldsSupplier> xTextFieldsSupplier (xTextDoc, UNO_QUERY); if (!xTextFieldsSupplier.is()) return { }; Reference<XNameAccess> xTextFieldsInfo = xTextFieldsSupplier...
XTextFieldsSupplier has two methods, and it looks like you chose the wrong one. The method to get text fields is getTextFields(). Example code: Reference< XEnumerationAccess > xFieldsEnumAccess = xTextFieldsSupplier->getTextFields(); Reference< XEnumeration > xFieldsEnum = xFieldsEnumAccess->createEnumeration(); Refere...
62,509,609
62,514,136
Expand polygons with boost::geometry?
I know it is possible to add/subtract different polygons to/from each other via boost::geometry, examples can be found at different places in web. Now what I want to do is something different: I have a 2D polygon which I want to expand/shrink by a given size. So I'm not talking about a simple scaling-operation but abou...
This feature is called "Buffering" in the OGC Simple Feature Specification. Boost Geometry supports it for most 2D cartesian geometries (and you can easily do the rest by conversion), and points only in other coordinate systems. Documentation The available strategies: JoinStrategy: join_round (cartesian) JoinStrategy...
62,509,792
62,524,915
Iterating through a list in the destructor of its elements
When an element of a list is destroyed I want to iterate through the same list to see if it includes another specific element. This has to happen each time an element is removed. It works fine if the container is a std::vector but it seem to iterate outside the for-loop and crash if its a std::list. Is this undefined b...
This program has undefined behavior. In the declaration of the member variable list_, the type Element is an incomplete type, and you can't instantiate a std::list of an incomplete type. (So in some versions of a compiler, this may appear to work, but there is no guarantee that it will). Since c++17, std::vector can be...
62,509,913
62,510,090
Do std::promise::set_value() and std::future::wait() provide a memory fence?
If I do the following: std::promise<void> p; int a = 1; std::thread t([&] { a = 2; p.set_value(); }); p.get_future().wait(); // Is the value of `a` guaranteed to be 2 here? cppreference has this to say about set_value(), but I am not sure what it means: Calls to this function do not introduce data races with c...
From my reading I believe a is guarnteed to be 2 at the end. Notice the information about the promise itself (emphasis mine): The promise is the "push" end of the promise-future communication channel: the operation that stores a value in the shared state synchronizes-with (as defined in std::memory_order) the successf...
62,509,990
62,510,161
How to calculate expected number of turns using DP in O(n)?
A single-player board game. The board is made up of a row of n cells numbered 1 to n from left to right. Cell ‘j' contains a positive integer cj. The rules are like this: You start on the leftmost cell. On each turn, you roll a fair 6-sided die with A as the outcome number. You move forward A × cj cells, where j is th...
The recurrence relation you're looking for is: E[j] = 0 (if j > n) E[j] = 1 + 1/6 * sum_k(E[j + k * c_j]) (otherwise, for k \in 1..6)
62,510,216
62,511,958
I want to understand in detail distinct between expression and statement in C++. Pls pick concrete example to explain that
Now I am learning C++ programming. I didn't understand the distinction between expression, definition, declaration, and definition. As Wikipedia says, In "Statement(computer science)" In most languages, statements contrast with expressions in that statements do not return results and are executed solely for their side...
Concretely, What do "side effect" and "result" mean here? Expression has no side-effects, when removing it from source does not change program semantics. int main(void) { int x = 1, y = 2, z = 0; // x+y expression calculates sum and ignores resulting answer // NO SIDE EFFECTS, can be removed x+y; // ...
62,510,436
62,511,019
How to remove all sub paths?
I am a new in C++ (and I think there is should be much shorter way to do what I need), but what I need to do is: I have a vector of paths to folders C:\\Sessions\\MyFolder C:\\Sessions\\Calib C:\\Sessions\\Calib\\2020_04_30_18_02 C:\\Sessions\\Calib\\2020_04_30_18_03 C:\\Sessions\\Calib\\2020_04_30_18_02\\test C:\...
You start by sorting the given paths. However, the order in which it sorts is propably not what you expect. The reason is that sorting std::strings does not treat the directory separator \ in any special way. And \ sorts later than upper case characters, but earlier than lower case characters. What you would want is a ...
62,510,528
62,510,646
Which is more efficient inside a loop condition, i<sqrtN (pre-calculated) or i*i<N, in C++?
Suppose for a given integer N, I need to run a loop square root of N times. In C++, I can do it in these two ways like- 1) long long sqrtN = std::sqrt(N); for (long long i=1; i < sqrtN; i++) { // some piece of code } for (long long i=1; i * i < N; i++) { // some same piece of code } I found that std::sqrt(...
I found that std::sqrt() has O(logn) complexity. Also, I believe the multiplication of numbers is just a constant time operation. So far so good. You missed one detail. In the first you call sqrt once, in the second you compute i*i in each loop iteration. Hence it is actually O(log n) vs O(sqrt(n)), ie computing the ...
62,510,801
62,515,428
circular_buffer and managed_mapped_file segmentation fault
I am using boost 1.73.0, and am trying to use circular_buffer together with manage_mapped_file to store strings in a circular buffer persisted on disk. I do the following to create/open the circular_buffer: boost::interprocess::managed_mapped_file mmf(boost::interprocess::open_or_create, "./circ_buffer.bin", 10u << 10)...
boost::interprocess::managed_mapped_file mmf(boost::interprocess::open_or_create, "./circ_buffer.bin", 10u << 10); typedef boost::interprocess::allocator<std::string, boost::interprocess::managed_mapped_file::segment_manager> string_allocator; typedef boost::circular_buffer<std::string, string_allocator> circ_buf; circ...
62,510,826
64,427,979
Assigning to const char * in constexpr constructor (c++17) fails using Android NDK
I'm trying to use a modified version of the compile-time string classes described in this nice post: https://akrzemi1.wordpress.com/2017/06/28/compile-time-string-concatenation/ The reason for this is that a bunch of string literals need to be adapted based on a compile time constant, so it would make sense to do this ...
Months later I actually noticed that if I explicitly initialize the array_string member, it works on android as well. template<int N> class array_string { char _array[N + 2 + 1]{}; // use default {}-initialization public: // ... see code from question
62,511,125
62,512,062
Generating prefix bitmasks
I am looking for a portable way to generate prefix bitmasks which have the first n bits set for 0 <= n <= 32 (or 64 or an arbitrary integer type bit width). Examples: prefix_bitmask(0) = 0b00000000000000000000000000000000u prefix_bitmask(4) = 0b00000000000000000000000000001111u prefix_bitmask(32) = 0b1111111111111111...
((uint32_t) 1 << i/2 << i-i/2) - 1. The above works where uint32_t may be replaced with any unsigned type. and no other changes are needed. Other options that require knowing the number of bits b in the type and a mask m = 2b−1 include: ((uint32_t) 1 << (i & m)) - 1 - (i >> b) (from supercat) and: ((uint32_t) i >> b) ^...
62,511,157
62,511,249
How do I adapt an old C style #define mapping with modern C++?
In an old C header file, I have the following mapping (32 lines long): #define IOCON_INDEX_PIO0_17 ( 0) #define IOCON_INDEX_PIO0_13 ( 1) #define IOCON_INDEX_PIO0_12 ( 2) //... In C++ I could have a function that takes an index and returns an int. To do so I would initialize an array in only ...
Using c++17 changing const std::array<int, 32> iocon_index = [](){ std::array<int, 32> buf; to constexpr std::array<int, 32> iocon_index = []() { std::array<int, 32> buf { }; seems to solve the assembly size issue (-O2 and -Os) In c++14 you can use a constexpr function instead of a lambda to initialize the ar...
62,511,730
62,511,922
Rectangle is not drawed properly?
Hello i want to draw rounded rectangle without any function, but first I tried to draw simple rectangle but it is not drawed properly. What is wrong ? int main() { Mat frame = Mat::zeros(300,300,CV_8UC1); //frame = duzKare(50); for (int i = 0; i <= 50; i++) //col { for (int j = 0; j <= 10; j++...
try <u_char> instead of <int> in frame.at<int>(i, j) = 255; CV_8UC1 means the value of each pixel is stored as an unsigned char (u_char in OpenCV) which is 8-bit while int occupies more than 8 bits
62,511,795
62,513,857
How to fetch a memory location in C++ without waiting for its retrieval?
Suppose we want to fetch a value from an array. In some cases, we know that the data is in data[i]. In other cases, we need to move the index by some offset: i += offset[i] i = .... FETCH data[i]; // The result could be here if the offset_shifts is 0 // Or if i is very small (data[i] is...
In portable C++, I'd solve it as follows: result = data[i]; // Unconditional! auto offset = offset_shifts[i]; if (offset) result = data[i+offset]; The rationale is that result is likely just a register, so result = data[i]; is effectively just a read. This will start the read, but not block the CPU pipeline for the...
62,512,209
62,512,438
When can values of variables be unexpectedly changed in C++?
I am having trouble understanding why there are some options in c++ in order to avoid changes in variables value if an exception is always thrown which alerts the user that you are redefining a variable. I am referring for instance, to defining a variables as: const int x=55 ; In my short experience with C++, I can't t...
The value of a const int will not change through the lifetime of the object in a well defined program. Neither expectedly nor unexpectedly. If the behaviour of the program is undefined, then there can be any behaviour including what you expect, and what you don't expect. Undefined behaviour is to be avoided.
62,512,370
62,515,308
ASIO signal_set not reliable with multiple IO threads, depending on code order?
Edit: I can no longer reproduce this problem. Without changing anything, the signal_set works reliably regardless of the ordering of blocks now. I am using (standalone) ASIO in a program, and in order to shutdown gracefully on Ctrl+C, I use a signal_set. Everything works well when only my main thread calls io_context.r...
Yes you can rely on it. I'm personally mildly surprised that you saw the effect you report with the blocks in order (#1,#2). I can't reproduce it either: Live On Coliru #include <boost/asio.hpp> #include <iostream> namespace boost::asio { using boost::system::error_code; // huh - maybe this is a non-boost Asio thi...
62,512,516
62,514,664
Scanf throws a random exception when I try to use it(same for scanf_s)
Here is the code: #include <iostream> #include <stdio.h> int main() { char name[15]; printf_s("What is your name: "); scanf_s("%s",name); printf_s("Nice to meet you, %s", name); return(0); } Please help idk whats wrong. Im doing this in VS2019 and using c++ if that helps.
You can just use scanf instead of scanf_s, to silence the error you can write "#define _CRT_SECURE_NO_WARNINGS" on top of your code. Difference between scanf and scanf_s is, in scanf_s you can specify buffer size and control the size of an input to avoid crash. It's not necessary in this level but i suggest you to look...
62,513,481
62,514,025
find if a structure already exists in a vector c++
I have to find the weight between all edges in a graph, so since the edges are bidirectional I dont want to include 2 -> 1 if I already have 1 -> 2 (since they will have the same weight). The edges are stored in a vector from structure Edge. My initial idea was to look up, if an edge that has the start and end position...
since the edges are bidirectional You can construct Edges such that v1 <= v2, then there is only one representation of each possible edge. struct Edge { Edge(int va, int vb, int w) : vi1 {std::min(va, vb)}, vi2 {std::max(va, vb)}, weight {w} { } int vi1; // earlier point int vi2; // later point ...
62,514,315
62,522,951
Constant function when its parameter is a reference to literal type
constexpr int func(int const& rf){ return rf; } int main(){ constexpr int value = func(0); } Consider the above code ,it will be compiled and it's well-formed, However I'm confused about this. According to [[stmt.return#2]] the return statement initializes the glvalue result or prvalue result object of the (expl...
So, I think the return statement would be equivalent to the following If by equivalent you mean that it would be copy-initialization had it been valid, then yes. But it's not valid, so to call it equivalent is not correct. However, as the equivalent form, I wonder why the first code is well-formed when the object va...
62,514,325
62,898,104
How to get file size in Windows kernel
I need to get file size in Windows kernel. I read the file into a buffer in kernel, while the code is as below. And I dig out a lot. // read file //LARGE_INTEGER byteOffset; ntstatus = ZwCreateFile(&handle, GENERIC_READ, &objAttr, &ioStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN, FI...
GetFileSize is not a WDK function. Use ZwQueryInformationFile instead of GetFileSize. Use the codes below FILE_STANDARD_INFORMATION fileInfo = {0}; ntStatus = ZwQueryInformationFile( handle, &ioStatusBlock, &fileInfo, sizeof(fileInfo), FileStandardInformation ); ...
62,515,113
62,515,594
Why Can't Make a Reference To Pointer for Constant Assign a String Literal
I can make pointer point to string literal, it will cast string literal to constant pointer, but reference to pointer can't assign string literal, for example: const char *&text = "Hello, World\n"; There's an error, the compiler says I can't cast an array to pointer reference, I am curious about it, why it isn't it ...
The conversion to a const char* can be seen as temporary returned by value. You can't bind a reference to a non-const temporary. To extend the life of a temporary you would have to make the pointer const too. If that's not an option, you'll have to bind the reference to a pointer that is not temporary. Example: #includ...
62,515,379
62,515,670
Recursion program doesn't work for big inputs
I tried to write an answer to the question from this site - https://main2.edu.pl/c/kurs-podstaw-algorytmiki-druga-e/p/kro/ It's addition to lesson about recursion so I came up with a code that uses it. It should show (a+1)^b modulo-10000 remainder. Unfortunately, for small numbers my program works, but when it reaches ...
Instead of taking the remainder only of the final result, you should take it every time pot returns a value. The result should be correct, since you're just multiplying the results by things, and (x*y) % m should equal ((x % m) * (y % m)) % m for positive x, y, and m. Try this: int pot(int a, int b){ int r; if...
62,516,121
62,721,752
Using QTeeView instead of QTreeWidget
I am a total noob in QT and C++. Sorry if I have asked something very fundamental. I have designed a QTreeWidget that looks something like this. The values inside of this TreeWidget are shown for a particular device 'X'. The functionality I am looking for is, how do I change/display/replace values(basically change num...
The advantage of using QTreeView over QTreeWidget is its performance. If you are planning on displaying an insane amount of rows (e.g. > 1000) and are planning on having custom controls in those rows (QComboBox is the most expensive one), then QTreeView is better. The reason that QTreeView is more performant is because...
62,516,599
62,518,285
Convert boost serialized object's asio::streambuf representation into Beast's DynamicBody req.body()
// Serialize using boost serialization boost::asio::streambuf binary_buffer; boost::archive::binary_oarchive archive(binary_buffer); archive << world_map; //beast::buffers_adaptor<boost::asio::streambuf>(binary_buffer); req.body().data() = beast::buffers_adaptor<boost::asio::streambuf>...
With dynamic_body the body() is actually a multi_buffer. So you would need to copy into that: req.body().prepare(binary_buffer.size()); req.body().commit(binary_buffer.size()); auto n = asio::buffer_copy(req.body().data(), binary_buffer.data()); Example: req.body().prepare(binary_buffer.size()); req.body().commit(bina...
62,517,244
62,519,885
extern in namespace scope - gcc vs clang vs msvc
I've tested the seemingly strange code example below with the newest gcc, clang, and MSVC; both clang and gcc give link errors, but MSVC compiles and links without any problem. Which one is correct? // foo.h #pragma once namespace A { class foo { public: foo(); void print(); }; } // f...
Both GCC and Clang are standard compliant. The example and explanation are given in the standard [basic.namespace]/4: The enclosing namespaces of a declaration are those namespaces in which the declaration lexically appears, except for a redeclaration of a namespace member outside its original namespace (e.g., a defin...
62,517,702
62,523,337
atomic operations on a variable which is in OpenMP reduction clause
I have a following piece of code. Its idea is very simple. There are billions of events in my full program and I need to count some of them not using long int type. So, I have to use 2 int numbers HIT and COUNT istead of 1 int number because there will be an overflow of 1 int variable (very big loop count). #include <f...
A simple + reduction won't work for two integers that aren't exactly summed independently, but since OpenMP 4.0 you can declare your own reductions. All you need to do is abstract the two parts of the counter in a class (or struct) and define a function that sums such objects. In the example below, an overloaded compou...
62,517,752
62,519,763
Scheduling a coroutine with a context
There are plenty of tutorials that explain how it's easy to use coroutines in C++, but I've spent a lot of time getting how to schedule "detached" coroutines. Assume, I have the following definition of coroutine result type: struct task { struct promise_type { auto initial_suspend() const noexcept { return std::s...
I think your problem is a general (and common) misunderstanding of how co_await coroutines are intended to work. When a function performs co_await <expr>, this (generally) means that the function suspends execution until expr resumes its execution. That is, your function is waiting until some process completes (and typ...
62,517,887
62,576,528
How to send a REST call with Qt?
I have started started working with Qt framework and after reading the documentation for Qt5 and some examples across some blogs, I wrote the following program but I does not seem to do the correct job. I am writing a class for which I need to write a method Login and logout. For login method, I am writing following co...
Cause As you say, the program goes into infinite loop. The very one you have created: while (!reply->isFinished()) { // wait for the request to complete } Simply put, with QNetworkReply* reply = m_manager.post(loginRequest, QJsonDocument(body).toJson()); you do not send a request, but merely declare your wish to d...
62,518,085
62,519,307
Boost locale normalize strips characters but no accents
I am trying to strip accents from a string using the boost local library. The normalize function removes the entire character with the accent, i only want to remove the accent. è -> e for example Here is my code std::string hello(u8"élève"); boost::locale::generator gen; std::string str = boost::locale::normalize(hello...
That's not what normalize does. With nfd it does "canonical decomposition". You need to THEN remove the combining character code points. UPDATE Adding a loose implementation gleaning from the utf8 tables that most combining character appear to lead with 0xcc or 0xcd: Live On Wandbox // also liable to strip some greek c...
62,518,210
62,518,619
Most vexing parse even more vexing
In the following code #include <map> #include <string> struct P2d { double x, y; P2d(double x, double y) : x(x), y(y) {} }; double bar() { std::map<std::string, int> m; //P2d lp = P2d(double(m["x"]), double(m["y"])); // this works P2d lp(double(m["x"]), double(m["y"])); return lp.x; } all com...
Hold on to your chair since it's pretty funny. As you surely know C++ allows array function parameters. And so you can get this: void foo(double s[2], double b[2]); This is obvious. A possible obfuscation step is to replace spaces between type and parameters name which is also allowed: void foo(double(s[2]),double(b[2...
62,518,682
62,519,375
is C++ abstraction Endian neutral?
Suppose I have a client and a server that communicate 16 bits numbers with each other via some network protocols, say for example ModbusTCP, but the protocol is not relevant here. Now I know, that the endian of the client is little (my PC) and the endian of the server is big (some PLC), the client is written entirely i...
(static_cast<uint16_t>(high)<< 8) | (static_cast<uint16_t>(low)) has the same behaviour regardless of the endianness, the "left" end of a number will always be the most significant bit, endianness only changes whether that bit is in the first or the last byte. For example: uint16_t input = 0x0201; uint8_t leftByte = in...
62,518,948
62,519,093
Why is needed to check if GLAD or GLEW was initialized correctly?
I was setting up opengl using GLFW + GLAD or GLEW (#include glad/glad.h #include <GL/glew.h>). After the function glfwMakeContextCurrent(window); I need to check if GLAD or GLEW was initialized correctly or I will run into exception errors in Visual Studio 2019. #include <glad/glad.h> #include <GLFW/glfw3.h> #include ...
Here I am using GLAD. I really can't understand why I have to check this if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) The key point here is not the check, but the call to gladLoadGLLoader which actually initializes GLAD and loads all the GL function pointers. So what you do here is initializing GLAD, and...
62,518,959
62,519,065
Why do I get a "no matching function" error when I open an fstream with the file name in a std::string?
I am trying to write a program that reads in a list of strings from a file and checks what strings are missing from a second file and prints them to the screen. However, I am currently getting an error when I try to compile. Below is the error I am getting when I try to compile as well as the code. Thank you for the he...
This construct works for standard C++ 11 and newer compilers: std::string filename; //... IN_FILE.open(filename); This is basically the code you have now. However, the above will not work with pre-standard C++ 11 compilers (C++ 98, 03). If you are compiling using a pre-standard C++ 11 compiler, then the code above sh...
62,519,018
62,519,046
Extra zero char at end of string appears in C++ for range loop
The following code #include <iostream> #include <string> int main() { std::string s = "abc"; for (char c : s) std::cout << (int) c << " "; } prints "97 98 99 ". The following code #include <iostream> int main() { for (char c : "abc") std::cout << (int) c << " "; } prints "97 98 99 0 ". Whe...
The literal "abc" is a const char[4] type: the final element is the NUL terminator (with value 0). In the second snippet, the value of the NUL terminator is printed as the code is describing an iteration over that entire const char[4] array. In the first snippet, the underlying iterator technology of the std::string cl...
62,519,709
62,520,236
Doing conditional replacement using c++ macro?
For a struct point{float x,y,z;}, i want to define many functions, in each function, i do the same thing to x, y and z. For example, float size = 1 * x*y*z, float edge = 0+x+y+z... So I'm wondering that, i could write a macro, or something, like #define forxyz(codes) ??????? that when i write forxyz(res=res+d;) it call...
This is the answer that answers the macro part and I would advise to provide operators overloads if possible and not to use macros in C++. So first create your own small overloaded foreach macro that will apply a function on each argument: #define M_FOREACH_1(func,_1) \ func(_1) #define M_FOREACH_2(func,_1,_2) ...
62,519,920
62,521,450
Changing the Gain in OpenCV's Kalman Filter to make it more responsive
For a tracking a bounding box position and velocity in the image, where the measurements are not very noisy, but the bounding box moves very fast state_size = 6; // x,y,w,h,vx,vy of BB meas_size = 4; // x,y,w,h of BB contr_size = 0; int type = CV_32F; initializing transition, process noise, and measurement noise with ...
The Kalman Filter is a linear filter that is optimal for linear systems with gaussian noise. Assume there is no noise and your system is perfectly linear. The transition matrix hence describes how the state changes and is not updated by the kalman filter. If the transition matrix is just the identity it means the state...
62,520,027
62,520,124
getting multiple definition error when compiling source code
I have a simple c++ app: node.h: #include<iostream> using namespace::std; class Node { private: int data; Node *next; public: Node(int nodeData,Node *nextNode); }; node.cpp: #include "node.h" Node::Node(int nodeData, Node *nextNode) { data = nodeData; next = nextNode; } linked_list.h #include...
Your linked_list.h includes node.h, so the compiler will see the definition in node.h twice while compiling main.cpp. To avoid this problem, you should add "include guard" to your header files. It should be like this: node.h: #ifndef NODE_H_GUARD // add this #define NODE_H_GUARD // add this #include<iostream> using n...
62,520,184
62,520,366
Why I'm getting WA(Wrong Answer) in CMPRSS problem of codechef?
I'm getting WA(Wrong Answer) in "Compress the List" problem Code(CMPRSS) of CodeChef, here is the link of the problem: https://www.codechef.com/problems/CMPRSS I've checked the sample output given in the problem and also some self made test cases and It's working properly.I'm not getting what's wrong in my code here is...
You forgot to check if number[temp+1] exists in the part while (number[temp+1]-number[temp]==1){ temp++; count++; } Therefore, it may read beyond the array and produce wrong output. Try this case: 2 5 1 2 3 4 5 3 1 2 3 The part should be like this: while (temp+1 < static_cast<int>(number.size()) && number[t...
62,520,419
62,520,557
How to create a json object from scratch in c++ using picojson.h
Trying to serialize a class I have into a json string. Of course I can just write the strings manually, but I was hoping to utilize a the picojson library. What I am trying to achieve is, given this class A class A { public: int field1; string field2; } A a; a.field1 = 1; a.field2 = "example"; I want to con...
Well completely of the top of my head, and just by looking at the header file, it seems you need something like this using namespace picojson; object o; o["field1"] = value(static_cast<double>(a.field1)); o["field2"] = value(a.field2); std::cout << value(o); or (what you actually asked for) std::string s = value(o).s...
62,520,652
62,600,718
How to get chained values in case of Collision in unordered_map?
If the unordered_map in c++ uses chaining as collision resolution. How can the chained values /Linked lists be accessed? unordered_map<int,int> diff; //collision : inserting two entries with same key 1 diff.insert(make_pair(1, 7)); diff.insert(make_pair(1, 26)); cout<<diff[1]; The output is just 7...
This question shows a misunderstanding of how chaining is used, and what people normally mean by a collision. In your example code: unordered_map<int,int> diff; //collision : inserting two entries with same key 1 diff.insert(make_pair(1, 7)); diff.insert(make_pair(1, 26)); The two insertions have the same key, so they...
62,520,713
62,521,347
Determine the amount of points needed to convert an arc to line segments
The arc is defined by start_point, sweeping_angle, and center_point. If given a parameter "tolerance", which is the error between original arc and line segments. How do I calculate the minimum amount of points needed to convert this arc into line segments?
The largest deviance between small arc of angle theta and its chord is at the middle, and value of this deviance is (versine) tol = R * (1-Cos(theta/2)) Having N arcs SweepAngle = N * theta theta = SweepAngle / N tol = R * (1-Cos(SweepAngle / (2N))) tol/R = (1-Cos(SweepAngle / (2N))) Cos(SweepAngle / (2N)) = 1 - tol/...
62,520,731
62,523,297
Is it possible to determine the size of a type from the types of its data members
Problem: Consider the following type: struct S { std::uint8_t a; std::uint32_t b; }; Is it possible to determine sizeof(S) from std::uint8_t and std::uint32_t solely? Context: I'm developing a code where S is actually a template type more verbose than this illustration-purpose one, so I thought in defining a t...
Yes. If the types and order of the object's members are known, and if all members have the same access specifier (e.g. public), and if the object lacks a vtable, you can rebuild the object's structure within a helper class and use the size of that: template<typename... Ts> struct struct_traits { static constexpr st...
62,520,770
62,524,051
How to convert UTF-8 text from file to some container which can be iterable and check every symbol for being alphanumeric in C++?
I read around 20 questions and checked documentation about it with no success, I don't have any experience writing code handling this stuff, I always avoided it. Let's say I have a file which I am sure always will be UTF-8: á Let's say I have code: wifstream input{argv[1]}; wstring line; getline(input, line); ...
L"á" means the file was read with a wrong encoding. You have to imbue a UTF-8 locale before reading the stream. wifstream input{argv[1]}; input.imbue(std::locale("en_US.UTF-8")); wstring line; getline(input, line); Now wstring line will contain Unicode code points (á in your case) and can be easily iterated. ...
62,521,207
62,522,069
Find factorial Using call by reference function in C++
I am missing very minor thing here i could not figure it out, i am just try to get the factorial of the number inputted, using a recursive call by reference concept in C++. Please let me know what am i missing. Declaring few additional variables for more further alterations in programs. #include <iostream> using namesp...
The errors in your program: It tries to bind a non-constant lvalue (roughly it means a variable that could be assigned in the left hand side of = sign) reference of type an integer reference (from argument) to an rvalue of an integer in the syntax: return m * factorial(m - 1); Passing a reference is not required he...
62,521,569
62,540,967
Compilation of the simple pybind example fails on macos
I'm trying to implement the simple add function example in the pybind11 docs. I'm using the default mac python3 (3.7.7), and have installed pybind11 by pip3 install pybind11. There is an example.cpp file: #include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { ...
It turns out that I had to add pybind11 to my path separately: export PYTHONPATH=$PYTHONPATH:/usr/local/include/python3.7m/pybind11/
62,521,687
62,522,175
How can I use static members in friend functions without prefixing [class name]::
I have this code in Player.h class Player { friend void clearBoard(); private: static char board[4][4][4]; }; and this code in Player.cpp char Player::board[4][4][4] = {}; void clearBoard() { for (byte i = 0; i < 4; i++) for (byte j = 0; j < 4; j++) for (byte k = 0; k < 4; k++) board[i][j][k]...
In general typing less is not a way to improve readability. Writing Player::board is good because if you write board outside of Player then it is not clear where it comes from. Having said this, you can always introduce an alias if a variable name is too long and you are too lazy to type its name repeadetely: void clea...
62,522,958
62,526,899
MSBUILD cannot build solution with Mixed Platforms?
I am upgrading batch file that needs to now restore nuget and build a solution that contains both c# x86 and c++ Wind32 projects - it used to use devenv just fine before the nuget additions. The solution is 'Mixed Platforms'. How do i do this with MSBuild? I can't specify x86, as the Win32 c++ projects then don't ge...
MSBUILD cannot build solution with Mixed Platforms? I think you should check your Mixed Platforms which you created carefully. I suggest you could create Mixed Platforms in this way. If you already used this way, you should check every step carefully. Solution First of all, remove or delete the previous Platform Mixe...
62,523,093
62,523,094
Compile LLVM from sources on macOS Catalina (How to solve "stdio.h" not found)
I'm bringing to your attention a question I tackled with for a few days and no issue could solve for me, in the hope that it'll save some other people time. I try to compile LLVM from sources on macOS Catalina (10.15). To do so, I used the following commands (after following the LLVM build manual): git clone https://gi...
System headers new path Since macOS Catalina, the /usr folder is been mounted as a read-only directory, so even as a root - no one has permission to modify this folder (well, unless you reboot in SIP mode, which's obviously not a considerable solution). The entire toolchain is saved by default under /Applications/Xcode...
62,523,264
62,555,935
How to properly set an API call in QML using XMLHttpRequest
I am building a small weather API as exercise to use QML and properly operate an API call using OpenWeather and you can see there a typical API response. The problem I am having is that I can't get the API call to work. After setting a minimal example with some cities that you can see below, right next to the city it s...
Below the answer to my question. I was not reading properly the JSON file and after console logging the problem the solution is below. code was correct from beginning, only the response needed to be reviewed properly and in great detail being the JSON response a bit confusing: function getCondition() { var request ...
62,523,431
62,545,953
correlation of a fit from colPivHouseholderQr().solve
I have some C++ code that is getting a bunch of X,Y values and doing a linear fit Eigen::Matrix<float, Eigen::Dynamic, 2> DX; Eigen::Matrix<float, Eigen::Dynamic, 1> DY; For loop over the data values (edited a bit because my data source is a bit more complicated than simple arrays): { DX(i,0) = x[i]; DX(i,1) ...
I'm assuming you are looking to compute the R² coefficient of your least-square fitting. Linear least squares First, let's recap what you're doing. In your Dsolution vector are two coefficients (lets call them a and b, which are your estimated parameters for an affine model between your xs and your y s). This means tha...
62,523,810
62,524,855
How to convert a Python deque to a C++ container?
I have to pass a Python deque to a C++ function but I can't find any documentation on how to convert a deque to a C++ container (for this case, either a deque or a vector would do). Searched everywhere but I couldn't find a solution. There's gotta be a simple way to do this right? Thanks
There's no "simple way". You'll need to do that by hand (or maybe with some kind of interface generator), in a data-specific way. Take a look at C API Introduction — Python 3.8.3 documentation for an overview of Python data model at C level. It has absolutely nothing to do with any C++ types. You'll need to somehow ext...
62,523,977
62,527,824
Check if combobox is opened
How can I check if the combobox's dropdown list is opened? (https://learn.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Controls.ComboBox?view=winrt-19041)
You can subscribe the DropDownOpened event which will be triggered when you try to open the dropdown list or use IsDropDownOpen property to judge whether the drop-down portion of the ComboBox is currently open. .xaml: <ComboBox x:Name="MyComboBox" DropDownOpened="MyComboBox_DropDownOpened"> <ComboBoxItem>123</Combo...
62,524,341
62,524,482
C++ - Explicit & Implicit Namespace Implementation Differences
I have a question about namespaces if someone can enlighten me :D I don't know if the title is right, I hope so xD Code in the ".cpp" file is called the Implementation of the Namespace and the code in ".h" file is called the Declaration of the Namespace? right? :/ Anyway, my Question is: there is any difference by Expl...
In general, there is no difference between the 2 versions you have shown, and you can use whichever one you prefer. For what it's worth, here's one case where it differs slightly: namespace A { struct S{}; S f(); // declare f } and then: namespace A { S f() { return S{}; } // define f, ok } is fine,...
62,524,359
62,524,530
Return 2D char array from function in c++ and print it
This is my code and I want to return 2D dimension array [10][8] and [10][20] from my function, but i get an error !! (Segmentation fault). Please help me !! I need this for my project. Finally i want to print this array and I cant do this because of the error. Can someone help me fix this and print that? #include <iost...
By doing char **words = new char *[10]; You are only allocating memory for the pointers, not for the memory blocks where the actual strings are to be stored, you need to allocate memory for that too: char **words = new char *[10]; //space for 10 pointers for(int i = 0; i < 10; i++){ words[i] = new char[10...
62,524,493
62,524,643
Compilation error when restricting template parameters of derived class with std::enable_if
This compiles: template<typename T, class T2, class = typename std::enable_if<std::is_arithmetic<T>::value, T>::type> class ENABLE{ public: T a; ENABLE(T b): a(b) {}; }; template<typename T, class T2> class ENABLE_CHILD : public ENABLE<T, T2> { public: ENABLE_CHILD(T x): ENABLE<T, T>(x) {}; bool...
I got a different error when pasting this code into godbolt.org. You need to include the third template parameter on your member function definition as well: https://godbolt.org/z/kxpvQt template<typename T, class T2, class Enable> bool ENABLE_CHILD<T, T2, Enable>::FOO(auto a) { return(1); };
62,524,536
62,524,637
Limit using/typedef to class scope
I need to store a function prototype inside of a class somehow, but it automatically becomes a global when I try to do so. The prototype is given trough a template, but I cannot use it straight out of there as I use it inside of thread member function which has to be static (Because otherwise, I break the callback prot...
You can use void (*addr)(); This declares addr as a member variable of type void (*)(). You can make it more readable by using. using my_ptr_type = void (*)(); my_ptr_type addr;
62,525,092
62,525,526
CMake: add conditional compiler flags into Visual Studio project
Visual Studio allows to select either the cl compiler or the clang-cl compiler to build projects -- these are called toolsets. These two compilers have different sets of flags, and in particular different flags for disabling warnings. Flags for one compiler produces errors on the other. This problem can be solved in Vi...
You can use CMAKE_CXX_COMPILER_ID and CMAKE_CXX_SIMULATE_ID with your favourite way of handling compilers (if-else or generator expressions) Output for -T ClangCL (Visual Studio 2019): message(STATUS ${CMAKE_CXX_COMPILER_ID}) // Clang message(STATUS ${CMAKE_CXX_SIMULATE_ID}) // MSVC Output with no toolkit (Visual Stud...
62,525,434
62,525,541
How can I download a string from a URL in a C++Builder VCL application?
I want to download a string from a URL that would essentially look like this: https://website.com/File.txt In C# WinForms, I know I can do this: using System.Net; WebClient client = new WebClient(); string str = client.DownloadString("https://website.com/file.txt"); And the string would be stored in str. I want to d...
There are plenty of HTTP libraries that are available for C++Builder. It even comes with 2 pre-installed: Indy's TIdHTTP component #include <IdHTTP.hpp> TIdHTTP *client = new TIdHTTP(); String str = client->Get(_D("https://website.com/file.txt")); delete client; Embarcadero's THTTPClient component: #include <System....
62,525,697
62,527,068
why can't I express 10 power 10
I tried to express 10 power 10 but it didn't work, so I thought the problem is the range of the data type. Finally I changed the type from int to __int64 but it isn't yet working. #include <iostream> #include <cmath> using namespace std; int main() { int a, r, n; __int64 d; cin >> a; // a=10 cin >...
You're trying to convert __int64 into int which can't hold values like 10000000000 in the cout statement. Don't confuse between __int64 (holds 8-bytes data) and int (holds 4-bytes data). Simply remove the conversion int().
62,525,799
62,530,823
Using copy assignment in derived class
The cppreference says: Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignm...
From C++11 Standards#12.8 [emphasis added]: 24 Because a copy/move assignment operator is implicitly declared for a class if not declared by the user, a base class copy/move assignment operator is always hidden by the corresponding assignment operator of a derived class (13.5.3). A using-declaration(7.3.3) that brings...
62,525,806
66,267,120
What does __MACH__ mean for an #ifdef?
I am just going through some code and have come across an #ifdef that is: #ifdef __MACH__ #define CLOCK_REALTIME 0 int clock_gettime (int /*clk_id*/, struct timespec *t) { struct timeval now; int rv = gettimeofday(&now, NULL); if (rv) return rv; t->tv_sec = now.tv_sec; t->tv_nsec = now.tv_usec * ...
__MACH__ is a built in compiler macro that indicates if you are on Macintosh operating system. It is defined when compiling on a mac machine.
62,526,044
62,526,067
When I print the creation time of a file, why is it +7:00 hours ahead of the actual file creation time?
A strange thing is happening when I print the creation time of a file in my program. This problem happens on my Mac machine as well as my Windows machine. The creation time my program outputs is exactly 7 hours AHEAD of the actual creation time(that i check in the file's properties). For example, in properties, the cre...
The gmtime function gives you the UTC time (the gm refers to Greenwich mean time despite the fact they are subtly different things, one a standard and one a zone), not the local time. Hence you're almost certainly in a time zone seven hours away from UTC. If you want local time, I'm sure there's a function lying around...
62,526,234
62,526,394
Read elements from a txt file that are separeted by a character
I'am working on a program where there are first names, last names and a numbers on a file and i need to read that information into my program. My actual problem is that there is people who doesnt have a second name or second last name. To solve the issue I started trying to read from a file until a specific character i...
It's just a matter of using std::getline with a delimiter character to read out of the string stream. See a simplified example (no error checking) below: for (std::string line; std::getline(std::cin, line); ) { std::string firstName, lastName; std::istringstream iss(line); std::getline(iss, firstName, ',')...
62,526,714
62,526,918
C++ Using Visual Studio 2020 cant use .length()
I am sorry if this is really basic but I just started and am extremely confused. I am trying to find the length of a string s using .length() I have included #include , #include "genlib.h"and #include "simpio.h", but am still getting an error. #include <iostream> #include "genlib.h" #include "simpio.h" #define MAX_HAS...
By looking at your error message, it looks like you're using the Visual Code IDE, not Visual Studio. The reason why you are experiencing the error is because it does not recognize s as a string because you have not defined it as such. Even though you declared s to be of type string, it is not the std string. The data t...
62,526,973
62,527,063
What is the runtime complexity of std::map in C++?
I'm still a little confused about what the runtime complexity is of a std::map in C++. I know that the first for loop in the algorithm below takes O(N) or linear runtime. However, the second for loop has another for loop iterating over the map. Does that add anything to the overall runtime complexity? In other words, w...
The complexity of a map is that of insertion, deletion, search, etc. But iteration is always linear. Having two for loops like this inside each other will produce O(N^2) complexity time, be it a map or not, given the n iterations in the inner loop (the size of the map) for each iteration of the outer loop (the size of ...
62,527,074
62,527,267
adding ipv6 support to Rainmeter
I'm trying to edit PluginSysInfo from the Rainmeter API to include IPv6 support. I have modified the code from SysInfo.cpp to do so as far as I know the included link has the edits I've made to SysInfo.cpp. When I build it in Visual Studio "identifier GetTcp6Table undefined" and "identifier PMIB_IP6TABLE undefined" eve...
There is a known conflict between the Win32 headers <winsock2.h> and <windows.h>, see for example 1, 2. The Microsoft documentation recommends to use one of two #include sequences. Without <windows.h>: #include <winsock2.h> #include <ws2tcpip.h> With <windows.h>: #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_...
62,527,402
62,527,732
Is it possible to mix SFINAE and template specialisation?
Here is what I am roughly trying to achieve: // the declaration template<typename... Args> struct ArgsEstimate; // specialisation for string, SFINAE would be overkill template<typename... Args> struct ArgsEstimate<std::string&, Args...> { static const std::size_t size = 64 + ArgsEstimate<Args...>::size; }; // spe...
Direct answer to your question You can, but you really can't. Your case is complicated by variadic template arguments. // specialisation for arithmetic types template<class AirthmeticT, class... Args> struct ArgsEstimate< AirthmeticT, std::enable_if_t<std::is_arithmetic_v<AirthmeticT>>, Args...> { stati...
62,527,619
62,542,032
C++ error while loading shared libraries: libopencv_ximgproc.so.4.4
I recently built OpenCV 4.4 with some contributed modules, but I cannot call them from C++. What I did From the make install output: ... -- Installing: /usr/local/lib/libopencv_ximgproc.so.4.4 -- Set runtime path of "/usr/local/lib/libopencv_ximgproc.so.4.4.0" to "/usr/local/lib" -- Installing: /usr/local/lib/libopencv...
After a good night's sleep, I realized I didn't run ldconfig after installing the library. I run that, and the problem in the OP goes away.
62,528,083
62,546,060
Add polygons with boost::polygon does not compile?
May be this is a stupid question and only a simple issue, but I fail compiling a relative simple code. What I try to do is to add/concatenate two polygons using boost::polygon (some pseudocode showing the relevant parts): #include <boost/polygon/polygon.hpp> boost::polygon::polygon_with_holes_data<int> baseData; /...
The only operators I see mentioned in the documentation are on polygon sets Also, note: Operators are declared inside the namespace boost::polygon::operators. So, making sure to actually use them: Live On Coliru #include <boost/polygon/polygon.hpp> #include <boost/polygon/polygon_set_data.hpp> #include <boost/polygon...
62,528,183
62,528,240
c++ try and catch not ending program
I know this is a lot of code but it's just a program that prompts for speed, altitude, fuel, and direction and catches any errors. If an error is thrown then the program should stop and if there is no error than the program should just display all the values. My problem is that whenever the last try-catch statement(Inv...
The Problem: Even when the last try-catch statements catch an error the program still runs the showAll function. The Reason: None of the catch clauses exits the program. Possible Solutions: In every catch clause, put a return <any number other than zero>. Do not catch the Exceptions. In every catch clause, put an exit...
62,528,191
62,554,680
Why does a segfault occur when accessing vtkRenderWindow's ```Interactor``` variable?
I have an application that uses VTK 9.0 with QT 5.14.2, on Ubuntu 20.04 LTS. It compiles just fine (using gcc) and most of the application works. However, when I try to create a vtkRenderWindow, it crashes with a segfault. Specifically, whenever my application tries to access or interact with the vtkRenderWindow object...
Solved! The problem actually came about from the QT side. QVTKOpenGLRenderWindow cannot deal with vtkXOpenGLRenderWindow, it requires vtkGenericOpenGLRenderWindow. But vtkGenericOpenGLRenderWindow cannot be created with vtkRenderWindow::New(). The solution is to declare the renderwindow wrapped in a vtkNew<> pointer: ...
62,528,238
62,535,803
DFS with stack to find length of longest path from a certain node in a directed, acyclic, unweighted graph
I am trying to figure out a way to implement a DFS search to find the length of the longest path from a given node on a directed graph represented as an adjacency list by using a stack, and not using recursion. Specifically, I want to implement the DFS search so that as it runs, the stack gets populated as shown in th...
Although it's possible to achieve this without recursion, as an alternative, I would suggest you to design a function this way, which requires you to write less code and which will provide the nice intuition to understand this algorithm for you're a beginner. And you'll not need to think about creating stack by your ow...
62,528,268
62,528,485
Why do we use functions that return a data structure in C++?
I have been learning C++ and came across a function, but the return type was a vector. Here is the code: vector<Name> inputNames() { ifstream fin("names.txt"); string word; vector<Name> namelist; while (!fin.eof()) { Name name; fin >> name.first_name; fin >> name.last_name; ...
Your question is basically: Do I return by value or do I use an output argument? The general consensus in the community is to return by value, especially from C++17 on with guaranteed copy elision. Although, I also recommend it C++11 onwards. If you use an older version, please upgrade. We consider the first snippet mo...
62,528,451
62,528,832
iterating over char** without any specified bounds C++
I'm currently struggling on finding a way to iterate over char** without knowing what the bounds are. currently I have this for (int i = 0; a[i] != nullptr;i++){ //do something } this issue is this will work if I have a char** that looks like this {"hey\0", "this\0", nullptr} but I want it to work for one that looks l...
If you don't know the size of the array, then there is no telling where it ends. This is the reason why a "sentinel value" such as the final nullptr is added, to mark the end of an array of unknown size. Kind of like the regular null terminator inside a C string. Which is btw added implicitly by the "str" syntax; "str"...
62,528,460
62,528,873
Adding same class object return values using operator overloading in C++
I'm currently working on adding memory capability to a counter program. My program has to use object oriented design aspects such as companionship and inheritance, so I have created two classes: Counter and User Interface. Two counter objects (aCounter and mCounter) are passed to the user interface object so that there...
You're trying to overload operator + whereas you're executing += where you had commented. Just change the operator overloading sign from + into += and rather than writing: void UserInterface::setMemory() { //What I want to essentially do mCounter.returnCount() += aCounter.returnCount(); } Since the operator o...
62,528,551
62,528,673
Pass two dimensional array in function
I am trying to pass two dimensional array in function, but is has two errors which I don't know why. I have some articles about passing two dimensional array in function but also can't understand why I fail. #include <iostream> using namespace std; // prototypes void matrixSwap(double** matrix, int rows, int columns)...
The multidimensional double array matrix you're trying to pass in the function matrixSwap() to the argument double**, actually doesn't represents a multidimensional array. Use arrays correctly as shown: #include <iostream> using namespace std; const unsigned short MAXROWS = 5; // prototypes void matrixSwap(double ma...
62,529,045
62,529,445
Only the last element of the linked list is displayed
I have been trying to create a linked list in c++. But only the last element of the linked list is displayed. I have searched for the error but i cannot find it. I have implemented the logic that I learned form c language. All the nodes are connecting properly. But still i cannot find the error. This logic works on c l...
#include<iostream> using namespace std; class node{ public: int data; node *next; node(int x) { data=x; next=nullptr; } }*head,*newnode,*temp; node* create(int); void display(node*); int main() { int n; cout<<"Enter the no of nodes: "; cin>>n; head=create(n); ...
62,529,403
62,547,875
Can ETL be used with Atmel Studio?
The Embedded Template Library provides the data structures of the STL without using dynamic allocation, to be used in embedded development. I'm experimenting with the ATSAMD21 in Atmel Studio, and cannot use dynamic allocation. Therefore I tried the ETL, but it gives me the same errors I get when I'm trying to use STL:...
A compromise solution can be to add the NDEBUG parameter in debug mode, while still specifying a debugging level (like -g2 or -g3) This allows to use breakpoints and to watch the values of variables in a debugging session, the only downside seems to be that assert statements won't work, a feature much less often used i...
62,529,632
62,529,671
In C++, what is the correct way to do perfect forwarding an lvalue to a function template?
What is the correct way to accept a parameter pack for perfect-forwarding, such that it will take any type and simply forward them? The following code works on regular types but fails on pointer types: template<typename ...A> void b(A &&... args) {} template<typename ...A> void a(A &&... args) { b(std::forward<A>(...
You should not specify template arguments explicitly; which just prevents template argument deduction from working with forwarding reference, and yields unexpected result. a<int>(5); // A is specified as int then function parameter's type is int&&. // 5 is an rvalue and could be bound to int&& a<int*>...
62,529,770
62,529,874
how to configure -std=c++11 as default compiler?
Hi i am working on C++11 related feature , i need to include header file such as #include <zmqpp/zmqpp.hpp> in my source code and i wrote some simple g++ script to compile it such as g++ client.c -o client i just realized i need to run it with additional argument g++ -std=gnu++11 client.c ....... in order for me ...
as stated here, the only way to change the standard version is to rebuild a custom version of g++. If you are using Linux, I recommend having a custom alias in .bashrc, like so: alias g++11='g++ -std=c++11'; CMake is another common method to do this, simply add this directive to make the default version C++11 : set(CM...
62,529,965
62,530,170
I'm having a problem with movement in opengl 3D
I'm having a problem in OpenGL, when I press W, A, S, D everything works normal, but when I press space or shift it happens: The cube disappears before the end of the screen. Depending on the value of xrot and yrot another axis gets this problem. I'm a beginner in openGL 3D and I don't know why that happens. code: flo...
The object is clipped by the fare plane of the Orthographic projection. The projection matrix defines the volume (clip space) which is projected on to 2 dimensional viewport. Actually you don't set a projection matrix, thus the projection is the Identity matrix. Hence, view space, clip space and normalized device space...
62,530,153
62,532,149
Drag and drop items in combobox
How can I drag and drop items in combobox to change their order? (https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.combobox?view=winrt-19041)
How can I drag and drop items in combobox to change their order? I'm afraid you can't implement this feature, because Combobox use ItemsPresenter to display items, but ItemsPresenter does not contains reorder feature. If you want to change items order, there only way is that change the data source's order.
62,530,253
62,536,375
error: no viable overloading with clang, compiles with gcc
The following program compiles fine with g++ (version 10.1.0) but not with clang++ (10.0.0) #include <iostream> template <typename U> struct A { U x; }; namespace tools { template <typename U> void operator+=(A<U>& lhs, const A<U>& rhs) { lhs.x += rhs.x; } } namespace impl { template <typename U = int> void ...
The code is ill-formed because the part of unqualified name look-up that is not argument dependent is performed in the template definition context. So Clang is right and the GCC bug is already reported (bug #70099) What followes is the long explanation. Inside your exemple code there are some place that must be marked,...
62,530,528
62,609,591
My VSCode debugger dosen't show any variable value (image attached)(c++)
I recently started to use VSCode and can't seem to figure out how to use the debugger.The c++ debugger dosen't show any values which are readable. p.s i have installed the c++ intellisense extension from microsoft. edit:screenshot after stepping over Variable not showing their values during debugging my launch.json: { ...
uninstalled MinGW-w32 and installed MinGW-W64 as instructed by @StupidMan
62,530,913
62,531,225
How do I take a given number of lists of numbers as input, if I do not know how many number are there in each list?
https://www.spoj.com/problems/TTRGRAPH/ I was trying to solve the above problem, in the input specifications, it's given that there will be N lines of numbers (each line may have more than 1 numbers). How do I take the input (I am using C++)? I tried to take the input as shown below, but all of the numbers are getting ...
One possible solution is to use cin.peek(): #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<vector<int>> g(n); for (int i = 0; i < n; i++) { int e; while (cin >> e) { g[i].push_back(e); if (cin.peek() == '\n') ...