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 |
|---|---|---|---|---|
72,003,506 | 72,003,837 | How constructor and destructor called during template object in c++ | Can you please explain how constructor and destructor is called,Because when i see the output for tempravary object 4 destructor called more times
output
item Args constructor called 1
1 100
item Args constructor called 2
2 Proffecessor
item Args constructor called 4
item Args constructor called 3
item desconstructor c... | You miss the copy constructor. That's why you see more destructor call than constructor. You can also see it with this code.
#include<iostream>
#include<string>
using namespace std;
template <typename template_type>
class item
{
string name;
template_type value;
public:
item(string name, templat... |
72,004,031 | 72,004,370 | How do I get Arduino to return to 0 degrees after turning to 90 degrees | I am working on a project at the moment that deploy a model rockets parachute. I am not very skilled at coding so I thought I would ask here. The code is designed to press a button on the ground with a timer and then the parachute is deployed by the servo moving to 90 degrees. I would like the servo to return to 0 degr... | Currently you are waiting for 10 seconds (10 000ms) after the button has been pressed. After the button has been pressed nothing is done except for the Serial.println(...). You then check the if/else statement once. For your code to work you would want something like
if (buttonPressed == true) {
// Wait for 10 seco... |
72,004,319 | 72,004,499 | Difference between std::vector::empty and std::empty | To check if a vector v is empty, I can use std::empty(v) or v.empty(). I looked at the signatures on cppreference, but am lacking the knowledge to make sense of them. How do they relate to each other? Does one implementation call the other?
I know that one comes from the containers library and the other from the iterat... |
Difference between std::vector::empty and std::empty
The difference between Container::empty member function and std::empty free function (template) is the same as difference between Container::size,std::size, Container::data,std::data, Container::begin,std::begin and Container::end,std::end.
In all of these cases fo... |
72,004,573 | 72,004,656 | Initialize vector without copying and using move semantics | Is there a way to avoid copying when initializing a vector?
The code below will produce the following output.
#include <iostream>
#include <vector>
using namespace std;
struct Ticker {
std::string m_ticker;
Ticker() {
std::cout << "Default constructor" << std::endl;
}
Ticker(const std:... | If you use
std::vector<Ticker> table = std::vector<Ticker>{Ticker("MSFT"), Ticker("TSL")};
You will get
Parametrized constructor
Parametrized constructor
Copy constructor
Copy constructor
Destructor
Destructor
|MSFT|
|TSL|
Destructor
Destructor
Which has 4 constructor calls instead of the 6 you currently have. 2 of ... |
72,005,386 | 72,005,756 | Possible memory leak from a handled exception? (With exception handling that calls exit().) | I'm working on a C++ application (an OpenSSL assignment for university), and I'm running it through valgrind, as one does. I've noticed some rather strange output when the program fails due to invalid input:
==1739== HEAP SUMMARY:
==1739== in use at exit: 588 bytes in 6 blocks
==1739== total heap usage: 52 allocs... | std::logic_error's constructor allocated memory for the "explanatory string". This is what() returns to you, in the exception handler (std::invalid_argument inherits from std::logic_error).
Observe that the backtrace shows the constructor overload that takes a const char * for a parameter. It would've been acceptable i... |
72,006,166 | 72,007,960 | Is it possible to efficiently get a subset of rows from a large fixed-width CSV file? | I have an extremely large fixed-width CSV file (1.3 million rows and 80K columns). It's about 230 GB in size. I need to be able to fetch a subset of those rows. I have a vector of row indices that I need. However, I need to now figure out how to traverse such a massive file to get them.
The way I understand it, C++ wil... | As I proposed in the comment, you can compress your data field to two bits:
-- 00
AA 01
AB 10
BB 11
That cuts your file size 12 times, so it'll be ~20GB. Considering that your processing is likely IO-bound, you may speed up processing by the same 12 times.
The resulting file will have a record length of 20,000 bytes, ... |
72,006,351 | 72,006,403 | C++ Using Time as variable to store event length to reproduce later | Long story short:
I am trying to measure the time difference between the start & end of an event (a device executing a command), because I want to reproduce that later on as a return Home command.
But, it seems that for the same event, the time is way different, it varies by a factor of x2.
Here is my testing code:
#in... | Well, first, consider measure time using C++ facilities like in this question:
Measuring execution time of a function in C++
Then, the execution time of a piece of code may be impacted by many circumstances, so you should treat it like a random variable of sorts, and measure it multiple times, or measure the sum of tim... |
72,006,709 | 72,006,884 | How do I get the C++ standard flag as a string in CMake? | I need to get the compiler flags that will be used to compile a target programmatically in CMake. I need these flags as a string because I need to pass them to an executable in a custom command that needs to know how the parent target was compiled because it propagates those flags. I know enabling compile commands gene... | If you just need the compiler flag for choosing the C++ standard, try this:
set(COMPILE_FLAG ${CMAKE_CXX${CMAKE_CXX_STANDARD}_STANDARD_COMPILE_OPTION})
Alternatively, replace "STANDARD" in the code above with "EXTENSION" if you want to allow compiler-specific extensions.
I grepped through the CMake source code, and I ... |
72,006,755 | 72,006,955 | Filling in a vector with random numbers | I'm trying to print random numbers using srand. This is my code.
I want each subsequent number larger than the previous number in the list.
This is my code.
#include <iostream>
#include <ctime>
#include <cmath>
#include <random>
#include <vector>
#include <algorithm>
#include <climits> // for INT_MAX;
int main(){
sra... | You should be able to write this a lot simpler. Also, the reason your code seems to be not getting any random values is because your pushing back your bound with myVec.push_back(number). You should instead be doing myVec.push_back(result).
As for your actual question, it doesn't seem like your code is written as to wha... |
72,007,489 | 72,007,522 | C++; Pass std::array as a Function Parameter | I know this is a common question, but how do I pass a std::array as a function parameter? I've looked at answers for other questions on here asking the same thing, and the best "solution" I found was to use a template to set size_t to a keyword like SIZE. I tried this, but it still gives me two compile time errors:
Err... | Your function definition still needs template parameters since the compiler has no way of knowing what SIZE is
template<size_t SIZE>
// ^^^^^^^^^^^^^^^^^^
void QuickSort(array<unsigned, SIZE>& arrayName)
{
/// whatever the function does.
}
|
72,007,867 | 72,008,448 | Can a constructor affect other fields of an enclosing object, or is this a static analysis false positive? | Consider this C++ code:
struct SomeStruct {
SomeStruct() noexcept;
};
//SomeStruct::SomeStruct() noexcept {}
class SomeClass {
const bool b;
const SomeStruct s;
public:
SomeClass() : b(true) {}
operator bool() const { return b; }
};
void f() {
int *p = new int;
if (SomeClass())
delete p;
}
When I... | There is no standard compliant way for a const member to be changed after initialization; any mechanism is going to be UB.
Like
struct foo{
const bool b=true;
foo(){ b=false; }
};
is illegal, as is code that const_casts b to edit it like:
struct foo{
const bool b=true;
foo(){ const_cast<bool&>(b)=false; }
};
... |
72,008,655 | 72,009,330 | How to throw an exception if two different derived class objects from the same base class interact with each other? | I have an abstract base class(X) with A & B derived classes.
I have a class method in X that is inherited by both classes A & B.
I want the method to be able to throw an exception if two different derived class objects interact with each other.
Here is a contrived example:
class Food{
public:
int count;
... | You can check that in the combine function :
void combine(Food const& a) // You should pass your argument by const ref
{
assert(typeid(*this) == typeid(a)); // This checks ONLY IN DEBUG !
this->count += a.count;
}
If you want to manage the error, use exception or return value :
void combine(Food const& a)
{
... |
72,010,108 | 72,014,842 | Jsoncpp nested arrays of objects | I need to search for an element in a json file using the jsoncpp library.
I can't wrap my head around how to get to the most inner array... Any thoughts?
{
"key": int,
"array1": [
{
"key": int,
"array2": [
{
"key": int,
"arr... | You can't access array2 with array1["array2"], since array1 contains an array of objects, not an object, so you should get array2 with an index i, array1[i]["array2"] instead.
The following code works for me:
const Json::Value &array1 = root["array1"];
for (int i = 0; i < array1.size(); i++) {
const Json::Value... |
72,010,284 | 72,034,562 | Is this a safe / correct implementation of a variadic list argument used to simplify setting "pinMode"? | Code (C++):
I'm new to C++ so I'm not sure if this is safe:
#include <Arduino.h>
void pin_mode(uint8_t pins[], uint8_t mode) {
const int length = *(&pins + 1) - pins;
for (size_t i = 0; (signed)i < length; i++) {
pinMode(pins[i], mode);
}
}
I have multiple pins that have the same pin setting, I'd like to se... | If I were doing this, I'd pass the array by reference, so the compiler would compute its size for me:
#include <Arduino.h>
template <size_t N>
void pin_mode(uint8_t (&pins)[N], uint8_t mode) {
for (size_t i = 0; i < N; i++) {
pinMode(pins[i], mode);
}
}
Of course, with this you're free to use a range-based fo... |
72,010,359 | 72,055,468 | Optional node still visited in OR-tools vehicle routing problem | In a simple vehicle routing problem solved by Google OR-tools library, two nodes (2, 3) are marked as optional with visiting penalty set to 0. The shortest path of distance 2 from the depot to the landfill is 0 -> 1 -> 4, however, the solver ends-up with path 0 -> 2 -> 3 -> 1 -> 4 of distance 4.
Where is the problem? W... | This was answered on the or-tools-discuss mailing list.
You encountered a corner case for the default parameter setup. Thanks for forwarding this, we will work on a proper fix.
To work around the problem, you can modify the default parameters as follows:
Option 1 - activate make_chain_inactive - faster option
Routi... |
72,010,370 | 72,010,598 | Why my program is terminated but main thread is run? | I run thread in Qmainwindow using thread library not qthread
I not use thread.join but main thread is run but program is terminated
why program is temianted?
void MainWindow::onSendMsg()
{
// std::thread trdSend([this](){
socket = new QTcpSocket(this);
socket->connectToHost(clientIP,clientPort.toUInt());
//sock... | Literally from std::thread::~thread:
~thread(); (since C++11)
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
Notes
A thread object does not have an associated thread (and is safe to destroy) after
it was default-constructed
it was moved from
join() has ... |
72,010,460 | 72,010,521 | why this template function does not recognize the lamda's returned type? | This template function does not recognize the lamda's returned type, even specifing it decommenting '->void'.
Why does it happen?
What could I do to circumvent this problem?
#include<iostream>
#include<array>
template<typename T, typename S, size_t SIZE>
void for_each(std::array<T,SIZE>& arr, S(*func)(int&))
{
for ... | Your for_each expects a function pointer, but the implicit conversion (from lambda to function pointer) won't be considered in template argument deduction, which causes the calling failing.
You can perform the conversion explicitly:
for_each(five_elems, static_cast<void(*)(int&)>([](int& ref)/*->void*/{ref *= 2; std::c... |
72,010,604 | 72,011,069 | Is there a C++ STL function to compare a value against a compile-time constant? | I've implemented the following function in a utility library:
template <auto Value>
bool equals_constant(const decltype(Value)& value) { return Value == value; }
It's useful with other template functions which take an invocable predicate, like this:
template <auto IsValid>
struct Validator {
bool validate(int valu... | No. std isn't a place where "anything vaguely useful" gets put.
boost::hana::equal.to looks to be similar.
|
72,012,706 | 72,012,924 | What is the preferred way to write string to file in C++, use '+' or several '<<'? | I am considering writing several lines into a file in C++ using ofstream and the text is composed of several parts (strings and numbers), so essentially I know there are two ways.
Here is a simple example:
// Way 1 (Use several '<<')
f << str1 << " " << 10 << "Text" << std::endl;
// Way 2 (Use plus to have a continuous... | I wrote a small program that tries both methods, the first version, using << seems to be faster. In any case, the usage of std::endl inhibits performance significantly, so I've changed it to use \n.
#include <iostream>
#include <fstream>
#include <chrono>
int main () {
unsigned int iterations = 1'000'000;
std:... |
72,013,343 | 72,013,580 | Using Boost strong typedef with unordered_map | I am using a Boost strong typedef to strong-type uint64_t:
BOOST_STRONG_TYPEDEF(uint64_t, MyInt)
and an std::unordered_map using this:
std::unordered_map<MyInt, int> umap;
Unfortunately I get a lot of compiler errors (can't paste here as they're on another machine):
error: static assertion failed: hash function must ... | From the boost documentation about BOOST_STRONG_TYPEDEF, it is clearly mentioned that it defines a new type wrapping the target inner type (it is not a simple alias).
Knowing that, there is no defined std::hash<MyInt> specialization available (required by std::unordered_map<MyInt, int>) since MyInt is now a distinct ty... |
72,013,873 | 72,610,580 | DocuSign JSON SOAP Request | I am trying to understand how to send SOAP requests with JSON formatted data to docusign. Following this guide is only for pdfs:
https://developers.docusign.com/docs/esign-soap-api/how-to/request-signature/
I created a template on docusign developer and downloaded it, which is in json format.
How do I send the data in... | Unless you have a really good reason, I highly recommend you consider using the DocuSign eSignature REST API and not the DocuSign eSignature SOAP API.
Not every feature is supported by the SOAP API.
You could use https://github.com/jgaa/restc-cpp to make REST API calls from a C++ codebase.
Also, remember that documents... |
72,014,691 | 72,014,747 | How to ignore text case while comparing two strings in C++? | I am a beginner coder. I am trying to create a program which will compare two strings alphabetically. But It will ignore the text case. I am facing problem on it. How can I ignore the text case in C++?
#include <iostream>
using namespace std;
int main() {
string a, b;
cin >> a;
cin >> b;
if ( a > b... | You can convert both strings to lower case before the comparison via std::tolower:
for (auto& c : a) c = std::tolower(static_cast<unsigned char>(c));
for (auto& c : b) c = std::tolower(static_cast<unsigned char>(c));
|
72,014,935 | 72,015,467 | Why does a two-dimensional array become a one-dimensional array after passing it to a function?(C++ | I'm making a simple Snake game. When making a map, my definition of the map is as follows
int map[25][25] = { 0 };
for (int i = 0; i < 25; i++)//Set the boundary to - 2
{
map[0][i] = -2;
map[24][i] = -2;
}
for (int i = 1; i < 25; i++)//Set the boundary to - 2
{
map[i][0] = -2;
map[i][24] = -2;
}
Then ... | You cannot pass built-in arrays like this to functions. snake_move(), even though it appears to have an argument that looks like a 2D array, it actually takes a pointer to a 1D array. This:
void func(int map[][25]);
Is actually equivalent to:
void func(int (*map)[25]);
map is a pointer to an array of 25 int elements.... |
72,015,309 | 72,016,334 | Serialize openDDS topic to a `std::string` | I've using OpenDDS in a project. Now, for interoperability, we need to send topics also with a custom framework to other machines. Since this custom framework allows to send strings, I'd like to serialize the topics in a string and then send them.
I was using boost::serialization, but then I've made up the idea that in... | It's possible to use TAO's serialization system to do this, but it's probably better to use what OpenDDS is using: https://github.com/objectcomputing/OpenDDS/blob/master/dds/DCPS/Serializer.h (or at least it's easier for me to write an example for since I know it much better)
These are some functions that will serializ... |
72,015,959 | 72,016,033 | Correct way to instantiate a class member of template class with paramter | I have a template class with an instantiation parameter.
I have another class that has a member parameter of that class.
The follow does not compile because it says instantiation method is deleted...
class MyClass {
public:
MyTClass<AClass> tclass;
}
The following works but I am not sure if it is the correct way..... | No, you do not need to do anything extra here. The destructor of MyClass invokes the destructor of all members, regardless of how they were originally constructed.
(This is true even if the member is a pointer. But the destructor of a pointer does nothing, which is why you'd need a delete call to destruct and free the ... |
72,016,205 | 72,017,989 | DPC++ & MPI, buffer, shared memory, variable declare | I am new to DPC++, and I try to develop a MPI based DPC++ Poisson solver. I read the book and am very confused about the buffer and the pointer with the shared or host memoery. What is the difference between those two things, and what should I use when I develop the code.
Now, I use the buffer initialized by an std::ar... | You are too eager in using constexpr. Remove all three occurrences in this code, and it should compile. So this has nothing to do with DPC++.
|
72,016,461 | 72,023,533 | RDMA Read protection for local memory operations | I have the following scenario: My server allocates a buffer of 1MB, which is periodically updated and written to (about every 50ms). The client is connected to the the server via Infiniband and periodically reads that buffer via RDMA Read (potentially even faster than it is updated).
My question is: Is there any way to... | The answer may depend on the device. In RDMA Verbs, there are two different modes for atomic operation (which can be checked using the ibv_query_device verb). With IBV_ATOMIC_HCA, atomic operations are only atomic with respect to other operations from the same device, while IBV_ATOMIC_GLOB means that they are atomic al... |
72,018,146 | 72,018,214 | C++ custom assignment | I have the following code:
template<size_t rows, size_t cols>
class Matrix{
std::array<int, rows * cols> data;
public:
int operator()(size_t i, size_t j){
return data[i * cols + j];
}
// ...code...
}
What is the best way to achieve this:
Matrix<1,1> a;
a(0, 0) = 0;
avoiding the lvalue required ... | You can change the following line:
int operator()(size_t i, size_t j){
To:
int & operator()(size_t i, size_t j){
Returning a refernce (L value reference to be precise) to the element in the Matrix will allow you to assign to it.
Update: Some notes to complete my answer:
As @user4581301 commented: you can see more i... |
72,018,553 | 72,020,749 | Win32 window not showing when ran through CLI/VSCode debugger | I am creating a Win32 application, I have followed some setup code for creating a Win32 window without the need for a WinMain which can be found here. The code builds just fine and if I run the application by opening it in a file browser it runs no problem. However, if I run it via the command line it only outputs the ... | This bit of code contains a mistake:
STARTUPINFO si;
GetStartupInfo(&si);
int nCmdShow = si.wShowWindow;
You forgot to check si.dwFlags, as indicated in the documentation for wShowWindow:
If dwFlags specifies STARTF_USESHOWWINDOW, this member can be any of the values that can be specified in the nCmdShow parameter ... |
72,018,885 | 72,032,419 | print condition while integer overflow not working | #include <iostream>
using namespace std;
int getFectorial(int n)
{
int ans = 1;
for (int i = n; i >= 1; i--)
{
ans = ans * i;
}
return ans;
}
int printNcr(int n, int r)
{
if (getFectorial(n) > INT_MAX)
{
return 0;
}
return (getFectorial(n)) / ((getFectorial(r)) * ... | int oveflow cannot be reliably detected after it happens.
One way to detect upcoming int overflow in factorial:
int getFactorial(int n) {
if (n <= 0) {
return 1; // and maybe other code when n < 0
}
int limit = INT_MAX/n;
int ans = 1;
for (int i = 2; i <= n; i++) {
if (ans >= limit) {
return INT... |
72,018,905 | 72,019,970 | C++ multidimensional array on heap | I don't understand how to create an multidimensional array on the heap with the new operator. In java it works like that:
int[][][] array = new int[3][3][3];
how do I achieve the same thing in c++? I wanna have an 3d array that I can access like that:
array[0][0][0] = 1;
How can I do that?
| Generally as you mentioned in the comments stack space is limited. In a lot of cases this does not really matter and most definitely it is not a problem for an int array that essentially has size in the double digits. To have it on the stack you can just do:
int array[3][3][3];
Note that this only works if 3 is known ... |
72,019,389 | 72,019,491 | How to get data from hookproc function winapi (C++) | I have a program that sets a hook on another window. I want this program to know if my hook function received a message. How can I do it?
I've had an idea to send message from hook function to my main window, but I don't know how to pass the HWND handler. Also I don't want to use EnumWindows or FindWindow to find my ma... | The simplest solution is to store your target HWND in shared memory that both the main program and the hook can access.
If your compiler supports #pragma data_seg() (ie, MSVC), you can use that to declare an HWND variable in a shared code section in a DLL. Have your main program and your hook use the same DLL. See Proc... |
72,019,875 | 72,022,926 | Usage of alignas in template argument of std::vector | I want to create a std::vector with doubles. But these doubles should be aligned in 32 byte for AVX2 registers. What would be the best way to do this? Can I simply write something like
std::vector<alignas(32)double>?
Thanks in advance for the help.
| If alignas(32)double compiled, it would require that each element separately had 32-byte alignment, i.e. pad each double out to 32 bytes, completely defeating SIMD. (I don't think it will compile, but similar things with GNU C typedef double da __attribute__((aligned(32))) do compile that way, with sizeof(da) == 32.)
... |
72,019,913 | 72,019,947 | How to Convert e.x. 2/3 or 1/2 in input to float in cpp | How to Convert e.x. 2/3 or 1/2 in input to float in cpp
string s="2/3";
float x=stod(s);
| You could try something like:
int a,b;
string s="2/3";
sscanf(s.c_str(), "%d/%d", &a, &b);
float x = float(a)/b;
Of course, you have to do some validations around b being zero.
|
72,019,994 | 72,020,497 | Is there a way to build a project with multiple C++ files efficiently in Visual Studio Code? | I have a project in Visual Studio code with > 10 .cpp files. The reason they're split up this way was to make compilation faster, and it is faster in Visual Studio 2022. However, when using a build task in Visual Studio Code that simply includes all .cpp files it can find, it obviously compiles really slowly, as expect... | Solution: Use CMake. It's less complicated and more reliable than Visual Studio build tasks. Comments on my original question clear up how that's done.
|
72,020,221 | 72,020,530 | How can i write an array starting from right to left in C++ | I don't want to reverse or shift the array. What I want is to write the array from right to left.
I did something like
int arr[5] = {0};
for (int i = 0; i < 5; i++)
{
cout << "enter a number : ";
cin >> arr[i];
for (int j = 0; j < 5; j++)
{
if (arr[j] != 0)
{
cout << arr[j] <... | Just change the inner for loop for example the following way
int j = 5;
for ( ; j != 0 && arr[j-1] == 0; --j )
{
std::cout << 'X' << ' ';
}
for ( int k = 0; k != j; k++ )
{
std::cout << arr[k] << ' ';
}
|
72,020,517 | 72,020,819 | Why can't the compiler ever elide the vtable? | Sometimes I create an abstract class merely for implementation hiding, as an alternative to the pimpl idiom. If there is only one descendant and no public visibility outside the library that I'm building, why can't the linker remove the vtable?
I tried some experiments with clang and -Os. I added this to the constructo... | Proving that (safely deriived) pointers to instances of your class are never passed to any code the compiler cannot examine is insanely hard.
Once such a pointer is in any code the compiler cannot examine, it must provide a vtable pointer to support RTTI and dynamic dispatch. And this must be ABI compatible with someo... |
72,020,782 | 72,028,046 | dpc++ start the do loop from 1 to n-2 using parallel_for range | Is that possible to start the do loop and the index is from 1 to n-2 using dpc++ parallel_for?
h.parallel_for(range{lx , ly }, [=](id<2> idx
this will give a do loop from 0 to lx-1, and I have to do
idx[0]>0 && idx[1]>0 && idx[0]<lx-1 && idx[1]<ly-1
and then I can complete the loop?
Also, does dpc++ support like 4D p... | In SYCL 1.2.1, parallel_for supports offsets, so you could use h.parallel_for(range{lx-2, ly-2}, id{1, 1}, [=](id<2> idx){ ... });.
However, this overload has been deprecated in SYCL 2020:
Offsets to parallel_for, nd_range, nd_item and item classes have been deprecated. As such, the parallel iteration spaces all begin... |
72,021,092 | 72,021,170 | recv() fails to read last chunk | The function below reads incoming data perfectly but only if the last data chunk is smaller than BUFFSIZE. If the size of the last buff happens to be equal to BUFFSIZE, then the program tries to recv again in the next loop iteration and sets bytes to 1844674407379551615 (most probably integer overflow) and repeats thi... | Probably size_t is unsigned on your platform. So if the recv times out, recv returns -1 and bytes overflows. Your code doesn't correctly handle this case due to the overflow.
This is just wrong:
//'buff' isn't full so this was the last chunk of data
It's entirely possible buff wasn't full because the last ch... |
72,021,185 | 72,021,322 | Output operator is not producing expected outcome | I am implementing a class Polynomial with private members consisting of a singly linked list for its coefficient and an int representing the highest degree. The constructor takes in a vector which represents the coefficients in the polynomial. This is my implementation of the constructor and the output operator.
#inclu... | This constructor
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
is invalid. Actually it does not build a list. Instead it produces numerous memory leaks.
For example at first a node was allocated and... |
72,021,195 | 72,021,596 | How to add/update/delete Department in university class? | #include <iostream>
using namespace std;
class Professor
{
string name;
long employeeID;
string designation;
public:
Professor()
{
name = "";
employeeID = 0;
designation = "";
}
Professor(string n, long ID, string d)
{
name = n;
employeeID = ID;... | First off, several of your for loops are incorrect, namely the ones in the following methods:
Department::Department(string, long, Professor[5], int), should be using no_of_dpt (or better, std::min(no_of_dpt, 5)) instead of 5 for the loop counter.
Department::setDepartmentData(), should be using nd (or better, std::m... |
72,021,473 | 72,156,491 | Save integers from string to vector | I need to save integers from string to vector.
Definition of number: each of strings substrings which consists entirely of digits, with a space before the first character of that substring and a space or punctuation mark after the last character, unless the substring is at the very beginning or end of the string (in th... | I found a way to solve this.
#include <iostream>
#include <string>
#include <vector>
std::vector < int > extract_numbers(std::string s) {
std::vector < int > vek;
for (int i = 0; i < s.length(); i++) {
std::string word;
while (s[i] == ' ' && i < s.length()) i++;
while (s[i] != ' ' && i < s.length()) wor... |
72,021,541 | 72,021,608 | Using cin makes my code not work properly | I'm pretty new to c++ and tried this project and got it to work. Basically it takes a word and a sentence then changes the word to asterisks whenever said word is found in the sentence.
The problem I am facing is I tried taking it a step further by asking the user to input a word and input a sentence and then using tho... | cout << "Sentence: ";
cin >> sentence;
The operator>> function you are using here stops reading at the first space character. It is not suitable for reading in a line of text.
|
72,022,183 | 72,022,261 | How do you restrict `resize()` from being called after constructing a vector? | I'm building a class that exposes a sequential container, with a fixed length, but the length isn't known at compile-time.
So when an instance of my class is constructed, a parameter is passed in, to indicate how big the vector needs to be.
But the length needs to be fixed after construction.
I need to guarantee that t... | Since C++20 you can return a std::span to the range in the vector. This allows access to the size and modifiable access to the elements, but not the vector's modifiers.
For example:
#include<vector>
#include<span>
class A {
std::vector<int> vec;
public:
/*...*/
auto getVec() {
return std::span(vec)... |
72,022,362 | 72,022,392 | C++; Pass a std::array Random Access Iterator as a Function Parameter | So I've seen questions on here about how to pass through a std::vector::iterator as an argument parameter for a function, however, those solutions don't seem to apply when dealing with std::arrays. What I want to use this for is a Quick Sort function that takes in std::arrays. This is the code I have thus far:
#include... | You need to use typename to hint to the compiler that iterator is a type
template<size_t SIZE>
void QuickSort(typename array<int, SIZE>::iterator low,
typename array<int, SIZE>::iterator high);
But that won't work either since SIZE is in a nondeduced context. It would be better to just make an iterator ... |
72,023,700 | 72,034,755 | base64 encoding removing carriage return from dos header | I have been trying to encode the binary data of an application as base64 (specifically boosts base64), but I have run into an issue where the carriage return after the dos header is not being encoded correctly.
it should look like this:
This program cannot be run in DOS mode.[CR]
[CR][LF]
but instead its outputting li... | Okay thanks for adding the code!
I tried it, and indeed there was "strangeness", even after I simplified the code (mostly to make it C++, instead of C).
So what do you do? You look at the documentation for the functions. That seems complicated since, after all, detail::base64 is, by definition, not part of public API, ... |
72,023,780 | 72,024,397 | Are QML calls to C++ public slots executed in the c++ target thread, or in QML (main thread)? | Imagine we have a QObject-based c++ class called CppClass that is registered in the QML context with the name qmlCppClass and moved to a new thread using QObject::moveToThread("newThread* name").
Imagine CppClass has a public slot declared as void doSomething().
Imagine the root QML object/window has a signal defined i... | If connect is done with QueuedConnection then the slot will be executed on the receiver's thread, otherwise—on the sender's. Given you moved the receiver to another thread before making the connection, it would be a queued connection by default.
If there is no direct call to the connect function then invokeMethod might... |
72,024,142 | 72,024,468 | Why does std::move cause SEGFAULT in this case? | Why does std::move() cause a SEGFAULT in this case?
#include <iostream>
struct Message {
std::string message;
};
Message * Message_Init(std::string message) {
Message * m = (Message*)calloc(1, sizeof(Message));
m->message = std::move(message);
return m;
}
int main() {
auto m = Message_Init("Hello... | If you really want to do something like this, then you can use placement new. This allows you to construct an object in a chunk of memory that is already allocated.
Several of the standard containers use placement new to manage their internal buffers of objects.
However, it does add complications with the destructors o... |
72,024,517 | 72,024,569 | What is atltime.h in MFC | Can someone will explain to me What is atltime.h ? I don't know how this header works. I tried to search it on google but i didn't get an answer of what atltime. h is.
| Not MFC, but ATL. ATL (Active Template Library) is a set of header files that ships with Visual Studio for making Windows programming easier without having to pull in all of MFC. These headers implement C++ class libraries that do useful things for legacy Windows programming.
It appear that atltime.h has the declarati... |
72,025,359 | 72,025,614 | fastest way of finding the end of a string | The question is simple: What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
std::array<char, 100> str { "A sample string literal" };
I guess one option is to use the std::strlen.
Another option that I can think of is std::find or maybe even std::ranges::find:
const auto p... |
What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
I'm going to assume that you mean "to find the first null terminator".
Fastest depends on details. You have to measure to find out. std::strlen is a fairly safe default choice.
Now would it make a difference if an Exec... |
72,025,770 | 72,100,387 | UWP Extended Foreground Session | So, I have made a few attempts to create an app in UWP, using C++/CX, and besides dreading the syntax, I had some fun.
I ran into troubles when I attempted to prevent the app from being suspended. Initially I tried using this resource, but I have learnt that there is a timeout. Then I tried getting rid of said timeout ... | I solved the issue, I ended up creating a new project from scratch in c#, and recreating the entire project (luckily I didn't have much trouble, since there wasn't too much to implement). In the end, it might have been something to do with either my xaml or some wrong API call.
Thank you Roy Li - MSFT for your time.
|
72,025,874 | 72,028,029 | Proper use of std::reference_wrapper in union | Can someone please explain what is wrong with this pattern? When I try to compile it I get errors for each type of the following type.
error: no match for 'operator=' (operand types are 'std::reference_wrapperstd::__cxx11::basic_string<char>' and 'int')
string_reference = property;
struct PropertyPointer {
int type... | Answer of your question
if statements are not marked constexpr
The reason why your code does not compile is because, even if the if statements will be evaluated to false at compile time, the branches contained by those if statements will be compiled.
In your example, you can mark those if statements as constexpr to com... |
72,026,112 | 72,026,180 | Capture shared_ptr in lambda | I want to capture a shared_ptr in my lambda expression. Tried two methods:
Capture the shared pointer
error: invalid use of non-static data member A::ptr
Create a weak pointer and capture it (Found this via some results online). I'm not sure if I'm doing it the right way
error: ‘const class std::weak_ptr’ has no memb... | You cannot capture member directly, either you capture this or capture with an initializer (C++14)
auto t1 = [this](){ auto value = ptr->someFunction();};
auto t1 = [ptr=/*this->*/ptr](){ auto value = ptr->someFunction();};
|
72,026,830 | 72,028,789 | Zip directory recursion | I am working on creating zip archive using old Qt - ZipWriter class. The problem is when I want to add the directory. The default Qt code for addDirectory method - d->addEntry(ZipWriterPrivate::Directory, archDirName, QByteArray());. It does not add any content, only the empty directory. So, I have improved it to add t... | You can use QDirIterator to recursively iterate over directory and subdirectories, and I believe you dont need to add nonempty directories at all, just files will be fine.
And why would you use stl container in qt, please use qt containers.
|
72,027,058 | 72,027,807 | Is it possible to expand a macro into two piece of data with different types | UPDATE
It seems that the original question is not that clear, so I made another example to specify what I need.
#define RPC_FUNC(X) &X,??? // I don't know how...
class Test {
public:
static void func(int a) {}
};
int main()
{
const auto ptr1 = std::make_pair(&Test::func, "Test::func");
// const auto pt... | The specification what the macro should precisely do is dim. The stringizing operator # can turn macro argument into string literal:
// example code what it does
#include <iostream>
#define YOUR_MACRO(X) X() << " from " << #X "()"
int foo() { return 42; }
int main() { std::cout << YOUR_MACRO(foo) << std::endl; }
Th... |
72,027,359 | 72,027,509 | How to input to vector correctly in C++ | When I try to input to vector by following code, I get a segmentation fault as shown below.
I defined the vector and set N, and tried to input a vector with N elements.
What is the root cause of this?
#include <iostream>
#include <vector>
using namespace std;
int N;
vector<int> A(N);
int main(){
cin>>N;
for(in... | That's because constructor of A is called with N=0. When you input N, it doesn't affect the vector at all. If you really want to keep using globals, then use std::vector::resize but the recommended way would be:
int main(){
std::size_t n;
std::cin >> n;
std::vector<int> A(n);
for(auto & x : A) std::cin ... |
72,027,373 | 72,027,501 | How to get a removed-reference tuple type without using an instance in C++ | I wrote a test framework for testing function output (see code below).
template <class FuncTy, class... IndexType>
typename std::enable_if<std::tuple_size<typename function_helper<FuncTy>::arguments>::value == sizeof...(IndexType)
and std::is_same_v<typename function_helper<FuncTy>::return_type, AnswerT... | You can get the element type of the tuple through template partial specialization and apply std::decay to those types to remove references, something like this
#include <type_traits>
#include <tuple>
template<class Tuple>
struct decay_args_tuple;
template<class... Args>
struct decay_args_tuple<std::tuple<Args...>> {
... |
72,027,739 | 72,074,304 | Is Q_INTERFACES macro needed for child classes? | If I have class A that implements an interface (and uses Q_INTERFACES macro), then does child class B : public A also need to use the Q_INTERFACES macro?
For example:
IMovable.h
#include <QObject>
class IMovable
{
public slots:
virtual void moveLeft(int distance) = 0;
virtual void moveRight(int distance) = 0;
... | Q_INTERFACES is needed for the qobject_cast function to work correctly with the interfaces a class implements. So if you want to use this function you have to place Q_INTERFACES into your class.
Docs aren't clear on what happens with the inheritance but the implementation of the generated qt_metacast function is always... |
72,027,843 | 72,074,356 | How does os figure if a dll is already loaded in memory or how does os figure two dll are the same? | In my comprehension, "dll/so" can be shared between programs(processes). for example when "libprint.so" is loaded in "main"(called main1) at first time, "libprint.so" is loaded from disk into memory, if we start another "main"(called main2), "libprint.so" will not loaded from disk but mapped from memory because "libpri... |
i want to know exactly what the tricks are, do i have to read the linux os source code ?
What actually happens when you run main (which is presumably linked against libprint.so) (or at least "explainlikeimfive" version):
At the time the static link is performed (g++ main.cpp ./libprint.so or similar), the static lin... |
72,027,928 | 72,028,003 | Min and Max function return gibberish value when array is not full | I need to create a program that collects user input until the user presses 0 or has inputted 10 values. Then I need to create a function, without using built-in to get the minimum and maximum values. However, when 9 or less values are inputted, the minimum and maximum function return a random value. Here is my code:
#i... | You are breaking the loop on less than 10 values, if need be, but still iterate over the entire array. Instead you should only iterate over those values that actually have been written to, reading the others results in undefined behaviour as the array is not initialised at these locations (and thus contains the 'giberi... |
72,027,998 | 72,028,800 | Polygon collision (sometimes) not working, possibly float error | I am writing a program in C++ using OpenGL to draw elements. This is a simple 2D game, in which a square is supposed to change its direction once it hits one of the walls, i.e. the bounds of the screen. To set up the bounding box, I have made tiny squares spanning the length of the sides. My coordinate system is from -... | You don't need an epsilon. In fact, it is the source of the error.
if (collisionX) { // Collision X
ball->flipDirectionX();
When the ball gets to move slow enough, once it enters the area of epsilon, it will just bounce left and right every frame.
But just removing the epsilon will not be enough to fix the issue. ... |
72,028,410 | 72,033,911 | OpenMP has low CPU usage | My OpenMP Implementation shows a really bad performance. When I profile it with vtune, I have a super low CPU usage and I don't know why. Does anyone have an idea?
Hardware:
NUMA architecture with 28 cores (56 Threads)
Implementation:
struct Lineitem {
int64_t l_quantity;
int64_t l_extendedprice;
float l_... | I was able to find the cause of my poor OpenMP performance. I am running my OpenMP code inside a thread pinned to a core. If I don't pin the thread to a core, then the OpenMP code is fast.
Probably the threads created by OpenMP in the pinned thread are also executed on the core where the pinned thread is pinned. Conseq... |
72,029,266 | 72,029,649 | Deleting minimum node from BST results in segmentation fault C++ | I am trying to delete the minimum node from a BST. But I get a seg fault.
To my understanding, minimum node will have no children, hence deleting it would not result in desserted leftover subtree. I am unsure on how to remove a node from a BST, I saw some solution that uses free() instead of delete. Where did I go wron... | At very first your assumption that the minimum node doesn't have children is wrong; it doesn't have a left child, but it might have a right child; consider the most simple case of the root node and one single child that's greater than:
1
\
2
Then for removing a node you cannot just only delete it, but you nee... |
72,029,420 | 72,029,497 | Char array to string and copy character \0 | How can I convert a char field to a string if I have the '\ 0' character stored in some position. For example, if I have "ab \ 0bb", the a.lenght () command will show me that I have only two characters stored
string getString(char *str, int len)
{
str[len] = '\0';
string strBuffer = string(str);
cout << str... | As mentioned in the comments, std::string (which I will assume string and the question is referring to) has a constructor taking the length and allowing null characters:
string getString(char *str, int len)
{
return {str, len};
}
or if you want to be explicit (to avoid confusion with an initializer list constructo... |
72,030,811 | 72,030,986 | cppcheck: member variable not initialized in the constructor | The following code, as far as I can tell, correctly initializes the variables of the derived class B:
#include <utility>
struct A {
int i;
};
struct B : A {
int j;
explicit B(A&& a) : A(std::move(a)), j{i} { }
};
int main()
{
A a{3};
B b(std::move(a));
return 0;
}
Running cppcheck with --enable=all giv... | Yes, this looks like a false positive. Base class subobjects are initialized before direct member subobjects and A(std::move(a)) will use the implicit move constructor which initializes this->i with a.i, so this->i will be initialized before the initialization of this->j is performed (which reads this->i).
The argument... |
72,030,923 | 72,031,262 | How to convert a windows FILETIME to a std::chrono::time_point<std::chrono::file_clock> in C++ | I'm looking for a way to convert a Windows FILETIME structure to a std::chrono::time_point< std::chrono::file_clock> so that I can build a difference between two file times and express that duration f.e. in std::chrono::microseconds.
EDIT: Here is a complete godbolt example of Howard's Answer.
| Disclaimer: I don't have a Windows system to test on.
I believe that one just needs to take the high and low words of the FILETIME and interpret that 64 bit integral value as the number of tenths of a microsecond since the std::chrono::file_clock epoch:
FILETIME ft = ...
file_clock::duration d{(static_cast<int64_t>(ft... |
72,030,976 | 72,031,446 | Basic forward list using unique_ptrs | As an exercise in learning C++, I want to build my own forward list using raw pointers and using unique_ptrs. Using raw pointers, I have:
struct node_raw {
node_raw(int data_, node_raw *next_) : data(data_), next(next_) {}
int data;
node_raw *next;
};
Then I can write this
int main() {
node_raw r1{1, n... |
Why do I need std::move twice to make a new node?
You cannot copy node_unique because it has implicitly deleted copy constructor because of std::unique_ptr member.
Is it now invalid to query u1.data because it has been moved from?
No. The implicitly generated move constructor will copy the member. It's not invalid ... |
72,031,008 | 72,031,423 | How can I sort a 2D vector in C++ by the first and second index? | I was wondering how in C++ I could sort a 2D vector so that it is sorted by both elements. It would be sorted in ascending order by the first element, and if there are multiple of the first element, they will be sorted by ascending order of the second element. Here is an example of what I mean:
vector<vector<int>> vec ... | If you are using C++20 std::ranges::sort would be a good option:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<std::vector<int>> vec = {{10, 25}, {10, 23}, {10, 22},
{10, 24}, {1, 100}, {13, 12}};
std::ranges::sort... |
72,031,323 | 72,087,315 | How to generate a symmetric key in C or C++ the same way this script does? | I am implementing Azure DPS (device provisioning service) for my ESP32-based firmware.
The bash script I use so far is as follows (where KEY is the primary key of the DPS enrolment group and REG_ID is the registration device Id for the given ESP it runs on):
#!/bin/sh
KEY=KKKKKKKKK
REG_ID=RRRRRRRRRRR
keybytes=$(echo ... | I manage to do it by using bed library (which is available from both ESP32/Arduino platforms).
Here is my implementation for the Arduino platform:
#include <mbedtls/md.h> // mbed tls lib used to sign SHA-256
#include <base64.hpp> // Densaugeo Base64 version 1.2.0 or 1.2.1
/// Returns the SHA-256 si... |
72,031,334 | 72,031,639 | MIDI Files in Hex Value | I am a beginner in programming
Is there a way to read a midi file in its hex numbers?
I searched the internet that midi files are composed of headers and their contents are in hex numbers like
4D 54 68 64 0A ....
So, what is the best way to extract those hex numbers from a midi file? If there is a C++ library to do thi... | Let me tell you a secret: There are no hex numbers inside your computer. There are also no decimal numbers. All numbers in your computer are stored as binary. Whenever you write a decimal number like 95 in your code, what C++ does is convert it into binary internally and write it to disk as 1011111.
As such, the proble... |
72,031,942 | 72,032,204 | malloc(): corrupted top size, but I am using delete[] | void merge_sort(int* arr, int start, int stop){ // [start; stop]
int min_array_size = 8;
std::cout << start << " " << stop << std::endl;
if ((stop - start + 1) > min_array_size){
merge_sort(arr, start, start + ((stop-start+1) / 2) - 1);
merge_sort(arr, start + ((stop-start+1) / 2), stop);
... | You're overflowing your heap allocations, corrupting the heap, and breaking things eventually. The problem is:
You allocate an array with stop - start + 1 elements (meaning valid indices run from 0 to stop - start.
In the subsequent loop (for (int i = start; i <= stop; i++){), you assign to any and all array indices f... |
72,032,281 | 72,032,543 | Aggregate class and non-viable constructor template | As we know, in C++20 a class that has a user-declared constructor is not aggregate.
Now, consider the following code:
#include <type_traits>
template <bool EnableCtor>
struct test {
template <bool Enable = EnableCtor, class = std::enable_if_t<Enable>>
test() {}
int a;
};
int main() {
test<false> t {.a = 0};... | The definition of aggregate has changed a lot, but the relevant part here has been pretty constant. The C++20 wording in [dcl.init.aggr] says:
An aggregate is an array or a class ([class]) with
no user-declared or inherited constructors ([class.ctor]),
no private or protected direct non-static data members ([class.ac... |
72,032,458 | 72,032,525 | How to detect non IEEE-754 float, and how to use them? | I'm writing classes for basic types, so that code is logically the same on multiple platforms and compilers (like int_least16_t for int). For fun! (I'm still a student.)
And I read this:
float [...] Matches IEEE-754 binary32 format if supported.
And what's worse:
Floating-point types MAY support special values:
∞, N... | In C++, the value of std::numeric_limits<T>::is_iec559 shall be true for all floating-point types T "if, and only if, the type adheres to ISO/IEC/IEEE 60559" and ISO/IEC/IEEE 60559:2011 is the same as IEEE 754-2008, so:
#include <iostream>
#include <limits>
int main() {
std::cout << std::boolalpha << std::numeric_... |
72,032,512 | 72,033,232 | `operator<<` on a container which works for both values and references | There is a container class container which is templated, so it can contain anything.
I want to add ability to print its contents to std::ostream so I've overriden operator<<.
However this has a drawback: if the container contains references (or pointers), the method only prints addresses instead of real information.
Pl... | You can use SFINAE to select an overload based on whether std::is_pointer<T>::value is true or false. This works already with C++11:
#include <iostream>
#include <deque>
template<typename T>
class container {
public:
// container() {} // dont define empty constructor when not needed
// or dec... |
72,032,754 | 72,033,059 | Unexpected Result with Cpp Vector insert | I have the following function
void rotate(vector<int>& nums, int k) {
int original_size = nums.size();
k = k%original_size;
nums.insert(nums.begin(), nums.end()-k, nums.end());
nums.resize(original_size);
}
For these inputs, I get the proper result
[1,2,3,4,5,6,7]
3
----
[5,6,7,... | You may not use insert with first and last being iterators to the same vector. That is because inserting elements invalidates iterators. From cppreference (overload 4):
The behavior is undefined if first and last are iterators into *this.
You can use std::rotate to rotate elements in a vector.
|
72,032,820 | 72,038,604 | How do you deploy/package a CMake project with Visual Studio? | I'm currently working on a small CMake project with visual studio and I'm wanting to distribute my current build but I have no clue how to, when testing the app on another system it would error saying what I'm guessing were runtime dll's that were missing. I can't find anything online about it, and the official CMake t... | Just like you have been told in the comments, the proper way to distribute an application on Windows is to use VC redistributable package. But if one wants to create an independent "bundle" CMake can help with it. It has a module which helps to bring the necessary dlls wherever needed. You need to understand and plan h... |
72,033,124 | 72,033,354 | Selecting files with folder using QFileDialog | I have a use case in an application using C++ and Qt (on windows 10). The application uses 7zip.exe as a subprocess to uncompress the files in a selected folder. I need to use QFileDialog to select a folder, and get all the files with extension .zip and .7z, to be selected automatically and then uncompress them using Q... |
it displays just the folder name not with no files selected.
That is what it is supposed to return. You asked it to display a dialog to select a folder, so that is all you can select. selectedFiles() will return the path to the selected folder, per the documentation:
https://doc.qt.io/qt-5/qfiledialog.html#FileMode... |
72,034,789 | 72,046,722 | Artefacts on OpenGL rendering seemingly specific to hardware | I am currently writing a graphics engine for OpenGL in C++. Here's the source if you're interested: https://github.com/freddycansic/OpenGL
These are the results when rendering a cube with a solid colour or a texture on my laptop (Ryzen 5500U, integrated Radeon graphics):
https://imgur.com/a/A50DHgW
These are the resul... |
int index = int(v_TexID);
if (index < 0) { // if index < 0 do a color
color = v_Color;
}
else { // else do a texture
color = texture(u_Textures[index], v_TexCoord);
}
This code is wrong in two ways. The GLSL spec clearly states in section 4.1.7:
Texture-combined sampler types are opaque types, declared and... |
72,035,237 | 72,035,487 | Create a copy constructor that reverses a stack using a linked list stack implementation | linkList::linkList(linkList const& rhs){
Node *temp = rhs.top;
Node *temp_stack = rhs.top;
while(temp){
char value = temp->letter;
// push(value);
push(temp_stack->letter);
temp = temp_stack->down;
temp_stack = temp_stack->down;
// temp = temp->down;
}
}
vo... | For starters declarations of these two pointers within the function
Node *temp = rhs.top;
Node *temp_stack = rhs.top;
does not make a great sense. They duplicate each other. It is enough to use one pointer to traverse the list rhs.
If you want to create a copy of the passed list then the function push is not s... |
72,035,443 | 72,035,823 | Can I ask a running thread about how much stack it has been using? | So let's say I have created a thread, on Windows OS, for which I know that the default stack size is much more than what is needed. Can I then run the application and ask the thread about the amount of stack it actually has used so that I know how much I should set its stack size instead of the default stack size?
| Windows usually doesn't commit the entire stack, it only reserves it. (Well, unless you ask it to, e.g. by specifying a non-zero stack size argument for CreateThread without also passing the STACK_SIZE_PARAM_IS_A_RESERVATION flag).
You can use this to figure out how much stack your thread has ever needed while running,... |
72,035,480 | 72,550,370 | Azure IoT Edge C++ module not sending device to cloud telemetry | I have written an IoT Edge C++ module that is sending the event output using the following function call:
bool IoTEdgeClient::sendMessageAsync(std::string message)
{
bool retVal = false;
LOGGER_TRACE(IOT_CONNECTION_LOG, className + "::sendMessageAsync(...) START");
LOGGER_DEBUG(IOT_CONNECTION_LOG, classNam... | It turned out that I need to call this function atleast a couple of times per second
IoTHubModuleClient_LL_DoWork(_iotHubModuleClientHandle);
which I was not doing. As a result the code was not working properly. Once I started doing it. The code just worked.
|
72,035,600 | 72,036,660 | How can I fix it "comparison between signed and unsigned integer expressions [-Werror=sign-compare]" | I tried to add unsigned, but the error still occurred, cpplint swears a lot because of this, I'm just tired and want to sleep(
string MinHeap::get_binary_string(unsigned int n,
unsigned int bit_size = -1) {
stringstream stream;
string reverse_binary, binary_str;
do {
stream << n % 2;
n /... | The problem is in the expression sizeB != -1.
The variable sizeB is an unsigned int, and the expression -1 results in a signed int. Since comparing signed values to unsigned values is very often a programming error, many compilers will warn you when it happens.
In your case, the -1 is just a special value carved out o... |
72,035,742 | 72,037,549 | How to initialize a variable from a class method binding C++ with Swig | I want to bind some C++ code to python thanks to swig.
In my C++ code, I initialize some important variables via class methods.
However, this kind of initialization seems to create some troubles to swig which returns Error: Syntax error - possibly a missing semicolon.
Below is a very simple example extracted from swig ... | SWIG's C++ parser doesn't support that initialization syntax, it seems.
Instead, in the header use:
extern float toto;
In the .cpp file initialize it:
float toto=MyClass().getSqr(3.);
Then SWIG will only see the extern declaration since it only parses the .hpp file. Here's a run of the result:
>>> import py_myclass
... |
72,036,077 | 72,036,191 | Using a value that can be approved if the user input was null | I am still a beginner in C++ but I have tried several methods to let the user only have one chance to get a value from the user if the user pressed enter without putting any value then it prints another value that I chose.
I tried:
#include <iostream>
#include <string>
using namespace std;
int main() {
char var;
ci... |
if (&var == NULL)
This test will never be true. Address of an automatic variable is never null.
A simple way to check whether a stream extraction was successful is to check the state of the stream by (implicitly) converting it to bool:
char var;
std::cin >> var;
if (std::cin)
std::cout << var;
else
std::cout... |
72,036,287 | 72,036,502 | How to left shift a character array? | #include <iostream>
#include<string>
using namespace std;
int main()
{
//for left shift geeksforgeeks should become eksforgeeksge
//for right shift geeksforgeeks should become ksgeeksforgeeks
char* original = new char[100];
cout << "enter the array\n";
cin >> original;
cout << "the array enter... | Given an array of 4 characters:
+---+---+---+---+
ltrs = | a | b | c | d |
+---+---+---+---+
Step 1: copy the first character to a temp variable:
const char temp = ltrs[0];
Step 2 copy slot 1 to slot 0:
+---+---+---+---+
ltrs = | b | b | c | d |
+---+---+---+---+
^ |... |
72,036,295 | 72,036,554 | Initialize std::array without constexpr | void test(const std::size_t& x) {
std::array<std::string, x> arr;
}
When I compile the above code I get this error.
main.cpp: In function ‘void test(std::size_t&)’:
main.cpp:15:24: error: ‘x’ is not a constant expression
How can I get the above code to compile?
| Template arguments must always be constant expressions, and function parameters are never constant expressions. To make this code work, you could do as is suggested in the comments and use std::vector instead, or you could make your test function be a template and make x be a template parameter instead of a function pa... |
72,036,452 | 72,036,501 | Parametrized Template Class constructor with another template class | I am trying to initialize a Calculator with two Complex variables. Both these classes are template classes.
calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
template <class U>
class Calculator{
private:
U left_val;
U right_val;
public:
Calculator(){}
Calculator(U m_left_va... | The issue is that there's no way to differentiate between the zero parameter constructor of Calculator, and the two parameter constructor with default arguments. You should just remove your zero parameter constructor.
|
72,036,510 | 72,036,529 | What happens if you don't call a base class's constructor for different derived constructors with different signatures? | Say I have a base and derived class like this:
class Base {
public:
Base() { ... };
Base(int param) { ... };
};
class Derived : public Base {
public:
Derived() { ... };
Derived(int param) { ... };
Derived(int p1, int p2) { ... };
};
Note that I'm not explicitly calling any of Base's constructors f... | Quoting from cppreference's description of constructors and how inheritance relates to them:
Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place w... |
72,036,549 | 72,036,570 | Why does getline() not read the last int value in the line? | I have a file that contains a list of books. Each book has 4 variables delimitated by a Tab.
The variables are
Title
author
isbn
qty
and there are around 400 book entries.
I have managed to write a function that reads each input to an array and saves it to a Book object.
void loadFile() {
std::ifstream inputFi... | The reason is that there's (likely) no tab character at the end of the line after the qty. So when you call line.find("\t", field2) the 4th time, it returns string::npos and you don't store anything in bookArray[3]
The best fix is probably to put an else there with the if:
} else {
std::string str2 = line.... |
72,036,711 | 72,036,761 | Is it possible to capture return value of function used in std::call_once? | Suppose I have a function returning an expensive object and I want it to call exactly once while having an access to return value of the function.
Is this achievable with std::once_flag and std::call_once or I need to go with boolean flags, etc..?
Simple example:
using namespace boost::interprocess;
shared_mempry_objec... | Simply use a static function variable.
using namespace boost::interprocess;
shared_mempry_object& openOrCreate(const char* name)
/// ^ return by reference to prevent copy.
{
static shared_memory_object shm(open_or_create, name, read_write);
// ^^^^^^ Make it static.
// This means it is in... |
72,036,882 | 72,037,001 | What is correct way to compare 2 doubles values? | There are a lot of articles, PhD publications, books and question here on this topic, still my question will be pretty straightforward.
How can we improve this or workaround without writing dozens of ifs?
Suppose I have 2 doubles;
double d1 = ..;
double d2 = ..;
The most naïve think we can try to do is to try if(d1==d... |
So the question will be is there a generic solution/workaround for this
There will not be a universal solution for finite precision floating point that would apply to all use cases. There cannot be, because the correct threshold is specific to each calculation, and cannot generally be known automatically.
You have to... |
72,037,962 | 72,038,039 | The code is erasing just one dublicates and not another. Why so? | enter image description here
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int>v;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
for(int i=1;i<nums1.size();i++)
{
if(nums1[i]==nums1... |
In the first 2 loops, you are erasing an element in a std::vector, from within a loop traversing its elements. This is a bad idea because the std::vector's size and element indices will change. A similar issue arrised when you use iterators which are invalidated by using erase. See: std::vector::erase
You can see her... |
72,038,088 | 72,038,126 | correct fix for warning: dereferencing type-punned pointer will break strict-aliasing rules? | Given:
inline uint16_t Hash3_x86_16(const void* key, int len, uint32_t seed)
{
uint32_t hash32;
Hash3_x86_32(key, len, seed, &hash32);
return (reinterpret_cast<uint16_t*>(&hash32)[1] | reinterpret_cast<uint16_t*>(&hash32)[0]);
}
What is the correct/best fix to prevent GCC from giving the following warning?
warn... | Bit shifting:
return static_cast<uint16_t>(hash32 | (hash32 >> 16));
|
72,038,390 | 72,038,429 | How to input 2D vector correctly? | When I try to set and populate a 2D vector as follows, I couldn't input int numbers to them.
I try to input numbers usinga range-based for loop; but it doesn't finish after the expected number of loop cycles.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int N;
vector<vector<int>> A(N,... | When running your code on linux you for example, I got:
terminate called after throwing an instance of 'std::length_error'
what(): cannot create std::vector larger than max_size()
If you encountered this, it should have been part of the question; if not, you still should have reported more on the actual behavior yo... |
72,038,591 | 72,040,008 | What is the use of _time64_t in MFC | Can someone explain to me what is _time34_t ? How will I use it ? I don't know how this _time64_t works. Should I use it as:
CTime::GetCurrentTime(_time34_t);
| There is no _time64_t in ATL or MFC. There is __time64_t (two leading underscores). That, however, is part of the (Universal) CRT, and not part of ATL or MFC either.
__time64_t is defined in corecrt.h as follows:
typedef __int64 __time64_t;
In other words: a 64-bit signed integer type. Values of this type are commonly... |
72,039,195 | 72,039,724 | CMake add_executable() failing to make executable and 3rd party library failing to untar | Problem Background
I am trying to incorporate UnitTest++ into my linux-based C++17 project template. I have done this on windows pretty easily, but I am running into major issues on linux for some reason.
I used Cmake 3.21 on Windows and I am currently using CMake 3.17.5 on Linux.
I downloaded the UnitTest++ source cod... | Somehow you set --target ExecutableName, that limits the build to a single target, the main executable ExecutableName. Try to select another target, or let it unset.
|
72,039,771 | 72,039,852 | Finding the largest prime factor? (Doesn't work in large number?) | I am a beginner in C++, and I just finished reading chapter 1 of the C++ Primer. So I try the problem of computing the largest prime factor, and I find out that my program works well up to a number of sizes 10e9 but fails after that e.g.600851475143 as it always returns a wired number e.g.2147483647 when I feed any lar... | Your int type is 32 bits (like on most systems). The largest value a two's complement signed 32 bit value can store is 2 ** 31 - 1, or 2147483647. Take a look at man limits.h if you want to know the constants defining the limits of your types, and/or use larger types (e.g. unsigned would double your range at basically ... |
72,040,306 | 72,043,335 | Makefile target with wildcard is not working | I have a simple project, whose folder structure is something like:
ls -R
.:
build include makefile src
./build:
./include:
myfunc.h
./src:
main.cpp myfunc.cpp
I want to compile the .cpp sources into .o object files, which should end into ./build folder. Using the GNUmake documentation and other sources (e.g. Pr... | The problem is here:
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(DEPS)
$(CXX) $(CXXFLAGS) -c $< -o $@
See the $(DEPS)? That expands to myfunc.h. The compiler knows where to find that file (or would if this recipe were executed), because you've given it -I./include, but Make doesn't know where to find it (so it passes over th... |
72,040,366 | 72,040,743 | Why the definition works at function level, but not at class level? | #include <iostream>
#include <vector>
using std::vector;
using MATRIX = vector<vector<int>>;
class Matrix {
public:
MATRIX matrix;
int row = matrix.size();
int col = matrix[0].size();
void repr() {
for (const vector<int> &sub_arr: matrix) {
for (int element: sub_arr) {
... | The most "natural" solution I can see is to have a constructor taking the matrix data as an argument, and use that as the base for initializations:
class Matrix {
size_t row;
size_t col;
MATRIX matrix;
public:
Matrix()
: row{ }, col{ }, matrix{ }
{
}
Matrix(MATRIX const& data)
... |
72,041,136 | 72,042,219 | What's the most efficient way to emplace a new element in a vector? | If I want to add a new element to a vector there are a couple of ways I can do it:
struct ZeroInitialisedType
{
int a, b, c, d, e, f;
}
std::vector my_vector;
ZeroInitialisedType foo;
foo.a = 7;
//....
my_vector.push_back(foo);
Can the compiler make it so that instead of writing into the local variable and then cop... | There are two independent questions related to your problem. The first one is whether an object of type ZeroInitialisedType can be constructed such that some of its members are not zero-initialized. I believe this is not possible according to the aggregate-initialization rules. A simple demo is:
struct X { int a, b, c,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.