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,157,532 | 62,157,659 | Load data into std::vector<char> efficiently | My understanding is that you can access the data in a std::vector using pointers. For example:
char *ptr;
std::vector<char> v1 {'A', 'B', 'C'};
ptr = &v1[0]
if (*(ptr+1) == 'B')
std::cout << "Addressing via pointer works\n";
How about loading a std::vector directly? For example:
std::vector<char> v2;
v2.reserve(3)... |
Is there any way to tell the v2 vector that its internal memory buffer is loaded with data?
No.
The behaviour of your second example is undefined.
This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.
You can read a file into vector like this:
std::vector<char> v3(... |
62,157,705 | 62,164,946 | Receiving the error "undefined symbol" when loading C++ dynamic library from C executable | I am trying to write a plugin for a popular program whose code and compilation process I do not have control over. The program is written in C. However, I have written parts of my plugin in C++, since I use the QT5 library for graphics capabilities. The functions that the C program calls are written in C.
When the C pr... | Apparently, I'd forgetten to put the #include "moc_controller.cpp" line at the bottom of a file that needed it.
For anyone else chasing this issue while using Qt on CMake, consider making sure that the proper lines are added.
|
62,157,717 | 62,158,369 | c++ definition inheritance scheme | the code is probably bad written and I would like to know how it should be done correctly.
Thanks for help
For the following inheritance scheme: A→B→C
a) define classes assuming that class A is to be an abstract class
b) equip all classes with a virtual name method returning the class name
c) add virtual destructors
d)... | Your code cannot compile and have a lot of syntax error
b) equip all classes with a virtual name method returning the class name
that means the profile can be
virtual const char * name();
or
virtual const char * name() const;
or
virtual std::string name();
or
virtual std::string name() const;
but not virtual void... |
62,157,814 | 62,157,913 | Is there any practical reason to check if something is destructible before calling its destructor? | So I've been messing around trying to implement a variant/tagged union class and needed a way to write generic destructors and made what I thought was a silly mistake forgetting that some types don't have destructors, doing something like
template<typename T>
void destruct(T& thing) {
thing.~T();
}
Yet, this work... |
Yet, this worked fine even with types that didn't have destructors, like int or struct A {int b;};
Those are examples of types that are trivially destructible. It is well defined to invoke their "destructor". It has no effects.
But is there actually any difference between the code?
Only for types that are not destr... |
62,158,018 | 62,158,133 | Is it possible in C++ to have a method in the superclass that when called by each subclass returns a shared_ptr to that subclass? | I want all children of a superclass to perform a similar action. So I figured I could have a method in the superclass to do so. The action requires sending a copy of (or shared_ptr to) itself as an argument to a method. But I do not know if such thing is possible or not, and if yes, how should it be done.
To clarify my... | It is not entirely clear what you are doing, but you certainly want to derive your Parent from std::enable_shared_from_this.
This will give you a member function shared_from_this() (which is more or less what you want to achieve via getPtr()).
However, it must be stressed that your Parent objects must themselves be man... |
62,158,041 | 62,158,285 | Apply the same random shuffle on multiple containers | I am writing a program where a Manager-class handles different containers.
Every container is the same size with the same contents and needs to be (randomly) shuffled the same way.
(FYI, The program will later apply different operations on each container)
What I want to achieve:
Randomly sort each container, but all co... | Both std::random_shuffle before it ws removed and it's replacement, std::shuffle, support passing to them a pseudo-random number generator. You should be able to leverage that to pass "the same" generator to each invocation to of the shuffler so that it shuffles in the same manner.
I say should here because the impl... |
62,158,085 | 62,158,199 | Is it acceptable to `const_cast<Foo*>(this)` if public state doesn't change? | I have a C++ class that calculates some statistic parameters on the go. Is it acceptable to cast away const from this to implement caching of lengthy computations, if I don't change publicly visible state, and const function in question is idempotent and pure/referentially transparent?
#include <cstdio>
#include <unist... | This problem is solved by using the mutable keyword. This keyword indicates that the member variable can be modified in a const qualified function:
struct S
{
mutable int x; // some data that is not relevant to users of the object (e.g. a cache variable)
int y;
void f() const
{
x = 42; // fine
y ... |
62,158,534 | 62,158,715 | I can't able to add an array after declaring the array | In this program
marks[0]="50";
is not working. It gives the error
[Error] invalid conversion from 'const char*' to 'int' [-fpermissive]
Here's the program:
int main()
{
int marks[40];
marks[0]={"50"};
cout<<"Enter the marks: "<<endl;
cin>>marks[1];
cout<<marks[0];
cout<<marks[1];
... | When you do:
marks[0] = "50";
you are trying to assign a char const * to an int. Hence the error message.
The code you probably mean to write is:
marks[0] = 50;
which assigns an int to an int.
|
62,158,678 | 62,292,726 | placement new on a class with reference field | This is a code example from the C++20 spec ([basic.life]/8):
struct C {
int i;
void f();
const C& operator=( const C& );
};
const C& C::operator=( const C& other) {
if ( this != &other ) {
this->~C(); // lifetime of *this ends
new (this) C(other); // new object of type C created
f... | To answer the currently open questions:
First question:
What is the case of such code in C++14 or before (when std::launder didn't exist)? Probably it is UB - this is why std::launder was brought to the game, right?
Yes, it was UB. This is mentioned explicitly in the NB issues @Language Lawyer referred to:
Because... |
62,158,698 | 62,158,844 | Which of these is the proper usage of std::move | I'm trying to change my code to take a vector by value using std::move instead of passing it by reference because I've gathered that would be more efficient. I've seen different ways of doing this though, one having the constructor pass by value and using std::move in the constructor, and the other way being to initial... |
StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))
This constructor takes the argument by value. The parameter can either be copy constructed from an lvalue argument, or move constructed from an rvalue. This ability to choose between copying from lvalue and mo... |
62,158,785 | 62,231,589 | How to extract output of torch model in c++? | I have got trained keras model and converted it using mmdnn. Then I try use it in c++ code:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <torch.h>
int main()
{
cv::Mat image;
image= cv::imread("test_img.png", cv::IMREAD_GRAYSCALE); // Read the file
t... | In this case the answer of model is tuple of 2 images. We can extract them by such way:
torch::Tensor t0 = output.toTuple()->elements()[0].toTensor();
torch::Tensor t1 = output.toTuple()->elements()[1].toTensor();
Variables t0 and t1 contain tensors with output of model.
|
62,158,815 | 62,159,445 | How to Translate "10:10" to epoch format | I am parsing a .json and plotting it using qt custom plot but for the x axis I need to translate "10:10" to secSinceEpoch, does anyone know the easiest way about going about this? I also have the date in ISODate format(2020-05-26) so I need to basically do the "date: 2020-05-26" + "minute: 10:10" to get the correct x a... | I think you can parse date and time separately:
const char * date = "2020-05-26";
const char * time = "10:10";
auto d = QDate::fromString(date, Qt::ISODate);
auto t = QTime::fromString(time, "hh:mm");
auto dt = QDateTime(d, t);
qDebug() << "d = " << d << " t = " << t << " dt = " << dt << " secs = " << dt.toSecsSince... |
62,159,121 | 62,159,209 | Identifier not found error when accessing Template Class Member from Sub-Class | This is my very first question on StackOverflow. I've searched for similar "Identifier not Found" errors but couldn't find anything helpful. I'll be grateful for your help since I've been trying to work this out for 2 hours with no results.
It basically creates an object of type "Addition" and prints "1 + 1 = 2" (if it... | When inheriting from a class template, identifiers need to be qualified so that the compiler knows where they come from. In this case, in the definition of Addition, you could do:
T Result() const { return this->m_Argument_1
+ this->m_Argument_2; };
Alternatively, you could qualify the names l... |
62,159,348 | 62,159,570 | print value of char array which is loaded with void pointer | I have below code where I am passing address of array of charectors to function "GetStr". GetStr function prototype is fixed.
Here in below code I am passing command line argument where string to function "GetStr" and update the value in the address of variable "str".
PRoblem:
At Print 1, I am getting the value what I... | You have to use strcpy() to copy a string. You're just assigning the address of argv[1] to the local variable RetVal, which has no effect on the array in the caller.
You should also check argc to determine if argv[1] has been supplied.
int GetStr(void *RetVal, int argc, char **argv)
{
if(argc != 0){
if(arg... |
62,159,478 | 62,159,510 | Mutating constant object via pointer copied from 'this' in constructor | Example code:
struct Foo {
Foo() { instance = this; }
int value = 0;
static Foo * instance;
};
Foo * Foo::instance = nullptr;
int main(int argc, char * argv[]) {
Foo const foo;
//foo.value = 1; // Compiler error, as expected.
Foo::instance->value = 1; // Fine.
}
Here foo is constant, but can ... | It is absolutely ill-advised to do so. For many reasons.
First, it's not thread-safe.
Second, mutating const-qualified objects by "unconsting" them by const_cast, or by the method that you've shown (or by any other method, for that matter), is simply undefined behaviour.
|
62,159,524 | 62,159,595 | strange behaviour of ternary operator in recursion | There is a properly working code:
#include <iostream>
int sum_odd_digits(int n)
{
if(n==0) return 0;
else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
}
int main(int argc, char ** argv)
{
std::cout<<sum_odd_digits(25897641)<<std::endl;
return 0;
}
But if to remove the outer parenthesis, i. e. replace
e... | This is due to operator precedence: + has higher precedence than ?:, so your incorrect version resolves to:
((n%2)!=0) ? n%10 : (0 + sum_odd_digits(n/10));
^ ^
// addition is grouped first
which now has obviously different grouping than the first version.
|
62,159,538 | 62,159,856 | Is the length in mmap a number of bytes or a number of pages? | In the function:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
Does the argument length in mmap represent a number of bytes or a number of pages? Also, can I use mmap similarly to malloc? What are the differences?
| The length parameter is in bytes. The Linux man page does not say this explicitly, but the POSIX spec says (emphasis mine):
The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off... |
62,159,577 | 62,160,586 | C++: get time zone deviation | So I want to creata a time stamp (as a string) with the format HH:MM:SS in C++. I use std::chrono to get a unix time stamp and then calculate the hours, minutes and seconds.
// Get unix time stamp in seconds.
const auto unix_time_stamp = std::chrono::system_clock::now();
long long seconds_since_epoch = std::chrono::dur... | Some implementations of std::tm will contain a member that has the local offset as a member. ... But it isn't portable.
One trick is to take your seconds_since_epoch, and either assign it to a std::time_t, or just make its type std::time_t in the first place instead of long long.
... Oh, wait that isn't quite portabl... |
62,159,628 | 62,160,186 | Using a prvalue to create a shared_pointer | I have a class functionCombiner which constructor looks like this
FunctionCombiner::FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>> Inner_) : Inner(std::move(Inner_)), valuationFunction("", 0) //<- Needs to initalize itself even though it gets all data from inner functions.
{
}
In my main class I'm ca... | (Shorting some names to make the example readable w/o horizontal scrollbars. You should consider doing the same...)
Passing {x,y} to make_shared() is attempting to forward a brace-enclosed initializer list, not to initialize the value in the shared pointer, but the temporary object its constructor takes. It's not som... |
62,159,742 | 62,163,090 | Reading a XML file in C++ with TinyXML2 | I'm pretty new to using XML in C++ and i'm trying to parse a list of files to download.
THe XML file I'm using is generated via PHP and looks like this :
<?xml version="1.0"?>
<FileList>
<File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>
The code I'm using in C++ is the following, which I came up using s... | I don't know if you have C++17 available, but you can remove a lot of noise by using auto* and if-init-expressions (or rely on the fact that pointers can be implicitly converted to boolean values.)
The main issue with your code is you were not using XMLElement* but instead a XMLNode. The function tinyxml2::XMLDocument:... |
62,159,746 | 62,159,817 | Is there a default C++ comparator for user defined structure? | #include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
map<TreeNode*,int> mp;
TreeNode* x=new TreeNode(4);
TreeNode* y=new TreeNode(5);
TreeNode* z=new TreeNode(6);
... | You have a map of TreeNode*, not TreeNode. A TreeNode* is just a pointer and like all other non-class member pointers, the default comparator for std::map, std::less, will handle them in a implementation defined manner.
If you had a map<TreeNode,int> mp;, then it would fail to compile as there is no operator < define... |
62,159,868 | 62,160,130 | How to use double quotes in xml? | I use QT's QDomDocument. There is a problem when using QDomDocument::setContent(), the compiler complains at this line:
< field regexp = "text".+"text" >
I tried so:
< field regexp = "text"".+""text" >
< field regexp = "text'"'.+'"'text" >
< field regexp = "text\".+\"text" >
| XML attribute values can be delimited by ', which is useful when the attribute value must contain a ".
So, if the attribute value in intended to be, say, text".+"text, use:
<field regexp='text".+"text'>
Alternatively, " can be used for ".
<field regexp="text".+"text">
See also:
When to escape double q... |
62,159,885 | 62,159,996 | Why is an overloaded function with two arguments of type double called when passing a long long? | I wrote those two overloads:
int func(int, int) {
return 1;
}
int func(double, double) {
return 2;
}
When I call them with the obvious two calling schemes, i.e. func(1, 1) and func(1.0, 1.0), the first and the second overloaded functions are called, respectively, and when I try to call func(1, 1.0) it gives ... | Which function from an overload set is chosen to be called (i.e. overload resolution) depends (in part) on how many arguments of the function call must go through an implicit conversion, and what kind of conversion is needed.
The rules that are relevant to your example are:
For each pair of viable function F1 and F2, ... |
62,159,969 | 62,166,990 | Timer function distorting a draggable line segment | I've a draggable line segment. Also I've got a timer. This line segment is getting distorted when I operate a timer in this window.
protected:
// override / make our own of these function to track mouse movement and
void mousePressEvent(QMouseEvent *event) ;
void mouseReleaseEvent(QMouseEvent *e... | Could it be that your update method clashes with QWidget::update? (see https://doc.qt.io/qt-5/qwidget.html#update)
I'm not entire sure about what class your code is running it (what is the base class), but it seems like a plausable issue to me. Try renaming your update method to onTimeout or something like that instead... |
62,160,449 | 62,160,578 | My files get deleted when moving content from the first file ("constituencies") to the second ("temp") and renaming it after | /* I want to transfer the content from the first file ("constituencies") to the second ("temp") and then delete the original ("constituencies") file then rename() ("temp") to ("constituencies") so it can be refreshed with a specific entry/line be deleted from the file by first finding it and then not adding it in the n... | This line fails if temp.txt does not exist:
fstream temp("temp.txt", ios::out | ios::in);
but you don't notice that since you don't check if it was successful.
Remedy:
ifstream constituencies("constituencies.txt");
if(constituencies) {
// constituencies.txt successfully opened for reading
ofstream temp("temp.t... |
62,160,838 | 62,160,879 | C++: initialize vs assignment? | I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment. It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function. Is this correct?
Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. b... | The curly braces is part of uniform initialization which was added with the C++11 standard.
Using
int value {1};
is equivalent to
int value = 1;
There's some differences between using curly braces and "assignment" syntax for initialization of variables, but in this simple case they're equal.
|
62,161,146 | 62,197,416 | WinRT app calling win32 c++ dll sending parameters | Hey all this is the first time working with C++ so be kind :)
I have made a WinRT app that, since of some type of "sandbox" it does for those apps I am unable to access anything outside of that (like what I want to access - my desktop app.
So reading here and there I found out that if you make a C++ Dll and call it fro... | Well I think I found a good way to achieve my goal here.
I have added a simple, small Web Server in C# that WinRT can call. Doing this call allows me to run anything I need to outside the sandbox of the WinRT application.
This is the web server C# code (SimpleWebServer.cs):
using System;
using System.Net;
using System.... |
62,161,640 | 62,162,163 | Disabling assert macro in C++ | I'm trying to disable the assert macro in C++ in this way:
#include <stdio.h> /* printf */
#include <assert.h> /* assert */
#define NDEBUG
void print_number(int* myInt) {
assert (myInt != NULL);
printf ("%d\n", *myInt);
}
int main ()
{
int a = 10;
int * b = NULL;
int * c = NULL;
b = &a;
prin... | The NDEBUG define controls the definition of the assert macro, not its expansion. In order for it to be effective, you need to define it before the macro itself is defined, which happens in assert.h.
There are two ways to achieve that:
put the #define NDEBUG before the line that says #include <assert.h>; or
define ND... |
62,161,652 | 62,162,376 | Tic tac toe Minimax Algorithm Having Weird Behavior (C++) | The other day, I wrote a console game of Tic-Tac-Toe in c++ for my son. He wanted me to add a computer, and I ended us using the minimax algorithm for the first time. I did some quick testing, but really just gave my laptop to my son as soon as it was printing stuff, who played with it for a couple minuets. I looked ov... | It looks like you only call minimax with a depth of three, so the algorithm will only look up to three moves ahead, if you want optimal play you need to set the depth to > 9, so that the agent is always looking ahead to the end of the game.
|
62,161,877 | 62,162,152 | Initialize a new static variable every loop, C++ | There is a way in C++ to create a new static variable (with a different memeory address) in a loop for every iteration?
Here it is an example:
static vector<int *> vec;
for(int i=0; i<n; i++){ //n is a generic number
static int var=i; //var should be a new static variable every loop
vec.pushback(&var);
}
The ... | What is a static variable?
In most operating systems the global variables and all static variables are placed into the program image in their own data section. If they have complicated initialization then those are run on program start, or protected with locks and set on first use.
The only difference between global an... |
62,161,963 | 62,162,388 | return type deduction of recursive function | Recently, I read Barry's answer to this question Recursive lambda functions in C++11:
template <class F>
struct y_combinator {
F f; // the lambda will be stored here
// a forwarding operator():
template <class... Args>
decltype(auto) operator()(Args&&... args) const {
// we pass ourselves to f,... | The difference is that in #1 the initial and recursive calls to y_combinator have different argument types, whereas in #2 they have the same argument types (including value category).
In #1, the initial arguments (1, 2) are both int prvalue, whereas the recursive arguments g(a + 1, b) are respectively int prvalue and i... |
62,162,046 | 62,162,110 | Comparing iterators crashes program without errors in custom bubble sort implementation | I'm relatively new to C++. I have been trying to use iterators to sort a vector. I'm using bubble sort. I don't want to know if my bubble sort implementation works or not, I just want to know what's crashing my program.
template<typename iter>
void bubbleSort(iter start, iter end) {
for (iter &j = end; j != start; ... | In that line you are dereferencing i + 1, in the last iteration of the cycle it will dereference .end() which invokes undefined behavior, .end() is one past the last element, it can't be dereferenced.
Quick fix is to make your stop condition i != end - 1.
This, though will not fix the the bubble sort implementation wh... |
62,162,058 | 62,162,392 | What is the significance of using a bracket on the node of the linked list in c++? | In the below code there is a node pointer naya in the mn function. In the if condition first time the naya pointer is pointing to the null and we are trying to access its data. If we try to do the same code without the brackets around the naya pointer, then it gives error such as:
prog.cpp: In function ‘void mn(Node*, ... | The reason it has to be written this way is because of operator precedence, which decides which operations are executed using which operands. You can see from that link that 'member access' or -> is bound before 'Indirection (dereference)' or *a by default. By enclosing the dereference operation in brackets you can spe... |
62,162,279 | 62,162,411 | Type requirement in C++ concepts (C++20) | I am learning the newly implemented concepts of C++20 standard using g++ 10.
I am stuck with a simple type requirement. Namely I want to implement a requirement for a template argument T to have T::inner member name.
Here is my code with error. What is wrong with this simple code and how to fix it?
#include<concepts>
... | This:
template<typename T>
concept ContainsInner = requires
{
typename T::inner;
};
is requiring that T has a type named inner. Which gcc tells you in its error:
source>:6:12: note: the required type 'typename T::inner' is invalid
6 | typename T::inner;
| ~~~~~~~~~^~~~~~~~~
Q doesn't have a type named... |
62,162,548 | 62,162,969 | How to initialize Directwrite IDWriteTextLayout properly in a Direct2D window | I'm trying to write text to my ID2D1HwndRenderTarget* renderTarget-window using Directwrite. That works good and text appears where it should. But i have the feeling i'm doing something wrong in Graphics::DrawMyText. I think I should create my IDWriteTextLayout* textLayout also in the Graphics::Initialisation but if I ... | The text of a DWrite layout is indeed fixed, your choices are either to create (and release) layout objects or go the much harder route of using IDWriteTextAnalyzer (along with IDWriteTextAnalysisSource/IDWriteTextAnalysisSink). It would have been nice if the text of a layout were mutable but MS simply didn't make that... |
62,162,638 | 62,162,732 | recursive binarySearch with array of strings | My function works for the first 4 elements, but returns -1 for 12 and 14..even though there in the array.
I've tried changing some of the if statements and using .compare but haven't had any luck.
Any ideas?
Thanks
/** Searches the array anArray[first] through anArray[last]
for a given value by using a binary search.
... | Problem is the fact that for binary search to work your array has to be sorted with the same criteria you use with your binary search. Array you provided is not sorted. You sorted numbers, but you have strings and they compare differently - lexicographically. Which means that "12" comes before "5" and so on. So you eit... |
62,162,708 | 62,163,565 | Trouble setting up Boost library with GCC-6 in Clion | I am not able to build a simple Hello World program in GCC-6 but it works fine with Clang in Clion.
Now I try to build and run the first example of Boost Date Time here
Boost Date time Example
My CMake looks like
cmake_minimum_required(VERSION 3.16)
project(Boost_Run_2)
set(CMAKE_CXX_STANDARD 11)
find_package(Boost ... | I was able to fix this issue.
I realized my Boost libraries were not installed properly.
For some reason, Homebrew does not install Boost libraries properly and you've got to install it the way it's mentioned in their documentation.
Getting Started on Unix Variants
StackOverflow question How do you install Boost on Ma... |
62,162,891 | 62,162,934 | How does stringstream work when converting a double value into a char variable | I saw a post on here asking how to convert a double variable value into a char array. Someone said to just use stringstream but didn't explain why it works. I tried googling but couldn't find any documentation on specifically how it converts it. I was wondering if someone could explain to me how it works. Here is the c... | When you do ss << a; you are inserting the double in the stringstream (let's suppose it holds the value in a string) and so when you run ss >> b; it just copies the string in the char[] char by char.
Now the only point is to convert double to string, thing that can be achieved with a simple algorithm:
std::string conve... |
62,162,984 | 62,163,069 | C++ pointer problem : How to fix bugs in these codes? | #include <vector>
struct node{
int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
temp->x = i;
ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
std::cout << (*j)->x;
}
delete temp;
This prints 999999999 as outp... | You are allocating only 1 node object and then storing 10 node* pointers into your vector that all point at that 1 node object. So, in your 1st loop, all of the assignments to x are on that 1 node. When that 1st loop is finished, whatever last value was assigned to the 1 node's x, that is what your 2nd loop prints ou... |
62,163,282 | 62,163,463 | Overriding a publically aliased method via private inheritance | I have a class heirarchy where there is one base type Base with a list of implementations and another base class, AnotherBase, that is almost like Base but a little different. To express this in the language I used private inheritance on the second base class (so there is no as-is relationship between implementations o... | On these two lines within the declaration of Derived, Base is resolved as the the privately-inherited Base type since it is in scope -- even though it is private:
explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<Base> base_;
C++ does not ignore in-scope names that refer t... |
62,163,702 | 62,164,004 | Working code throwing exception when new lines added. Debugging tips? | I'm working on a proprietary code base, so I have to abstract this.
I'm trying to set the value of DataType_T*** myData in MyApplication. I'm using a shared c++ library (which I denote library A) to set the value. The shared c++ library is just a simple wrapper class around a C API.The C API is included in library A as... | I think you want something like this:
const DataType** myData;
GetData(&myData);
const void* strData = myData[0]->strData;
Because in the original code you're just passing a pointer by value; an uninitialized pointer, and then accessing that same uninitialized value.
ed: fixed up the third line
|
62,163,732 | 62,163,820 | Converting a function's parameter - signature from using an `std::function<T>` to a template parameter type | In my existing codebase, I have a non-template class and its constructor has the following declaration signature...
struct SomeStruct {
double a_;
double b_;
SomeStruct(double a, double b) : a_{a}, b_{b} {}
}
class SomeClass {
private:
SomeStruct fields_;
size_t n_;
std::function<double(double... | I would suggest not specifying the template parameters for the constructor, but instead provide a deduction guide like this:
template<typename FieldType, typename ValueType, typename Func>
SomeClass(SomeStruct<FieldType>, ValueType, Func*)
-> SomeClass<FieldType, ValueType, Func>;
and then you can call the constructo... |
62,163,802 | 62,178,586 | C++ small function not inlining | I have a hot and critical path function (about 45% of cycles:ppp as per perf record) in my C++17 application that is not being inlined as I would expect. It's a tiny function -- it simply returns the value of an atomic pointer member. The disassembly confirms that the function is just four assembly instructions, includ... | PS
The always_inline attribute probably does not mean what you think it means. Normally g++ does not inline anything when there are no optimizations turned on (as this makes debugging easier, I assume). By adding this attribute (always_inline) the compiler will inline when not optimizing (probably not what you want) bu... |
62,164,353 | 62,186,402 | Algorithm to return arg_min and optionally min_val | I made a simple arg min function based on a couple of STL algorithms:
template<class ForwardIt, class UnaryOperation>
ForwardIt arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op)
{
if (first == last) return last; //we were passed an empty container
ForwardIt smallest = first; // iterator to the elem... | Based on the comments above, this is want I came up with:
template<class ForwardIt, class UnaryOperation>
auto arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op) ->
std::pair<ForwardIt, std::optional<std::decay_t<decltype(unary_op(*first))>>>
{
if (first == last) return {last,{}}; //we were passed an... |
62,164,376 | 62,169,145 | Are lock and unlock on the same mutex sequential consistent? | For mutex lock(), the standard mentions:
Prior unlock() operations on the same mutex synchronize-with (as defined in std::memory_order) this operation.
This answer tries to explain what synchronize-with means according to the standard. However, looks like the definition is not clearly specified.
My main question is, ... | The synchronize-with relation is clearly defined. The standard states the following:
Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store. [...] [ Note: The specifications of the... |
62,164,701 | 62,236,936 | hashtable: how to understand this implementation of hashtable based on List in STL | I'm learning to build a hashtable with c++. And find this post: https://www.geeksforgeeks.org/c-program-hashing-chaining/.
It implemented a simple and basic version of hashtable (not production level) with chaining to fix hash collision issue.
I followed the post and run it locally and it works as expected. The imple... |
list<int> *table : table should be buckets array. Right? list<int>* should be list type pointer, right? How it works here?
In this awful code, table is a pointer to a list<int>, but when you have a pointer to an item and happen to know there's an array of contiguous elements there, you can index it like an array, so ... |
62,164,702 | 62,165,033 | Double Dispatch in C++ | I have the need for the following type of dispatch function. In my application, what I really have is a pointer to a state base class (foo) as well as a pointer to a measurement base class (bar). Based on what derived instance is passed to the dispatch2 function, I need to produce an estimated measurement given the s... | One way (certainly not the only way) is to call a virtual function on foo, passing it bar. Each derived type of foo implements this dispatch function the same way, which will pass itself to a virtual handler function in bar.
When you need to add more, you extend the interfaces to accept the new type(s). All the foo f... |
62,164,882 | 62,165,177 | Why does std::set.erase(first, last) impact the container from which (first, last) were taken? | I will preface that I'm fairly new to C++ in general. Recently, I ran into some perplexing behavior from the std::set.erase() method, which I have isolated into the following code. This code sample crashes with a segmentation fault when it hits the second for loop:
#include <set>
#include <iostream>
int main() {
s... | The arguments to the erase function are iterators. Iterators are not portable across objects. The iterators that you pass to bar.erase are supposed to be iterators on bar. If they're not, you get undefined behavior.
The crash probably happened because the call to bar.erase somehow got rid of the contents of foo, bec... |
62,165,001 | 62,165,046 | complex<> using list initializer vs constructor? | I'm reading Stroustrup C++ 4th Ed. Page 162 Types and Declarations. Specifically, where the following is allowed to construct a complex<> object.
The book comments that case A is "use constructor". Is case A really a list initializer and the constructor method of initialization is performed in B or C?
#include <iostr... |
complex<double> z = { 0, 3.14 }; // A performs copy-list-initliazation (since C++11).
complex<double> h(0, 3.14); // B performs direct initliazation.
complex<double> i{0, 3.14}; // C performs direct-list-initliazation (since C++11).
The effects are all the same for this case; objects are initialized by the constructo... |
62,165,044 | 62,165,255 | Why StringCopyFromLiteral is faster than StringCopyFromString? | The Quick C++ Benchmarks example:
static void StringCopyFromLiteral(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
std::string from_literal("hello");
// Make sure the variable is not optimized away by compiler
benchmark::DoNotOptimize(from_literal);
}... | The answer is simple. In the case where you construct an std::string from a small string literal, the compiler optimizes this case by directly populating the contents of the string object using constants in assembly. This avoids expensive looping as well as tests to see whether small string optimization (SSO) can be a... |
62,165,081 | 62,165,099 | Can we use derived class in place for anywhere requiring the base class? (In the context of templates) | I'm am quite new to C++ but I could not seem to find an answer to this question.
If I have a class template <Type> with a constructor taking in object type of ClassA<Type>, and I have another class derived in the following manner:
class ClassB : public ClassA<Animal>, am I able to pass in an object of type classB into ... | That depends entirely whether the constructor takes its argument by reference/pointer. If it does not, the object will be sliced into a ClassA<Type>.
#include <memory>
template <typename Type>
class ClassA {};
class ClassB : public ClassA<Animal> {};
template <typename Type>
class ClassUser1 {
public:
explicit ... |
62,165,120 | 62,166,194 | C++ equivalent blueprint event dispatcher vs blueprint events | I know delegates are the equivalent to dispatchers. But there are so many different types of event declarations. Using the UFUNCTION macro events can be defined using BlueprintNativeEvents and BlueprintImplementableEvent. But then there is DECLARE_EVENT macro. I love to overthink things. can someone explain the differe... | When you use UFUNCTIONs BlueprintNativeEvent and BlueprintImplementableEvent - it means that this function can be overriten by a Blueprint. Then you can launch a blueprint function from c++.
Then - there are several types of delegates:
DECLARE_DELEGATE - C++ only, standard delegate, only one function can bind to it.
DE... |
62,165,331 | 62,165,582 | the object has type qualifiers that are not compatible with the member function. Why is this error showing up? | PVector operator + (const PVector& lhs, const PVector& rhs){
return PVector(lhs.getX() + rhs.getX(), lhs.getY()+ rhs.getY());
}
I get an error on the lhs and rhs object when I use the getX() or getY() function. The function does not make any changes to the object, it only returns a private float value. I am wonder... | This compile error indicated that you try to use a (non-const) member function of a const object.
class A {
void f();
}
const A a;
A.f(); // <- this will result in a cv qualifier compile error.
You can fix this by setting the function to const
class A {
void f() const;
}
It means, that no member variables ... |
62,165,386 | 62,166,757 | How to distinguish between "using declaration" and "using directive" in C++? | How can I distinguish between "using-declaration" and "using directive" in C++? What are the main differences between "using-declaration" and "using directive"? Could somebody make it clear by giving some simple examples? I would be grateful to have some help with this question.
| As description in https://en.cppreference.com/w/cpp/keyword/using
using-directives for namespaces and using-declarations for namespace members
using namespace std; // using-directive
using std::string; // using-declaration
|
62,165,667 | 62,165,799 | C++ While statement not working with string and "or" | I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always ru... | If you do:
while (month != "june" && month != "july");
Or alternatively,
while (!(month == "june" || month == "july"));
Rather than:
while (month != "june" || month != "july");
Your program will be working fine even with multiple logical OR.
|
62,165,932 | 62,166,102 | Assign a value to an rvalue reference returned from function | #include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
return std::forward<Container>(arr)[n];
}
Make a function call :
#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, as... | You said "When function calling finished, the object vector {1, 2, 3, 4, 5} will be destroyed" but that is untrue. The temporary created for the function call is not deleted until the statement ends, i.e. the next line of code. Otherwise imagine how much code would break that passes c_str() of a temporary string.
|
62,166,827 | 62,167,066 | Will structure like std::list<std::pair<string, string>> be copied when returned? | I have a function that is expected to extract a list of key values from a given string, where each key/value pair is represented by a std::pair, the function has the signature like below:
std::list<std::pair<string, string>> extract(const string &s)
If my implementation looks like:
list<pair<...>> kv_pairs;
for (....)... | If you are compiling targeting at least C++11, there are really only two possible outcomes:
Without RVO, the returned temporary will be used to move-construct the object to which the return value is assigned. This is basically just shuffling a few pointers around, and will take exactly the same amount of time (which ... |
62,166,974 | 62,168,956 | Difference between std::fabs(a * b) and std::fabs(a) * std::fabs(b) | I am working on some numerical code and I was looking at the compiler output. One particular case struck me as odd:
In real numbers, it holds that abs(a) * abs(b) = abs(a * b). I would expect the same to hold in floating point numbers. However, the optimization is performed neither by clang nor by g++ and I wonder whet... | I believe I have found a counter example. I post this as a separate answer, because I don't think that this is at all analogous to the case for integers.
In the cases I considered, I missed that it is possible to change the rounding mode for floating point arithmetic. Problematically, GCC seems to to ignore that when h... |
62,167,068 | 62,170,082 | delete triggers exception in "_CRTDECL operator delete" in delete_scalar.cpp | I am writing a WinAPI application in C++.
Situation
I initialize Interface class in wWinMain and store the pointer to it into GWLP_USERDATA like so:
WinMain(...)
{
...
// INITIALIZE CUSTOM INTERFACE
Interface* p_inface{new Interface(hWnd)}; // Create class object
SetWindowLongPtrW(hWnd, GWLP_USERDATA... | The problem isn't the actual Interface object (thanks molbdnilo!), but the order of processed information within one of the base classes.
All my control classes which subclass WinAPI controls are stored in unique_ptrs in objects deeper within the Interface object, so on Interface delete statement the cascading destruct... |
62,167,127 | 62,167,223 | C++ two std::cout, only one outputting | I'm just starting out in C++ programming. Having finished the codecademy course I am trying some projects. I have a program which accepts input for 10 people, and is then supposed to cout the person who consumed the highest number of pancakes and the person who ate the fewest. I've tried:
std::endl; at the end of ever... | You have an infinite do-while-loop in who_ate_least(): If i == 0 you never change i and never make the condition become false.
|
62,167,257 | 62,167,378 | How to simplify many if else statements | I want to simplify this code and want to make it smarter, there are about 80 singleS and multipleS's. I considered State design pattern usage but it seems that it wont be simpler. Can anybody help me with the below lines:
void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
el... | You can use std::map or std::unordered_map like that
std::unordered_map<std::string, std::function<void(void)>> functionsMap = {
{"1", std::bind(&SingleS::runS1, &singleS)},
{"12", std::bind(&MultipleS::runS12, &multipleS)},
...
};
auto it = functionsMap.find(num);
if (it != functionsMap.end())
it->second();... |
62,167,497 | 62,167,730 | copying C-style arrays and structure | C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
But consider following code
#include <iostream>
using namespace std;
struct user {
int a[4];
char c;
};
i... | Your class user gets an implicitly declared copy constructor and implicitly declared copy assignment operator.
The implicitly declared copy assignment operator copies the content from b to a.
Two passages from the standard that seems to apply:
class.copy.ctor
if the member is an array, each element is direct-initiali... |
62,167,817 | 62,169,207 | D3DXCreateTextureFromFile does not create texture | D3DXCreateTextureFromFile does not work for me, i get the D3DXERR_INVALIDDATA error when i use XorString and the D3DERR_INVALIDCALL when i don't.
if (Globals::User::g_pAvatar == nullptr)
{
auto s_avatarFile = Globals::g_sAppdataFolder + "\\avatar.jpg";
auto avatarFile = s_avatarFile.c_str();
if (!fileExist... | The D3DX9 library is very old, and it used the filename extension to determine which codec to use for loading the image. Since you told it jpg it will only try to load it using jpeglib.
The D3DX10 and D3DX11 libraries use Windows Imaging Component (WIC) which relies on a file inspection technique, so it wouldn't care w... |
62,168,028 | 62,181,932 | Retravel Database value according to the username and password Qt C++ | I'm try to re-travel MYSQL database value to the QLine edit. I want to re-travel data according to the username and password. Username and password are in mainwindow.cpp. After login successfully, it's open second window named userdetails.cpp. I want to display data in this userdetails.cpp. This is the code I used in t... | When your application accepts a user (using a login phase), you should save the user id in your application and pass it using a set function member or even as parameter in your ctor of UserDetails. So, when your application displays the user details, you can create a SQL query referring directly the user throw her/him ... |
62,168,217 | 62,168,663 | mp3 file corrupted after downloading it from libcurl | I'm using libcurl to access the IBM Watson API, and I'm downloading an mp3 file, but the downloaded file is corrupted. I was expecting a "hello world" message, but instead, I get either a corrupted mp3 file or the sounds of hell. I guess that the error is coming from when I convert the response to a const char * and it... | The statement
file.write(response, sizeof(response));
contains two errors:
First of all it passes the std::string object as an argument, but write expects a pointer to the bytes to write. You need to pass e.g. response.data().
The second problem (which I also mentioned in the comments) is that sizeof(response) is the... |
62,168,728 | 62,168,862 | Does c++ compiler protect const memory address from any change? | I wanted to prove that there is nothing known as (A protected memory address) and the whole story is just about the compiler, or the OS, or whatever application the hosted app is running on just make some checking on read and write requests the hosted app send to its superior process and this superior app or whatever y... |
This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that [...]
You can break the rules of the language, but then your code is not valid C++. You shall not modify something that is qualified as const. If you do you have undefined behavior. As compilers are made to co... |
62,168,826 | 62,188,351 | C/C++: POSIX compatible way to find default network interface up/down | I'm working on POSIX platform (PSE51 to be exact). I want to get notified when the default network interface goes up/down (via a callback or through continuous poll). The challenge is that I could find a linux specific way to get the default interface here and found a linux specific way to find the network is up or dow... | POSIX does not provide such an interface.
Many POSIXy systems – Linux, BSDs, many Unixes – do provide a C function getifaddrs(), which provides a pointer to a linked list of struct ifaddrs structures. If the list contains an entry whose ->if_name matches your interface name and ->if_addr->sa_family matches your addres... |
62,169,272 | 62,169,564 | What exactly happens when I use the return value of a void function (by casting a function pointer)? | When I run the following program, it always prints "yes". However when I change SOME_CONSTANT to -2 it always prints "no". Why is that? I am using visual studio 2019 compiler with optimizations disabled.
#define SOME_CONSTANT -3
void func() {
static int i = 2;
int j = SOME_CONSTANT;
i += j;
}
void main() ... | What apparently happened is:
mov ecx, cs:i
add ecx, eax
mov eax, ecx ; <- final value of i is stored in eax
mov cs:i, eax ; and then also stored in i itself
Different registers could have been used, it just happened to work this way. There is nothing about the code that forces eax to be chosen. That... |
62,169,592 | 62,169,802 | How to get rid of the arithmetic overflow | This is the code for the Triangle problem in codility that is throwing me an arithmetic overflow error.
int solution(vector<int> &A) {
int i, n;
n=A.size();
sort(A.begin(), A.end());
for(i=0; i<n-2; i++)
{
if((A[i]+A[i+1]>A[i+2])&&(A[i]+A[i+2]>A[i+1])&&(A[i+1]+A[i+2]>A[i]))
{
... | You store A.size() in n and then you loop until i<n and access A[i+2]. In the error cases this is A[A.size()] or even A[A.size()+1]. It's out of bounds. Fix the range of the loop.
The next problem occurs when the sum is larger than INT_MAX. Use the difference instead of the sum to avoid overflow. Remember that the elem... |
62,169,702 | 62,170,484 | Making (virtual) functions made innaccessible in intermediate base class accessible in most-derived class, well-defined? | Consider the following code:
#include <iostream>
struct a {
virtual void f() = 0;
};
struct b: a {
private:
void f() override {
std::cout << "b::f()\n";
}
};
struct c: b {
public:
using a::f;
};
int main() {
::c c;
c.f();
}
This compiles and works as expected with g++, clang and msv... | I believe GCC is wrong to reject the modified code.
[namespace.udecl]
1 Each using-declarator in a using-declaration introduces a set
of declarations into the declarative region in which the
using-declaration appears. The set of declarations introduced by the
using-declarator is found by performing qualified nam... |
62,170,021 | 62,170,103 | Constructors without parameters giving me errors | I have created a class Book that store 3 variables(string title, int pages, float price). I also have created 3 constructor but the null constructor keeps giving me errors.
(58: error: request for member 'pages' in 'b1', which is of non-class type 'Book()')
(61: error: request for member 'Info' in 'b1', which is of non... | Book b1();
This is a declaration of a function called b1 with no parameters and Book return type. Simply change it to
Book b1;
or
Book b1{};
or
auto b1 = Book();
etc.
|
62,170,041 | 62,170,194 | Make template function select type by function parameter | I got some classes like
class A {
public:
void OnStageOne() {}
void OnStageTwo() {}
void OnStageThree() {}
};
class B {
public:
void OnStageOne() {}
void OnStageTwo() {}
void OnStageThree() {}
};
class C {
public:
void OnStageOne() {}
void OnStageTwo() {}
void OnStageThree() {}
};
and I got som... | In c++17:
template <auto F, typename T>
void ForAll(std::vector<T>& vector) {
for (auto& item : vector) {
(item.*F)();
}
}
Usage:
ForAll<&A::OnStageOne>(va);
DEMO
In c++20:
constexpr auto OnStageOne = [] (auto& t) -> decltype(t.OnStageOne()) {
return t.OnStageOne();
};
constexpr auto OnStageTwo = [] (auto&... |
62,170,067 | 62,171,918 | How to free up a resource used by a function in a googletest ASSERT_THROW statement? | In googletest you can use ASSERT_THROW to test that a certain function throws an error. For instance
ASSERT_THROW(PhysicalPropertyResource p("other/identifier72652"), InappropriateResourceException);
How would you explicitely call another method for releasing some memory used by PhysicalPropertyResource? Normally used... | The proper syntax for executing multiple instructions would to wrap them in a block:
ASSERT_THROW({PhysicalPropertyResource p("other/identifier72652");
p.free();},
InappropriateResourceException);
However, this won't help it's not the last line that throws, because then p.free() will not be ... |
62,170,106 | 62,171,306 | Gurobi shadow price of a variable without generating separate constraint | Gurobi 9.0.0 // C++
I am trying to get the shadow price of variables without explicitly generating a constraint for them.
I am generating variables the following way:
GRBModel* milp_model
milp_model->addVar(lb, up, type, 0, name)
Now I would like to get the shadow price (dual) for these variables.
I found this article... | I suppose you are referring to the reduced costs of the variables. You can get them via the variable attribute RC as explained here. And then you need to figure out whether these dual values are corresponding to the upper or lower bound as discussed here.
|
62,170,272 | 62,171,086 | Sublime Text, my file is stored in my home folder when I write a file using fstream on Mac | I'm using Sublime Text 3 on mac to write c++. I wrote some code that gets my cin value for the name and the age and write them in the file file.txt.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string name;
int age;
ofstream file("file.txt", ios::out);
cout<<"enter name: "<<... | That's too weird problem, I'm not 100% fully sure about macOS, but this works on Linux and Windows.
#include <iostream>
#include <fstream>
int main(void) {
std::ofstream file("./file.txt", std::ios::out); // --- here add './' prefix
std::string name;
int age;
std::cout << "Enter your name: ";
std:... |
62,170,304 | 62,170,343 | I overloaded a virtual function, but it didn't work | So far I have done the following work:
class Stamp{
public:
virtual std::string GetStampName() const { return "undefined"; }
};
class FooStamp : public Stamp {
public:
std::string GetStampName() const override { return "foo-stamp"; }
};
I use it like this:
FooStamp fooStamp;
std::cout << "foo-stamp:" << foo... | You’re experiencing object slicing since a FooStamp object doesn’t fit into a Stamp object, and copying it therefore slices off the subclass parts.
Runtime polymorphism requires the use of references or pointers:
Stamp const& stamp = fooStamp;
std::cout << "stamp:" << stamp.GetStampName() << "\n";
Stamp const* pstamp ... |
62,170,968 | 62,171,066 | how to bind stl queue push function to a std::function? | I tried this
{
std::function<void(int)> push;
queue<int> myqueue;
push = std::bind(static_cast<void (queue<int>::*)(int)>(&queue<int>::push), &myqueue,std::placeholders::_1);
push(8);
}
but it is not working
| For queue<int>, push's parameter type is supposed to be const int& or int&&, so you should change the static_cast to match the type.
E.g. from
static_cast<void (queue<int>::*)(int)>(&queue<int>::push)
to
static_cast<void (queue<int>::*)(const int&)>(&queue<int>::push)
LIVE
|
62,171,459 | 62,171,596 | Segmentation fault when try to copy float vector of large size through memcpy | I am trying to copy a float vector into a void* variable through memcpy. If vector size is less than 3000, then below code works fine. But when try to copy vector of size greater than 3000, i got segmentation fault.
void* process(std::string datatype) {
// given datatype will decide the dataype of vec.
const ui... | A vector is just an "envelope" object holding a pointer to dynamically allocated memory that actually stores the elements. So if you take the address of the vector object itself, you are taking the address of the "envelope", but not that of the first element stored. So you are very likely reading beyound the bounds of ... |
62,171,585 | 62,171,893 | What "operator()" means in overloading operators method, used in priority_queue (STL) as comparator in C++? | I've read in a book of c++ algorithms about overloading operators and I have a problem understanding how overloading operator works in that case. This is the sequence of code:
struct cmp {
bool operator () (const int &x, const int &y) const
{
return x % 17 < y % 17;
}
};
int main() {
pri... |
What I don't understand is this line of code:
bool operator () (const int &x, const int &y) const
This line of code declares an operator overload for the operator (). This overload has two arguments, both of which are references to const int. It is declared const, and therefore it can be called through const lvalues... |
62,171,708 | 62,171,871 | Stack pop giving segment fault | The stack which I'm using is not empty and I did a check for that still getting segment fault.
Let s="aaabbaaccd"
string removePair(string s){
stack<char>st;
st.push(s[0]); //Doing this,So that first pop without insert doesn't cause error.
string output="";
for(int i=1;i<s.length();i++){
if... | Here
if(st.top()!=s[i])
st.push(s[i]);
else if(st.top()==s[i] && st.empty()==false){
You check if the stack is empty, but you do that too late. At the point you call st.empty() you already called st.top() twice. You need to check if there is an element before you try to access it. I am not sure about the logic of ... |
62,172,119 | 62,173,602 | how to import the pywt library which is a python library in dev c ++? | I'm trying to run this code which was picked up by someone I can't reach anymore,
the code calculates the dwt2 and idwt2 of a square matrix
#include <iostream>
#include <pywt>
#include <numpy>
using namespace std;
int main() {
int Matrix=numpy.array([[1.0,2.0,3.0,4.0,],[5.0,6.0,7.0,8.0,],[9.0,10.0,11.0,12.0,],[13.0,1... | I saw that you are using MinGW64, therefore I think you are using CodeBlocks IDE. To add a library in CodeBlocks, go to Settings->Compiler->Global compiler settings-> Search Directories-> and add the include directory from the downloaded folder. Then, do to Linker settings and then add the libraries you need.
You can... |
62,172,222 | 62,185,344 | how to load library in cppyy? | I am trying cppyy in python to import C++ files. I want to load HSMdApi.h and HSMdApi.lib. Here is the dir structure
Here is the code
import cppyy
cppyy.include('include/HSMdApi.h')
cppyy.load_library('win64/HSMdApi.lib')
I load the header file succefully. But when I load the lib, I got an error
Error in <TWinNTSys... | The library to load is the (dynamic) .dll, never the (static) .lib library. You do not need to specify the extension as it is added if not provided. Is the python executable used also 64 (the build is printed in the welcome message when starting python interactively)? The bdist_wheel warning can be ignored (wheels are ... |
62,173,013 | 62,211,511 | GDI+ Text Flickering and Now with Black background | I'm working on a windows desktop application and I noticed to my dismay that my text was flickering so upon searching I found two methods - return true for erasebkgnd and double buffering. The first method didn't do anything and the second made my background all black for some reason and it still flickers.
Below is whe... |
my background all black
This issue is due to not filling the your background. You can fill your background before draw the image like this:
RECT rc;
GetClientRect(hWnd, &rc);
FillRect(screen, &rc, GetSysColorBrush(COLOR_WINDOW));
flickering
This issue is due to not using BeginBufferedPaint ... |
62,173,863 | 62,175,694 | -Ofast produces incorrect code while using long double | #include <cstdio>
int main(void)
{
int val = 500;
printf("%d\n", (int)((long double)val / 500));
printf("%d\n", (int)((long double)500 / 500));
}
Obviously it should output 1 1. But if you compile it with -Ofast, it will output 0 1, why?
And if you change 500 to other values (such as 400) and compile with... | With -Ofast, -ffast-math is enabled, which can cause some operations to be calculated in a different and faster way. In your case, (long double)val / 500) can be calculated as (long double)val * (1.0L / 500)). This can be seen in the generated assembly when you compare -O2 and -Ofast for the following function:
long do... |
62,174,083 | 62,174,380 | Is there a sequence container with external allocation of elements (in the STL)? | I would like to use a sequence container type like std::forward_list but with external allocation of the contained elements. This requirement is in order to gain more control over the allocation.
Such elements would probably have to use a class template which contains the necessary members for linking the (list) elemen... | Considering that you want fine-grained control over the list elements, to the level how they are joined, Boost.Intrusive could be an option.
Boost.Intrusive provides an intrusive slist class: https://www.boost.org/doc/libs/1_73_0/doc/html/intrusive/slist.html
|
62,174,199 | 62,472,275 | Python os.system() returning bad value | Background: I'm using a Python script with os.system() to repeatedly call a command line program to run test cases. The program being tested returns zero for normal operation and a negative value for error conditions. I compare this value against what is expected (not always zero) as part of determining pass/fail.
The... | So the short answer is that the value I'm getting is the exit code from the program, unless Windows feels it has something important to say.
In this case a DLL I was calling was corrupting the heap and cause windows to abort the execution. To get the actual 32 bit Windows return code and not a sign extended version I ... |
62,174,313 | 62,174,564 | Info lost between classes | For one of my programming classes in c++, we are required to design a matchmaking agency and somehow after I create a new client it will add it in the operator's += to clients array, then in MENU class the database lost the client and I can't seem to find the reason.
ADDING A CLIENT OPERATOR
MatchmakingAgency& Matchm... | You've copied the client pointers over to newArr, adding in the new one, then after setting m_clients to the newArr pointer you delete everything you just copied by deleting the newArr pointer.
delete[] m_clients;
m_clients = newArr;
delete[] newArr;
|
62,174,381 | 62,175,275 | What cpp file types can I delete/exclude when packaging into an install bundle? | I want to package my executable file and other needed files into an install file (using NSIS) so that other people can install and use. There are a few file types I am uncertain of whether they are needed for installation or if it is safe to delete them.
Here is a random example of the files in the project folder as w... | You generally only need the .exe. Your app might depend on custom .dlls or the C++ run-time library in which case you would bundle the custom .dlls and/or the C++ redistributable.
Your screen shots are of a debug build and you normally want to distribute a release build instead because it is often smaller and contains... |
62,174,478 | 62,174,872 | Why does string_view::operator== accepts parameters by value | I was reading source code of string_view, and found that operator== accepts parameters by value.
template<typename _CharT, typename _Traits>
constexpr bool
operator==(basic_string_view<_CharT, _Traits> __x,
basic_string_view<_CharT, _Traits> __y) noexcept
{ return __x.size() == __y.size() && ... |
Why does string_view::operator== accepts parameters by value
Because that is the recommended way to pass arguments that are not modified, and are cheap to copy.
There is no need to pay the cost of indirection introduced by the reference - that said, the function would in most cases be expanded inline in which case it... |
62,174,578 | 62,174,904 | Understanding base addresses in VirtualAlloc | In my application I'm trying to allocate a large block of memory (approximately 1GB-2GB) through VirtualAlloc on startup that I can then later divide up for use throughout the rest of the application. When in debug mode I want to pass a base address in the VirtualAlloc call to keep pointer addresses consistent for eas... | The linked article is for 32-bit mode. In 64-bit mode reserved addresses start from 128 TB. Here's what MSDN says about it:
For a 32-bit process, the virtual address space is usually the 2-gigabyte range 0x00000000 through 0x7FFFFFFF. For a 64-bit process on 64-bit Windows, virtual address space is the 128-terabyte ra... |
62,174,944 | 62,193,039 | std::cin inside a infinite while loop in C++ | This doesn't work as i intended it. Please point me what i am doing wrong here.
The program is supposed to follow the steps below. But instead, it loops infinitely without waiting for inputs (except for the first time through the loop).
it prompts me and wait for inputs (integers).
it reads 4 integer inputs to an empt... | Ok. i found a way to work around this while having a sensible and fair mind about what i've been doing wrong in my code.
First of all the everything i am saying from here to below are coming from a person so new to C++ and to programming in general. And my English skill is barely sufficient to survive the day.
Everyone... |
62,175,144 | 62,176,086 | UE4 Failed to find animation class during project packaging | In the player class constructor, I use ConstructorHelpers::FObjectFinder to get a link to blueprint animation class:
static ConstructorHelpers::FObjectFinder<UAnimBlueprint> finderAnim(TEXT("AnimBlueprint'/Game/MixamoAnimPack/Mixamo_Adam/Anims/MixamoAnimBP_Adam.MixamoAnimBP_Adam'"));
Then I call SetAnimClass() method:... | Here is a similar question on Unreal Engine's Forum.
This is the proposed solution:
Adding "_C" at the end of filename and treating the file as a "UClass"
makes things run smoother. Now it runs properly on both editor and
packaged game.
So your initialization of finderAnim will look like:
static ConstructorHelper... |
62,175,837 | 62,180,837 | Linphone Desktop on windows 10 | When I build the latest update of linphone-desktop project on windows 10,
It builds in the VS2017 without any issues, but after that i get the error message:
unable to start program. build\RelWithDebInfo\ALL_BUILD the system can not find the file specified.
and when I open the exe in output\bin myself, I get an error:
... | I was unable to rebuild the project after updating to latest commit.
Updated QT from 5.9.8 to 5.12.1
Reset all the path environment variables after the QT update
Reinstalled the latest perl
Rebuilt the project step by step (I tried Release mode) and finally, it works :)
|
62,175,997 | 62,178,791 | thread racing when working with vector of data in the thread function | Being an early stage c++/thread coder I am having some hard time with thread racing in one of my test functions and would truly appreciate some feedback.
My parent() function takes in as input a rather large vector of images (cv::Mat from openCV) and the task is to compute an operator on each one separately (e.g. dilat... | Where you thinking something like this?
This processes them all individually, but you can chunk it up however you want and return a vector from the lamda if you want.
Note: This is in C++11, since that is what you tagged. If you have access to 17, this becomes a whole lot simpler.
#include <vector>
#include <algorit... |
62,176,244 | 62,176,433 | How do I sort rest of the elements that I insert in a list by keeping the first insertion remain in its position? | Suppose I'm trying to insert random stuff on a list in CPP using include list,
list <string> newList;
list<string>::iterator z = newList.begin();
//James(Remains static, rest sorted) -> Abraham-> Brian-> Chuck-> David-> Rick-> Morty
newList.insert(z,James);
newList.insert(z,David);
newList.insert(z, Rick);
newList.in... | Here's a potential solution, by first removing the first entry, then sorting.
auto front = newList.front();
newList.pop_front();
newList.sort();
newList.push_front(front);
This will make the entire list sorted, but whatever was at the beginning (James in your example) will be re-added to the front of the list.
|
62,176,495 | 62,196,968 | Why is an alias declaration not a valid init-statement (/simple-declaration)? | Typedef declarations can, whereas alias declarations cannot, be used as initialization statements?
The grammar for an init-statement is, for C++17, as follows:
init-statement:
expression-statement
simple-declaration
expression-statement:
expression_opt;
simple-declaration:
decl-specifier-seq init-declarator-li... |
Is it indeed a fact that a typedef declaration is a valid init-statement/simple-declaration whereas an alias declaration is not
Yes, a typedef declaration is a valid init-statement, whereas an alias declaration is not.
Is this an intended "deviation" as of C++17 w.r.t. the previous (near-?)identical semantics of the... |
62,176,770 | 62,176,892 | Why is char not a single character? | In Microsoft's documentation for DEV_BROADCAST_DEVICEINTERFACE_A the type of dbcc_name is defined as follows:
char dbcc_name[1];
But as shown in this StackOverflow question it turns out to be a string with multiple characters.
Isn't a char a 16 bit value single character? How does this work?
(I had originally thought... |
Isn't a char a 16 bit value?
On what platform? On most platforms (including all that run Windows, AFAIK), char is 8 bits.
How does this work?
The type documentation explains this:
dbcc_size
The size of this structure, in bytes. This is the size of the members plus the actual length of the dbcc_name string (the nul... |
62,177,109 | 62,178,907 | Embeding Xterm into Qt5 application in c++ | Sorry if it is duplicate but i can't find anything usefull to me regarding Qt5. Is there any way to embed Xterm into Qt application using c++? I did it with python, but there is problem with resizing xterm on (at least with PyQt5) widget's container resize, in other words xterm doesn't resize, which is not acceptable.
... | The problem is that xterm does not have the "-embed" command (I don't know if it did) but you must use the "-into" command as the docs point out.
On the other hand, it is not necessary to access the tabwidget or create a QProcess pointer unnecessarily.
Considering the above then the solution is:
#ifndef TERMINAL_H
#def... |
62,177,129 | 62,177,157 | C++: call cosntructor of base class in a derived class without a constructor | I want to make a simple wrapper B around a complex class A. A has many different constructors. The class B does not have any constructors, so how can I automatically pass the constructor arguments to the base class A, without needing to implement them all in B?
Here is a simple example of what I want to do:
class A
{
p... | In B, you can inherit A's constructors:
class B : public A
{
using A::A;
int b;
};
Then B b(0); will work.
|
62,177,254 | 62,178,868 | Moving a file from a React.JS frontend to a C++ backend | So I have a function written in C++, that works on a file. I can convert it to a script and the script to take a parameter of the file location for example and work on it, that is not a problem.
My frontend is done with React, it is still not connected to the backend. I have a button that is "Upload File" the user clic... | Problem
Have the user load a file -> have the C++ function run on that file -> return output to the user.
Possible Solution with REST-API
As you stated in your question you could upload to google drive and then wget the file, however its a bit too complex for nothing. What you could do instead is skip the uploading to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.