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 |
|---|---|---|---|---|
61,606,347 | 61,606,495 | Makefile with an Implementation and Header Files | Every question I've seen on here is dealing with much more complicated use cases than I am.
I'm in a first year programming course and just can't understand what I am doing incorrectly. When running make I just get a Circles is up to date message.
I have three files:
main.cpp => entry point for the program
CircleDrive... | I usually do something like this for my Makefile:
%.o: %.cpp
g++ -c -o $@ $< -std=c++11 -Wall
Circles: main.o CircleDriver.o
g++ -o $@ $^ -std=c++11 -Wall
clean:
rm *.o *~
This will create object files for each .cpp file and then use the object files to make Circles.
|
61,606,464 | 61,606,506 | How do I get BMI correct? | Having an issue with my calculation to determine BMI. Please advise me where I am going wrong as the answer always returns as -nan(ind). I'm sure that the problem lies with the calculation itself as I have removed the displayFitnessResults function and simplified the code but I still get the error.
#include<iostream>
#... | Your getData() function takes its parameters by value, so any modifications it makes to them are not reflected back to the variables in main(), thus they are still 0.0 when passed to calcBMI().
You need to pass the parameters by reference instead:
void getData(float &weightP, float &heightP)
|
61,606,690 | 61,606,798 | Is there a way to create a central program that can handle the different RGB components of my computer? | I'm still young but I've been learning software development for about 5 years now and I wanted to write a program that was actually useful to me. I wanted to create a program (preferably in c++ but I would be willing to learn something else if I needed to) that could change the colors of all the RGB components of my co... | Maybe they need special access, maybe don't. I don't think there are any, but check if your company released open-source drivers. Keep in your mind that reverse engineering is usually license violation, and you should definitely not give the final program to anyone. For reverse engineering: first check that they are na... |
61,606,841 | 63,554,479 | Using a boost::numeric::odeint stepper inside a complicated class | I have an extremely convoluted system of numerical rate equations, which are to be solved by the class ElectronSolver. The electron state is handled by a separate class state_type, not shown here.
A simplified template of the problem class appears as
ElectronSolver.h
class ElectronSolver {
public:
ElectronSolver(co... | Whether or not you want to continue using boost is a decision only you can make, but it's easy to create a wrapper with no performance hit.
You'll want to wrap sys in a lambda that captures this. This should not have a performance hit, as the lambda will be inlined when optimizations are turned on.
You would call it li... |
61,607,044 | 61,608,579 | Memory allocation and constructor | I am sorry if it has been asked before explicitly stated in the standard, but I fail to find whether the memory for objects with automatic storage is allocated in the beginning of enclosing block or immediately before executing the constructor?
I am asking this because https://en.cppreference.com/w/cpp/language/storage... | First of all, from a language standard perspective, you cannot access the object's storage outside of the lifetime of the object. Before the object is created, you do not know where the object is located, and after it has been destructed, accessing the storage yields undefined behavior. In short: A conforming C++ progr... |
61,607,092 | 61,607,168 | Are static member variables of templates defined or specialized? | This relates to the following question: constexpr differences between GCC and clang
In the following spinet, is the last line a specialization, a definition, or both?
template<typename T>
struct A {
static const T s;
};
template<typename T>
const T A<T>::s = T(1);
This seems like a definition to me, but the posted ... | It's definition.
The following would be a specialization.
template <>
const int A<int>::s = 20;
Given the following program,
#include <iostream>
template<typename T>
struct A {
static const T s;
};
template <typename T>
const T A<T>::s = T(1);
template <>
const int A<int>::s = 20;
int main()
{
double a = A<do... |
61,607,150 | 61,608,847 | Sum of last N nodes in a binary search tree | I want to write a function that obtains a number N and a binary search tree, then the function needs to sum the value of the last N nodes of the tree. from higher to lower value of the nodes. I cant use auxiliar functions or static variable.
For example, if the function obtains that binary search tree and the value of... | You can simply visit the tree in reverse order, that means starting from root and do three things:
visit right branch
visit self node, and accumulate sum if needed
visit left branch
And stop iterating when k items are accumulated.
#include <iostream>
struct Node {
int value;
Node* left = nullptr;
N... |
61,607,487 | 61,609,414 | Architecture pattern: function to handle 2 identical implementations | I have the following problem which I guess I am solving incorrectly given the problem I am facing:
I have an interface I and implementations A, B, C... I want to somehow express that I can get some results from couples (f(A, A), f(B, B), f(C, C)) and so on. In other words, I want to interface I to express that 2 identi... | Your interface is indeed strange, asking for method which should not be implemented.
We don't have multiple dynamic dispatch, except with std::visit of std::variant.
So following might help:
using V = std::variant<A, B, C>;
int f(const V& v1, const V& v2) {
struct {
template <typename T1, typename T2>
... |
61,607,722 | 61,607,854 | No match operators[] | Heyy Everybody.
Please have a look at my code my getting some errors that I cannot able to resolve by my self.
DP_Wine_problem.cpp:42:17: error: no match for 'operator[]' (operand types are 'std::__cxx11::list' and 'long long int')
if(v[x]>v[s])
^
DP_Wine_problem.cpp:42:22: error: no match for 'operator[]' (operand t... | Error messages like no match for mean, that either the method or operator isn't there at all, or there is such a method, but with different parameter types.
Looking at std::list, you can see, that this is the first case, no operator[] for std::list can be found.
Just in case, v[1] is not the first element in the list,... |
61,607,741 | 61,607,894 | JSON using nlohmann::json jpointer for dynamic string and default value | In nlohmann::json library if a key is not found there is a provision to return the default value like this
j.value("/Parent/child"_json_pointer, 100);
here 100 will be returned if "/Parent/child" is not found
But if the "/Parent/child" is dynamic like an array for example
eg. /Parent/child/array/0/key
/Parent... | First of all, you can just use ::value with a json_pointer.
Second, you can use the / operator to construct new json_pointers.
Thus, your main function can do the following:
json j = nlohmann::json::parse(name);
auto root = "/GNBDUFunction/gnbLoggingConfig"_json_pointer;
size_t count = j.at(root).size();
for (size_t i... |
61,607,841 | 61,607,911 | How to find a sequence of letter in a given string? | My string is "AAABBAABABB",
and I want to get the result as
A = 3
B = 2
A = 2
B = 1
A = 1
B = 2
I have tried to use
for (int i = 0; i < n - 1; i++) {
if (msg[i] == msg[i + 1]) {
if(msg[i]==A)
a++;
else
b++;
}
}
I tried this by it didn't work for me. And I don't unders... | Iterate through the array by followings:
If i = 0, we can set a variable as 0th character and counter by 1.
If ith character is equal to the previous character, we can increase the counter.
If ith character is not equal to the (i-1)th character we can print the character, counter and start counting the new character... |
61,608,010 | 61,620,981 | Pytorch C++ (libtorch) outputs different results if I change shape | So I'm learning Neural networks right now and I noticed something really really strange in my network.
I have an input layer created like this
convN1 = register_module("convN1", torch::nn::Conv2d(torch::nn::Conv2dOptions(4, 256, 3).padding(1)));
and an output layer that is a tanh function.
So it's expecting a torch::T... | THANK YOU @MichaelJungo turns out you were right in that one of my BatchNorm2d wasn't being set to eval mode. I was unclear how registering modules worked in the beginning (still am to an extent) so I overloaded the ::train() function to manually set all my modules to the necessary mode.
In it I forgot to set one of my... |
61,608,431 | 61,726,016 | Virtual keyboard top black screen in Yocto | I am developing a device using VAR-SOM-MX7 developing in Yocto Sumo.
I managed to add virtual keyboard into my QApplication but when the keyboard appeared, it overlaps the application.
The textEdit field still getting the input from the virtual keyboard but just cannot show the textEdit field while typing.
I have tried... | After long try, I finally found a solution to solve this issue.
The virtual keyboard was created using another QQuickWindow and this window overlap my QWidget application window.
I just have to find the vk window, and use the QWindow setMask function to mask of the black region.
Hope this can help others too since I co... |
61,608,568 | 61,608,800 | Is this example working with virtual inheritance in C++? | Could I do this?
class A {
public:
virtual void aFoo() = 0;
};
class B : virtual public A {
public:
virtual void aFoo() { ... }
};
class D : public A {};
class C : public B, virtual public D {};
The issue is with the implementation of aFoo() in B and the lack of it in C. When it comes to compiling I see this e... | You need virtual inheritance in this way:
struct A {
virtual int f() = 0;
};
struct B : virtual A {
int f() { return 1; }
};
struct C : virtual A {};
struct D : B, C {};
int main() {
D d;
return d.f();
}
In the dupe I commented you can see this relation
A
/ \
B C
\ /
D
for virtual in... |
61,609,369 | 61,609,587 | why do we really require static function in factory design pattern? | we can do the same with normal member function in factor class and can access with factory pointer variable? can some one please tell the difference.
enum shapeType
{
CIRCLE_TYPE,
RECTANGLE_TYPE,
SQUARE_TYPE
};
class Shape
{
public:
virtual void draw()=0;
virtual ~Shape(){
}
};
class Rect... | Static method is not a requirement, but as long as you don't use non-static members of the class, method can be static.
|
61,609,579 | 61,609,700 | dynamically create vector<class A> inside constructor of class B, when class A allocates memory when constructed | I am an embedded developer. And now I am part of a project which uses c++, since our µC didn't support c++ my c++ became a little rusty. I hope some of you can help me.
I want to symulate a SPI-bus-connection with dynamic datalength and number of Slaves.
Since this code tests some µC Code written in plain old C, it's n... | If you use C++ use the standard containers this way you will not have to worry about freeing the memory. You can always access to the data allocated by the container if you want to retrieve raw array pointer.
Some sample modification of your code
class LSPI_BusSymulation{
...
private:
// must use normal arrays
... |
61,609,680 | 61,611,112 | How to return one out of multiple values from a single C++ return statement? | return a or b or c or d;
That statement returns either true or false in C++, and I know the reason for this.
But I need a workaround so that I can return the first non-zero value via that return statement (or something similar) like it happens in Python.
I am not looking for conditional statements as it looks untidy s... | I would write the function like this:
int fun(int a, int b, int c, int d) {
if (a) return a;
else if (b) return b;
else if (c) return c;
return d;
}
It is clean and short. I could stop here, but lets explore what can be done...
There exists an algorithm that already almost does what you want. A slight ... |
61,609,983 | 61,610,019 | Error "subscript of pointer to function type 'int *(int)'" | I am writing a code to find a cluster, I am using "cern root" to plot graphs,
the data is saved in ".root" file, but the code is written in c++. The data is saved as a 2D histogram. The logic of the code is once I find a bin with some signal in it, I find the neighbours around it (8 bins), then I tag the bin and increa... | Maybe question should be closed as typo, but a function gets called like this:
int* neighbour_i = neighbour_function_i(i);
Not like this:
int* neighbour_i = neighbour_function_i[i];
|
61,610,761 | 61,613,863 | Is std::hardware_constructive_interference_size ever useful? | Existing questions in this area that still don't ask specifically my question:
Understanding std::hardware_destructive_interference_size and std::hardware_constructive_interference_size
Correct way to ensure sharing with std::hardware_constructive_interference_size
The answer to second one actually makes me ask this ... | Consider a std::deque<T>. It's often implemented using chunks of a given size. But how many T's do you store per chunk? A reasonable answer is std::hardware_constructive_interference_size/sizeof(T), if sizeof(T) is small.
Similarly, a string class with the Small String Optimization may aim for a size of std::hardware_c... |
61,611,266 | 61,611,694 | HUP Signal on a process reading from cin | I have an executable that reads input from std::cin in a loop always, I have a SIGHUP handler as well.
#include <iostream>
#include <signal.h>
void hupHandler(int)
{
std::cout << "Handled sighup" << std::endl;
}
int main(int, char*[])
{
struct sigaction sigHupHandler{};
sigHupHandler.sa_handler = hupHand... | You cannot just do anything you want in a signal handler. A signal handler can interrupt a program at any time. Including when it's in a middle of doing something inside a C++ library function or a class, and none of the C++ library functions, templates, et al, are reentrant, like that. You, pretty much, cannot use any... |
61,611,478 | 61,742,173 | Qt detecting Unicode command line arguments as question marks | Sometimes when I build a Qt C++ app (MinGW, Qt 5.7.0) and open it with arguments in Windows 10, it detects Unicode arguments as question marks. I don't really know when but I think it depends on parameter's length and being or not being whitespaces in parameter.
For example:
>app.exe سلام
receives: سلام
>app.exe سلامم... | It's a problem in MinGW compiler's globbing process. According to QTBUG-84002 and MinGW Tips, it can be solved by adding this code above main() function:
extern int _CRT_glob = 0; /* 0 turns off globbing; 1 turns it on */
|
61,611,610 | 61,611,724 | pass address of an object to another object C++ | int main(){
Test obj1(a,b,c);
Test obj2(d,e,f);
&obj1=&obj2;//This line wont work saying lvalue required on left side
}
What can i do to counter this error? I want to store address of obj2 into obj1 so their member variables become same(a=d,b=e,c=f) and when i change a member variable of obj1, it changes in ... | What you are doing is like 42 = 64. It makes no sense. If you want to store the address of an object, you can use a pointer object:
Test obj1;
Test obj2;
Test * pobj = &obj1; // pointing to obj1
pobj = &obj2; // pointing to obj2
You could also use a reference to accomplish something similar, but since you mentioned y... |
61,611,675 | 61,612,217 | OpenGL camera target issue | I'm implementing a 3D maze game in C++, using OpenGL where the camera is at a fixed position exactly above the middle of the maze looking at the middle too. It works and looks just as I've wanted but the my code is not so nice because I needed to put a + 0.01f into the position to work well. If I miss it out, the labir... |
I know that by convention, in OpenGL the camera points towards the negative z-axis
In viewspace the z-axis points out of the viewport, but that is completely irrelevant. You define the view matrix, the position and the orientation of the camera. The camera position is the first argument of glm::lookAt. The camera lo... |
61,611,762 | 61,612,355 | C++ map of std::function objects throws 'failed to specialize function template' error | I'm having hard time solving this issue related to my C++ school project. Basically, I need a map where the key is given GUID and the value is a member function of MyClass, which is a factory method for instances of derived classes of BaseClass, returned as a BaseClass pointer. The code would look like this:
class MyCl... | You forgot the first placeholders:
map[classGuid] = std::bind<BaseClass*>(&MyClass::createInstance<DerivedClassX>, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
You could also use a lambda:
map[classGuid] = [this](ClassX* classX, ClassY* classY, const GUID* guid) {
... |
61,612,204 | 61,612,482 | Alternative of std::find that works faster | I have code that finds the new words in a container and adds them to the class private variable dict. The function Learner::Learn needs to be optimized so that it runs faster. The elements in the dict vector could repeat each other, but 'newWords' should always return the count of the new (non-repeated) words.
#include... | If you always keep words sorted you could use a binary search for a total runtime of O(n log n), but you have to shift the entire vector to insert things in the middle. (which will bring it back to O(n^2))
You should switch to another container for a significant improvement though:
std::set (O(log n) lookup, O(log n) ... |
61,612,255 | 61,612,566 | Implementing Multi threading with Polymorphic Classes | I am trying to implement a Logic system for my game which takes dt as its parameter
So far I have done this
#include <iostream>
#include <thread>
#include <chrono>
#include <memory>
class Player {
private:
float x, y;
public:
Player(float initX, float initY)
: x(initX), y(initY) {}
void Logic(f... |
The problem is that the value of dt is not being updated in the Logic Thread.
That's ambiguous - are you expecting it to be updated by the Logic thread?
If so - it can't be: void Logic(float dt) takes dt by value - it can't update dt. Note that the by-reference capture in the lambda just means the Logic function c... |
61,612,291 | 61,612,500 | I know C++ basics, can I find any small jobs? | I learned C++ basics such as syntax, data structures, and OOP. What should I learn next to be able to find small jobs as a college student and where?
|
Join open-source project. Checkout code, analyze it, learn, and once you will be more confident with your skills you can prepare your own features/fixes. Results of your pull requests will be your skills "score". The main advantage of it is seeing large-scale code, without going through job interview.
You can offer yo... |
61,612,452 | 61,614,038 | Is there a clang++/libc++ equivalent to the __gnu_cxx::__freeres hook? | Does anyone know if clang++/libc++ has an equivalent to __gnu_cxx::__freeres?
(this is a hook that allows tools to trigger deallocation of resources such as memory allocated for exception handling to be used in case malloc fails, see here).
| Not that I know of.
The exception pool (in libc++abi, not libc++) is not on the heap, anyway.
|
61,612,614 | 61,634,730 | How to convert a BVH node object into a simple array? | I am working on an Opengl ray-tracer, which is capable of loading obj files and ray-trace it. My application loads the obj file with assimp and then sends all of the triangle faces (the vertices and the indices) to the fragment shader by using shader storage objects. The basic structure is about to render the results t... | One way to lay out binary tree nodes in an array is: for all nodes in the tree, if a given node has array index i, its children are at indices 2i + 1 and 2i + 2 (described more fully here).
Assuming you have a complete tree, you can write your tree to an array with a simple breadth-first traversal:
In pseudo-code:
int... |
61,612,621 | 61,612,663 | (C++) multiplication wont give off expected results | hello :) so this is my first time writing a c++ program, im currently using code::blocks tho im pretty sure the issue ive got probably isnt related to the program at all but anyway...
i want to write a simple code, where two "boxes" are created and their volume is calculated and printed on the terminal. ive written thi... | Your constructor assigns values to the passed arguments.
Try this instead:
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length=l;
breadth=b;
height=h;
}
};
As others have mentioned, there are other improvements that can... |
61,612,921 | 61,613,218 | How do you read from a ifstream asynchronously in C++? | The ifstream is reading from a UNIX pipe, currently the communication is done by sending a signal to the reading application, but I would like to get rid of the signals and use proper async io.
In C I would use the select() function with a timeout, so I could react immediately when there is something to read, and waith... | std::ifstream does not support asynchronous operations, it is designed for synchronous IO. You could build async IO around it using additional threads and IO queue, but in general this is not a good idea for efficiency reasons.
For asynchronous IO you might want to look at Boost.ASIO, in particular its stream_descripto... |
61,613,301 | 61,614,741 | NetBeans configurations | I need help configuring my NetBeans to use C++. I'm now using it on Linux and the construction fails every time, no matter what the project, so I'm assuming it must have something to do with the compilers and makers installed.
Is there something I can change here?
| In NetBeans select Tools -> Plugins -> Settings tab -> Configuration of Update Centers and install the latest version of the NetBeans Plugin Portal. The latest version of the NetBeans Plugin Portal is compatible with one of the later versions of g++ 8, 9 or 10 in your distribution's default repositories.
Install the ... |
61,614,448 | 61,644,612 | error: no match for ‘operator==’, but indeed defined on base class | struct BaseA {
auto operator==(const BaseA& other) const {return other.a == a;}
int a;
};
struct B {
int b;
};
struct A: public BaseA {
auto operator==(const B& other) const {return other.b == a;}
};
int main() {
A a{10};
a == a;
return 0;
}
It won't compile:
error: no match for ‘operat... | I found a fix, without writing out using for each comparison operator I add in the child class:
Make the operator non-member and pull it out to the enclosing scope of A (in this example the global scope):
auto operator==(const A&, const B&)
If you want to access private members of A or the protected of its base class,... |
61,614,594 | 61,614,672 | How can I check if a type is a specialization of std::bitset? | I'm struggling to check at compile time if type is std::bitset or not.
I would like to to something like:
is_bitset<std::bitset<2>>::value; // should evaluate to true
is_bitset<int>::value; // should evaluate to false
I think this SO post is pointing in the right direction, but for some reason I can't manage to make i... | The solution is very similar to the answer in the link you posted:
template<typename T>
struct is_bitset : std::false_type {};
template<std::size_t N>
struct is_bitset<std::bitset<N>> : std::true_type {};
static_assert(is_bitset<std::bitset<2>>::value); // should evaluate to true
static_assert(!is_bitset<int>::value)... |
61,614,703 | 61,615,536 | Assign value to a pointer array give me error while using pointer arithmetic | When I do this pointer arithmetic , it always give me an error
int main()
{
const int rowSize=40;
int* unique=nullptr;
int arr[rowSize]={1,1,11,31,21,22,2,2,3,32,31,3,4,34,45,5,55,5,55,5,6,46,64,6,7,27,74,7,7,7,7,11,11,11,11,11,1,2,13,4};
int amount=0;
for (int count=0; count<rowSize; count++)
... | Changing the value of a pointer returned by the new[] operator is extremely dangerous, and never really the right way to go about coding. This is because, at some point, you will need to release that memory with a delete[] 'call' to the address that new[] gave you.
In your case, the module that calls your uniqueArr fun... |
61,614,738 | 61,617,482 | When __strlen_chk called? | as part of my project, I try to write a feature inside android art, and for some reason I get exception on
__strlen_chk
my trace is:
DEBUG : Revision: '0'
DEBUG : ABI: 'arm'
DEBUG : pid: 969, tid: 1346, name: PackageManager >>> system_server <<<
DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0... | __strlen_chk uses a double underscore, which indicates an internal part of the library. From the context, it's clear that it's called from std::string::string(const char* src).
Now that's a constructor which takes a null-terminated string as an input. But nullptr is not null-terminated. In fact, it doesn't point to an... |
61,615,298 | 61,616,024 | TwinCAT : Getting a file (FB_FileGets) | I am developing a code to get a text file in twincat. I am using the block functions:
FB_FileOpen
FB_FileGets
FB_FileClose
I build on the example on the website https://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_fileio_example.htm&id=5958930695166849062
When the program r... | You're forgetting to call the function blocks. As it is right now, you're only supplying the input-parameters to the different Beckhoff function blocks, but not actually executing them (just as you execute tRisingEdge, which is also a function block).
So do (in the correct places, or all at the end):
fbFileOpen();
fbFi... |
61,615,386 | 61,616,615 | Can copy/move constructors be inherited by using-declaration in c++17? | struct B {
B(int) {}
B(B const&) {}
};
struct D: B {
using B::B;
};
int main(void) {
B b(5);
D d(b); // error
return 0;
}
c++14 explicitly excludes copy/move constructors from inherited constructors in 12.9 [class.inhctor]/p3.
For each non-template constructor in the candidate set of inherited
constru... | The new wording is in [over.match.funcs]/8:
A constructor inherited from class type C ([class.inhctor.init]) that has a first parameter of type “reference to cv1 P” (including such a constructor instantiated from a template) is excluded from the set of candidate functions when constructing an object of type cv2 D if t... |
61,615,450 | 61,629,207 | how to write a cp function (in linux shell ) in c++ that runs in background? | I am trying to write a my own small linux shell , and i want to write the function cp , the function format is like the following :
cp <old-file-path> <new-file-path>
It copies the first file into the second file (overwriting it) , and if the second file doesn't exist it will create a new one.
If the files didn't open... | For starters, I rewrote your code a bit.
In particular, note that the child branch (PID == 0) exits when it is done.
The parent closes the passed-down file descriptors after forking and in case of error.
if (this->num_args == 2) {
int fd1 = open(args[1], O_RDONLY);
if (fd1 == -1) {
perror("open failed")... |
61,615,596 | 61,615,775 | Passing QWidget* as function parameter doesn't behave as expected | I want to pass QWidget pointer to a function to get some widget back as a result of function actions. But the value of this pointer leaves the same as befoere.
Next code
#include <QApplication>
#include <QWidget>
#include <QDebug>
class Test
{
public:
QWidget *_widget;
Test()
{
_widget = new QWidg... | You pass the pointer as copy, which means the outside pointer is not modified by the inside assignment. Instead you have to pass a pointer or a reference to your QWidget*.
|
61,615,812 | 61,617,032 | Problem viewing application changes using update() function | I'm starting to learn programming with qt and to become familiar with the library I'm making easy little programs. One of these plans to create QLabels, which should be added to the app each time a button is pressed, but I don't understand why they don't appear. Here is the code:
file .h:
class Base : public QWidget
{
... | Something must be missing in OPs code.
Additionally, the call of Vlayout->update() isn't necessary in my opinion.
I made an MCVE to demonstrate:
testQWidgetAdd.cc:
// Qt header:
#include <QtWidgets>
// main application
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(... |
61,616,139 | 61,632,516 | Linking to visual studio dynamic library | I am trying to create a dynamic library and use it in a console application. The library is Multisite.lib.
My problem is that when I add the project as a reference and add the header files directory it works well, however, when I try to use this library in an independent project I get the unresolved external symbol err... | The problem was using a 64-bit library on a 32-bit application.
That's why it was working fine when I added it to the same solution but not in my independent project.
I used to think that visual studio can detect a wrong format but turns out that just the exported symbol's names change between two same libraries with d... |
61,616,999 | 61,617,182 | Could not find a package configuration file provided by "boost_atomic" | I am compiling C/C++ to wasm with emscripten. And need boost library as well. Pretty new to emscripten and wasm
After installing emscripten and boost. I ran the following command
emconfigure cmake -DBoost_DEBUG=1
-Dboost_headers_DIR=../boost_1_71_0/build/lib/cmake/boost_headers-1.71.0
-DBoost_DIR=../boost_1_71_0/build... | I added a flag -Dboost_atomic_DIR=/path/to/.cmake/file in the above command and it worked.
|
61,617,052 | 61,627,259 | C++ Implementing a tree containing multiple types with templates | I am trying to implement a complex structure for a project of mine, but I don't know how to proceed.
The structure itself is a tree, where every node has a string id and is either a tree or a container for one of the supported data types, somewhat like json data.
tree: {
value1: 4,
value2: {
value3: 40.... | I searched for a while, and found a solution. I wanted to avoid C as much as I could but in the end, what is C++ but C with a bunch of stuff ?
The comments are correct, using std::variant or an union are the way to go, and do not be afraid of using pointers towards next nodes.
There is also a bunch of stuff doable with... |
61,617,065 | 61,617,252 | What's the void* of function pointers? | I am trying to compile some old code.
Depending on the compiler I get this warning/error when I try to assign a function pointer to a void* pointer:
warning: a value of type "double (*)(double, double)" cannot be assigned to an entity of type "void *"
error: invalid conversion from ‘double (*)(double, double)’ to ‘vo... |
What's the void* of function pointers?
In a way: All pointers to functions.
A special thing about pointer to void is that it can point to any object, and any object pointer can be converted to pointer to void and back, which yields the original pointer.
All pointers to functions can be converted to other pointers to ... |
61,617,315 | 61,622,773 | BOOST_STRONG_TYPEDEF and move semantics | From what I can see BOOST_STRONG_TYPEDEF does not support move semantics(no move ctor/assignment).
Is this just an oversight(nobody updated old macro) or is there a more fundamental reason why strong typedefs are limited in this way?
| The fundamental reason would be that many boost libraries are still targetting pre-c++11 standard compilers¹, i.e. compilers that do not support move semantics.
I suppose for some compilers the tricks in Boost Move might be used, but I'm not sure that would be easy to apply transparently to strong typedefs.
However, I'... |
61,617,639 | 61,617,878 | C++: const array instance generation in header file | I could use a define macro to do what I want to achieve. But I'm sure there is a better way with C++14.
Basically I would like to instantiate a std::array of objets in the header of a class without defining by hand each instance.
const std::array<property<uint16_t>, 16> cmd_eng1 =
{{
{PROG_MEM_ENG1,... | @Micheal's answered can be slightly improved by using a lambda instead of a function.
This is somewhat similar to the trick used to initialize a local const variable using complex logic without having to write a helper method.
const auto cmd_eng1 = []{
std::array<property<std::uint16_t>, 16> result = {};
for (... |
61,617,726 | 61,617,833 | Add c++ compiler flags using CMake | I am quite new to the whole CMake logic and syntax. For the code I am working on, I need to use the cap_set_proc function to work with a process capabilities flags (man link). So I decided to start with a really stupid piece of code that you see here:
#include<iostream>
#include<string>
#include<sys/capability.h>
usin... | Something like the following should be all you need:
cmake_minimum_required(VERSION 3.17)
project(TestCapProject)
# Add your executable target.
add_executable(test_cap test_main.cpp)
# Link the libcap library to your executable.
target_link_libraries(test_cap PRIVATE cap)
If you're adding this to an existing CMake ... |
61,617,847 | 61,625,381 | How to write to a file using read system call ? and how to decide the buffer size? | i am writing a code that reads from a file and write to the other file , i am having a problem deciding what to put the buffer size , because i don't know, it could be any file , also how to read from a file using while loop ? :
here i opened the first file:
int fd1 = open(args[1], O_RDONLY);
if(fd1 == -1){
... | You should read up on pointers. The read function wants a pointer to use.
A traditional solution looks like
#SIZE 255
char buff[SIZE]
int count = read(fd1, buff, SIZE)
//add logic to deal reading less then SIZE
That is because the name of an array is a pointer to the first element in the array.
If you only want to re... |
61,617,963 | 61,618,218 | Unable to pass vector to lambda function | Im unable to pass my vector into my lambda function.
Am i missing something simple?
Thanks.
std::vector<Wnd_S> GetWindows()
{
std::vector<Wnd_S> vRet;
::EnumWindows(static_cast<WNDENUMPROC>([vRet](HWND hWnd, LPARAM lParam) -> BOOL {
char buffer[255];
GetClassNameA(hWnd, buffer, sizeof buffer);... | Capturing lambdas cannot be casted into function pointers, so you can't capture vRet. But EnumWindows takes the second parameter that is then passed to the callback function. You can use it to pass vRet into your callback:
std::vector<Wnd_S> GetWindows() {
std::vector<Wnd_S> vRet;
::EnumWindows([](HWND hWnd, L... |
61,618,102 | 61,618,359 | How do you disable a specific warning for C++ in Visual Studio 2019? | I've found answers which suggest right clicking the solution and going to Code Analysis Settings but this has been deprecated in VS2019. I found a response here on StackOverflow that talked about Roslyn Analyzers, but that only applies to .NET. I need to disable warning C26451 as it's completely useless and underlines ... | To disable a specific warning for a C++ project, choose Project - Properties - Configuration Properties - C/C++ - Advanced - Disable Specific Warnings - Edit... and then input warning code(s) you want to suppress (26451 in your case) without the C part.
Performing code analysis now does not yield a C26451 warning. Tha... |
61,618,528 | 61,651,758 | How to Add io2d.h library to intellisense in Visual Studio Code | So I have this C++ Project which uses the io2d library.
I installed the library and compile and run the project with CMake.
However Intellisense Show Errors in the cpp Files which use like this:
I thought if I add the path of the header in the c_cpp_properties.json it would work:
However no luck. What else can I ch... | io2d header uses the cairo library internally. In order to get this to work we need to add the include path for cairo aswell:
"includePath": [
"${workspaceFolder}/**",
"/usr/local/include/io2d",
"/usr/include/cairo"
],
|
61,618,869 | 61,619,240 | How to use value of inherited class member, when upcasting to base class | I have a problem with displaying the content of inherited class members, when up casting to the base class. Currently, the result displayed is 4, how can I achieve 2?
#include <iostream>
#include <vector>
#include <memory>
#include <tuple>
class A {
public:
A() = default;
std::vector<int> v = {3, 4, 5};
};
clas... |
How to use value of inherited class member, when upcasting to base class
By using runtime polymorphism. Write a virtual function.
In this case, a virtual overloaded subscript operator might be appropriate:
struct A {
virtual int& operator[](std::size_t index) = 0;
};
struct B : A {
int& operator[](std::size_... |
61,619,086 | 61,619,129 | Persisting variables outside scope of a function | This is part of a debugging assignment that I've been stuck on for days. I'm not as much looking for an answer as much as I'm looking for where to look to find the answer.
I have a function that takes an int as a parameter, and the test uses that function to calculate the sum of the range (0,n]. My problem is that I am... | You can change the value of an argument to a function, by taking that argument as a reference:
bool getNum(int &n) // note the reference parameter
{
// changes to n are visible to the caller of this function
}
You have to change the declaration of getNum to match as well, of course.
Note that there is no change to ... |
61,620,170 | 61,620,246 | How to create specialization template using scope resolution operator in cpp | template<class t> class Temp{
static t x;
public:
Temp(){};
t increment();
~Temp(){/*body of destructor is important.*/};
};
template<class t>t Temp<t>::x;
template<class t> t Temp<t>::increment(){
return ++x;
}
/*Template specialization starts.*/
template<>class Temp<int>{
int x;
... | You don't have to use template<> with specialized member function, because the compiler knows that you are specializing the Temp for int type. So an empty template<> giving the error.
int Temp<int>::increment() {
return ++x;
}
template is used to tell the compiler that T is template param, that's all. But in your ca... |
61,620,225 | 61,621,116 | FindFirstFileW Issue - How to Convert 'LPWIN32_FIND_DATA *' to 'LPWIN32_FIND_DATAW' | I have implemented the following function to list the contents of a directory but when I compile and linked the program, the compiler gives the following two errors to me:
error C2664: 'HANDLE FindFirstFileW(LPCWSTR,LPWIN32_FIND_DATAW)': cannot convert argument 2 from 'LPWIN32_FIND_DATA *' to 'LPWIN32_FIND_DATAW'
erro... | You are passing FindFirstFileW() and FindNextFileW() a pointer to a pointer to a WIN32_FIND_DATA, but that is not what they are expecting, hence the compiler errors. They want a pointer to a WIN32_FIND_DATAW instead.
You are also misusing printf() and wprintf().
Try this:
bool FmListDirectoryContents(LPWSTR arg_path_d... |
61,620,390 | 61,645,059 | Why does gcc's implementation of openMP fail to parallelise a recursive function inside another recursive function | I am trying to parallelise these recursive functions with openMP tasks,
when I compile with gcc it runs only on 1 thread. When i compile it with clang it runs on multiple threads
The second function calls the first one which doesn't generate new tasks to stop wasting time.
gcc does work when there is only one function... | Your program doesn't run in parallel because there is simply nothing to run in parallel. Upon first entry in mario, current_node is 9 and vec is all 8s, so this loop in the first and only task never executes:
for(int i = current_node;i <= vec[current_node];i++){
++steps;
mario(i + 1,new_... |
61,620,449 | 61,620,671 | OpenMP expected declaration or statement at end of input | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <sys/time.h>
#define N 10000
int A[N][N];
int B[N][N];
int C[N][N];
int main(){
int i,j,k;
struct timeval tv1, tv2;
struct timezone tz;
double elapsed;
for (i= 0; i< N; i++){
for (j= 0; j< N; j++)
... | I got following errors on Wandbox:
prog.c: In function 'main':
prog.c:29:35: error: expected 'none' or 'shared' before 'private'
29 | #pragma omp parallel default (private) shared (A,B,C,N) num_threads(4)
| ^~~~~~~
prog.c:29:58: error: expected ')' before numeric constant
... |
61,620,512 | 61,620,578 | Perfect forwarding interpreted as rvalue reference | My understanding was that ConcreteType&& was an rvalue and TemplateType&& was "perfect forwarding".
I'm trying to use perfect forwarding, but clang-tidy interprets it as rvalue reference.
clang and gcc don't complain, but clang-tidy marks it as parse error before doing any further analysis, so I'm not sure if it's an i... | T is fully resolved by the time the constructor is invoked, so it's not perfect forwarding anymore
If you want perfect forwarding on a function, it has to be the function itself that's templated, not the enclosing class.
Like so:
template <typename T>
class my_wrapper {
T val;
public:
template<typename U>
my_wra... |
61,620,601 | 61,622,157 | Safe way to reference nested member | I have a struct with some other structs as member. Both external and internal structs are StandardLayout (it can be even assumed that internal are plain old data). Something like this:
struct Inner1 {
int a = 0, b = 0;
};
struct Inner2 {
int c = 0, d = 0;
};
struct Outer {
Inner1 x;
std::string s;
I... | You can do it this way.
/* main.cpp */
#include <string>
#include <iostream>
using namespace std;
struct Inner1 {
int a = 0, b = 0;
};
struct Inner2 {
int c = 0, d = 0;
};
struct Outer {
Inner1 x;
std::string s;
Inner2 y;
};
struct OuterMember
{
int (*getter)(Outer &obj);
};
inline int ge... |
61,620,645 | 61,620,991 | How do you read a text file into a vector in c++? | I am trying to read a text file containing 9 lines of single integers into a vector. VS Code returns no syntax error but when I debug the program, I got a segmentation fault under main(I commented on the specific line). Am I doing something wrong with my implementation? Thank you in advance!
#include <iostream>
#inclu... | This vector:
vector <int> list = {};
Has exactly zero members. You never try and increase its size so any access to this array will result in a bad result.
There are a couple of places you accesses this vector:
input>>list[i];
// and
cout<<list[k];
These are both invalid access to the list.
To fix the problem you c... |
61,620,949 | 61,621,463 | Is there an analogue of keyword "where" from C# in C++? | I need to create a template class in C++. I need to make sure that the type for the template parameter will be a class with 1 int field and 1 string field (there can be more fields, but these are mandatory).
For example, in C# I could define an interface with methods or properties, like this:
interface MyInterface {
... | C++20 offers you the closest solution to C#:
#include <concepts>
template <class T>
concept MyInterface = requires(T x)
{
{ x.GetSomeInteger() } -> std::same_as<int>;
};
And then:
template <MyInterface T>
struct MyClass
{
// ...
};
|
61,621,328 | 61,623,288 | Class layout: Do all objects created from the same most derived polymorphic class type share a unique memory layout? | From https://en.cppreference.com/w/cpp/language/data_members#Layout:
Layout:
When an object of some class C is created, each non-static data member of non-reference type is allocated in some part of the object representation of C.
Q1: Is it also true for object of (possibly virtual) base class and non-static data ... | By definition, the object representation contains all the data stored in the object, including all non-static data members and base classes, whether virtual or not. The definition of object representation in C++17 is:
the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T).
... |
61,621,446 | 61,621,711 | How can I change char array to int array in c++ and store it separately | I don't know how to use the atoi function. If I change atoi(e) to atoi(e[i]), it produces an error.
How can I store the data separately, for example tmp[0]=3 tmp[1]=5
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
char e[11]="3596047218";
int max=0,tmp[11];
cin... | atoi doesn't accept chars as an argument, it accepts c-strings (const char*). When you subscript a char array, you return a reference to a char. This is what is causing the error. You don't actually need atoi at all to solve your problem, nor do you need std::cin. This is what your code should look like:
int main(){
... |
61,621,473 | 61,621,919 | C++ / WinRT Coroutine does not compile due to problem with type conversion | I've started to use C++/WinRT and I want to implement coroutine which call function "LaunchFileAsync". But my code doesn't compile and I have no idea why.
#include <pch.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.Storage.h>
using namespace winrt;
using namespace Windows::System;
using namespace Windo... | The code is attempting to return an awaitable object rather than the value it returns. You will have to co_await the result first before you can co_return it:
Windows::Foundation::IAsyncOperation<bool> ActionOnClick()
{
const auto uri = Uri(L"URI");
const auto storageFile{ co_await StorageFile::GetFileFromAppli... |
61,622,004 | 61,624,764 | Message size limit seems much smaller than should be in Open MPI | As I understand from this answer, there is a size limit of 2^31-1 elements for the messages that you can send/receive in Open MPI. Nevertheless, when I try to send an int array that has more than exactly 4786470 elements my code simply stops working. It does not give me any error messages or segfaults, it only gets stu... | It looks like this is a known issue from version 4.0.1 of Open MPI running on macOS. MPI stops communication after transmitting 19145881 bytes, which gives exactly an array of 4786470 integers. The bug was fixed for the versions >= 4.0.2 and after installing a newer version the example worked perfectly.
|
61,622,082 | 61,622,149 | Benefits of using a create() method instead of the class constructor? | In this code, class Window has a create() method. The Windows OS' window class is here. Why was it done this way instead of using a constructor, and thus saving the hassle of doing auto win = Window::create()?
I believe that it was done so they could return a nullptr. Am I wrong?
| Window::create is a "factory function". The main reason why factory functions are sometimes used instead of constructors in C++ is that a constructor T::T can only create objects of type T, whereas a factory function T::create can return a pointer to T, which could potentially point to a derived class. The actual type ... |
61,622,116 | 61,622,420 | C++ redefinition with include guard and #pragma once | So I'm new to the concept of header files. As far as I understand stuff gets defined in the header and then implemented/used in the *.cpp file. It now cannot build and is giving me Semantic Issues "redefinition of '//*literally everything*//'"
What I do now is
//move.hpp
#pragma once
#ifndef MOVE_HPP
#define MOVE_HPP
... | Technically, you do not need to use #pragma once and #ifndef.. #define... #endif together. They are the same algorithms for compiling the header file only once!
I never encountered the problem myself, but for the purpose of multiplatforming and compiling without errors - I would use the latter (#ifndef.. and #endif) on... |
61,622,194 | 70,427,240 | Whats the best possible way to represent a time as a double type | I am trying to use a library called QCustomPlot and on the X Axis I want to be able to put the users time zone of the stock market being open, from say 9:30AM to 4:00PM but the paramenters i need when setting the range of the x axis has to be a double, what is the best way about getting the time to a format I can use? ... |
what is the best way about getting the time to a format I can use?
You need a QwtDateScaleEngine along with a QwtDateScaleDraw. These will interpret your double values as the time from the epoch "1970-01-01T00:00:00 UTC" in milliseconds.
ui->stockGraph->setAxisScaleDraw(QwtPlot::xBottom, new QwtDateScaleDraw());
ui->... |
61,622,386 | 61,622,480 | Why doesnt this function overide the base class function | So here is the base class:
class MovieRepo {
protected:
MyLista<Movie> all;
public:
MovieRepo();
void store(const Movie& m);
}
And this one is the override:
class RepoFile : public MovieRepo
{
private:
string filename;
void loadFromFile();
void storeToFile();
public:
RepoFile(string _file... | MovieRepo::store() is not a virtual function. The override specifier only works with virtual functions. Change the base class method to a virtual method to fix the issue.
|
61,622,561 | 61,622,625 | C++ resize 2d vector where function is const | I create a 2D vector (0,0) and would like to resize it (n,m), however, my resize function must remain const
I have tried doing
void resize(int row, int col) const
{
array.resize(row, vector<int>(col));
}
but keep getting
passing ‘const std::vector<std::vector<int>, std::allocator<std::vector<int>... | When you put const on the end of the function there, you're saying the implicit this is const. That is, you're promising not to modify the state of the object this function is being called on.
But isn't the whole point of calling resize() to modify the state of the object? If I were you, I'd take the const off of there... |
61,622,654 | 61,622,699 | Multiplication/division order(?) confusion | I'm just calculating the volume of the sphere and unexpectedly
volume = (4/3)*M_PI*pow(radius, 3);
or
volume = 4/3*M_PI*pow(radius, 3);
gives 392.699 (should be 523.6)
But if I write
volume = 4*M_PI/3*pow(radius, 3);
or
M_PI*4/3*pow(radius_, 3);
Everything is fine. But
M_PI*(4/3)*pow(radius_, 3);
again gives w... | 4/3 will return 1 in c++, since both 4 and 3 are integers, and dividing two integers will result in integer division. You can solve this by performing floating-point division: 4.0/3.0. This will give the expected output.
The reason volume = 4*M_PI/3*pow(radius, 3); works, is because multiplying an integer by a double,... |
61,622,745 | 61,623,240 | non-type template parameter alias in a different type | I am trying to define a generic container with a template parameter. There are predefined values to pick from for the template parameter. For convenience, I would like to also allow passing integer values as an alternative, and have them mapped automatically to the corresponding predefined value.
For example (this does... | There is no safe or standard way to get the desired effect, and if you reach a point where this begins to look like a viable option, I would strongly recommend reconsidering your design. However, if you are insistent, you have a c++17 compiler, and you are willing to use pointers instead of references, you can use non-... |
61,622,826 | 61,623,164 | Is implicit construction of `const std::string` from `const char *` efficient? | Like many people I'm in the habit of writing new string functions as functions of const std::string &. The advantages are efficiency (you can pass existing std::string objects without incurring overhead for copying/moving) and flexibility/readability (if all you have is a const char * you can just pass it and have the... |
It strikes me that, because everything is const, copying is not
necessary—a thin STL wrapper around the existing pointer is all that's
needed
I don't think this assumption is correct. Just because you have a pointer to const, it does not imply that the underlying value cannot change. It only implies that the valu... |
61,622,891 | 61,634,284 | C++ Compiling windows service with visual studio | hope you could help me. I got a C++ source for my service based on Microsoft example, still i get linker error compiling it:
error LNK2019: unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
as the entry point for windows services is int _tmain(int argc, TCHAR... | Ok, still no luck with _tmain. Unfortunately i haven't tried to define WINAPI WinMain entry point.
Still if you proceed with wmain program entry point and add code mentioned by Richard Critten for a service startup SCManager performs just fine. For a complete service sample refer to MS doc.wmain will force you to use U... |
61,622,959 | 61,623,087 | error: cannot initialize a variable of type 'int *const' with an rvalue of type 'const int * | Why am I getting this error: error: cannot initialize a variable of type 'int *const'
with an rvalue of type 'const int * when compiling the following code?
Code:
constexpr int ch1 = 5;
constexpr int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr int* pch2 = &ch2;
cout << *pch1+*pch2;
Let me make this clear. Th... | The fact that you have declared pch1 and pch2 as constexpr does not of itself make them const int *, so you would need:
constexpr int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr const int* pch2 = &ch2;
However, then you get:
error: '& ch1' is not a constant expression
error: '& ch2' is ... |
61,623,274 | 61,623,770 | What does adding a pre-processor variable before a function declaration means? | I'm reading the Dear ImGui API, and i'm wondering what does it mean to add a pre-processor variable (here IMGUI_API) before the function declaration like this :
#ifndef IMGUI_API
#define IMGUI_API
#endif
...
namespace ImGui
{
...
IMGUI_API float GetWindowWidth();
...
};
Thanks in advance !
| Like Hans Passant said - it won't always be empty.
One of the main properties of dynamic shared objects (and DLLs in Windows) is that the internal symbols of the library are not exposed to the user. In GCC, this is done by specifying the default symbol visibility to "hidden" on the command line when building the librar... |
61,623,284 | 61,623,426 | Remove last n elements of vector<int> in O(1) complexity C++? | I want to remove the last n elements of a vector of integers in constant time complexity O(1). This should be doable I think because only some arithmetic for the end pointer is needed. However, erase, resize, and remove all have O(n) complexity. What function is there to use?
| The C++ standard (I believe) says that the cost of removing k items from the end of a std::vector must have time complexity O(k), but that's an upper bound on the amount of work done, not a lower bound.
The C++ compiler, when generating code for std::vector<int>::erase, can inspect the types and realize that there's no... |
61,623,438 | 61,623,673 | Type trait for boost multiprecision integers | I want to write a type trait to identify boost multiprecision integer types. I can do this for a concrete type like uint256_t:
template <typename T>
struct is_multiprecision_int : std::false_type {};
template <>
struct is_multiprecision_int<uint256_t> : std::true_type {};
But how can I do the same for ANY boost multi... | Okay, I'll take a crack at this.
Based on the official documentation for boost-multiprecision: https://www.boost.org/doc/libs/1_73_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html, this may be a possible option:
#include<type_traits>
using namespace boost::multiprecision;
//helper struct for ... |
61,623,624 | 61,640,969 | Reverse linked list causes a loop | Why does this cause a loop?
I am trying to do a reverse linked list using an iterative method, but a loop occurs when the head node is traverse (ex. print()). I've tried this with C# and had no problem (modified syntax of course).
struct Node {
int data;
Node* next;
};
void
Reverse(Node& head_ref) {
Node* curre... | head_ref = *prev; overwrites a Node because head_ref is Node&, not Node*&. Whereas you intend to update head pointer, rather than an entire Node head_ref refers to.
One fix would be:
void Reverse(Node*& head) {
Node* current = head;
// ...
head = prev;
}
// ...
Reverse(head);
Alternatively:
Node* Reverse(N... |
61,623,662 | 61,623,761 | Deallocating memory using double pointers | Just a question about deallocation through a double pointer.
Would the following basic example be correct?
#include <iostream>
int main()
{
int **d = { new int*[3] };
int * p = { new int[100] } ;
p[0] = 300;
int *x = new int(1);
d[0] = p;
d[1] = x;
// pointer in d[0] is a pointer to an ... | You (try to) access p[0] after your delete[] d[0]; call, and d[0] has the p address as its value, so that delete[] call frees the p memory. This means your cout statement is undefined behaviour (when I run it, I get a 'random' value for p[0]).
Move the cout line to before the delete[] d[0] call, and you'll see the valu... |
61,623,716 | 61,631,083 | Saving in binary files | I've been working on a project for the past few days that involves three linked lists.
Here is an example of the header with the nodes and the lists themselves:
class nodeA
{
int data1;
double data2;
nodeA* next;
}
class listA
{
nodeA* headA;
...
}
class nodeB
{
int data3;
double data4;
... | So lista_vendas::novaVenda needs to call lista_produto::escolheProduto.
To call lista_produto::escolheProduto you need a lista_produto object. Where are you going to get that lista_produto object from?
There's really only three ways this can be done. I don't know which way is the correct way for you, but I'll list them... |
61,623,755 | 61,636,330 | How to make method of a base class use inherited protected members that derived class sets? C++ | I've got a problem that even though the code in the loop has the correct pointer type ( as call to tells() shows ) it still uses getPointer() over default constructed Triangle class, if I'm not wrong.
How to make a call to getPointer() in loop return a pointer to the memory where the coordinates saved?
main.cpp:
#inclu... | The main problem in this code is that when constructors of derived classes (all but the unused here IsoscelesTriangle(QPointF ,uint, uint) are called they invoke additional constructors inside themselves thus creating a temporary object instead of initializing class fields.
Also it would be a good idea to make points a... |
61,623,803 | 61,623,965 | Why can std::cin not be implicitly converted to bool? | In C++ Primer 5th Ed., Chapter 14 discusses conversion operators:
Under earlier versions of the standard, classes that wanted to define a conversion to bool faced a problem: Because bool is an arithmetic type, a class-type object that is converted to bool can be used in any context where an arithmetic type is expected... | The operator bool is declared explicit, so it shouldn't be implicitly converted to a boolean:
bool b = std::cin; // Error
So you need to explicitly convert cin to a boolean for it to work:
bool b {std::cin}; // OK, explicitly converting
So when you try to call
std::cin << 5;
It won't compile because you're expecting... |
61,624,054 | 61,624,326 | Private variable declaration in implementation file | Consider this header file:
#ifndef __FOLDER_H__
#define __FOLDER_H__
#include <boost/filesystem.hpp>
class Folder
{
public:
Folder(char* arg);
private:
std::vector<boost::filesystem::path> files;
};
#endif
Everybody including Folder.h will also include boost/filesystem.hpp. However, there a... | There are quite a few idioms to hide the implementation details of a given class. Two of the ones I tend to use are PIMPL and interfaces.
PIMPL
PIMPL is a paradigm where you define a private structure with no definition in the header file, and all of your private implementation details are stored in this private struct... |
61,624,176 | 61,624,295 | Why does the C/++ scanf function need referenced variables as arguments? | Why does the C/++ scanf function need referenced variables as arguments? I was wondering why scanf can't just take in the variable itself, since it gave me a weird warning whenever I didn't put in a referenced variable. It thought I had put in a pointer. Why is that? Thanks.
|
I don't see how they could modify the value
Here is an example
#include <stdio.h>
void changeNumber(int *n) {
*n = 12;
}
int main() {
int x = 5;
printf("X: %i\n", x);
changeNumber(&x);
printf("X: %i", x);
return 0;
}
Output
X: 5
X: 12
|
61,624,187 | 61,624,814 | Should a friend function of a class template become friend to all instantiations? | Consider the following snippet:
template<typename T> struct Foo {
friend void bar(Foo, Foo<char> f) {
static_cast<void>(f.private_field); // Should only compile when friends with Foo<char>.
}
private:
int private_field{};
};
int main() {
bar(Foo<char>{}, Foo<char>{}); // Compiles.
bar(Foo... | GCC is plainly wrong here: because each specialization defines its own separate friend function (as it must to avoid duplicate definition errors), bar(Foo<char>,Foo<char>) is a friend of Foo<char> but bar(Foo<char>,Foo<char>) is not. The standard contains a relevant example that mentions a very similar case.
|
61,624,620 | 61,625,302 | How does that syntax for defining a full function template specialization a friend of a class? | I saw the following example at cppreference (" Template friend operators" section), simplified
template<typename> struct Foo;
template<typename T> void bar(Foo<T>) {}
template<typename T>
struct Foo {
// friend void bar<T>(Foo f); // (1)
friend void bar<>(Foo f); // (2)
};
int main() {
bar(Foo<int>{});
... | See C++17 [temp.friend]/1:
A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or a non-template function or class. For a friend function declaration that is not a template declaration:
if the name of the friend is a qualified ... |
61,624,743 | 61,624,851 | taking the last element of a vector and moving it to another vector | I am trying to move the last element of the vector old_balls to the new vector new_balls.
But when I call the function, it doesn't move the element to the new vector.
I think I am using the move function correctly.
std::vector<ball*> old_balls;
std::vector<ball*> new_balls;
void move(std::vector <ball*> ball_box, std:... | You are passing the vectors by value, so you are acting on copies of the vectors, not on the original vectors. You need to pass the vectors by reference instead.
Also, you said you wanted to move the last element, but you are actually moving the first element instead. And you are not removing the element from the old... |
61,624,843 | 61,637,611 | How to access .second in std::pair with std::variant? | I'm using MinGW64 with GCC 7.5.0 that enables C++17 on Dev C++ 5.11 on Windows 7.
Now how to access .second in the following pair?
#include <iostream>
#include <vector>
#include <variant>
using namespace std;
int main()
{
vector<pair<char,variant<bool,int,string>>> x;
x.push_back(make_pair('i',5));
cout<<x[... | Extract a specific value from the variant based on type:
if(auto pval = std::get_if<int>(&x[0].second)) {
std::cout << "variant has int value: " << *pval << '\n';
} else {
std::cout << "failed to get int value!" << '\n';
}
if(auto pval = std::get_if<bool>(&x[0].second)) {
std::cout << "variant has bool v... |
61,624,859 | 61,624,886 | why does long long 2147483647 + 1 = -2147483648? | Why doesn't this code print same number? :
long long a, b;
a = 2147483647 + 1;
b = 2147483648;
printf("%lld\n", a);
printf("%lld\n", b);
I know that int variable's maximum number is 2147483647 because int variable is 4 byte.
But as I know, long long variable is 8 byte, but why does that code act like that?
| 2147483647 + 1 is evaluated as the sum of two ints and therefore overflows.
2147483648 is too big to fit in an int and is therefore assumed by the compiler to be a long (or a long long in MSVC). It therefore does not overflow.
To perform the summation as a long long use the appropriate constant suffix, i.e.
a = 214748... |
61,624,907 | 61,625,144 | How to choose when to split a string with comma | I have a string that needs to be split by commas, but there is a comma in the string that I do not want to split on.
So, my string is:
Let's eat, Granny,Happy,22,Chicken
I want to split it like this:
Let's eat, Granny
Happy
22
Chicken
But I get this instead:
Let's eat
Granny
Happy
22
Chicken
How do I split this str... | Given the data you are limited to, a comma is really not a reliable separator, unless you can guarantee that any ignorable commas are always followed by whitespace. If so, you can do something like this:
char delimiter = ',';
string test = "Let's eat, Granny,Happy,22,Chicken,";
size_t start = 0, end;
string token;
do... |
61,625,449 | 61,625,590 | No Names returned in search function | So I cant get my search function to return to the actual title of the movies with the instantiated array with a movie title, director, and actor. I create an array of objects, instantiate it, run a do while loop to get the position, and run a search algorithm to get the title, director, and actor of the movie. But for ... | This line:
Movies moviesArr[ARR_SIZE];
defines an empty, uninitialized array of Movies. You are searching for a particular Movie title in hollywood, which finds the movie. However, you are then indexing moviesArr:
cout << "The movie: " << moviesArr[pos].getTitle() << " is in the list. " << endl;
which is undefined b... |
61,625,667 | 61,632,009 | Texture wont appear FreeGLUT | i have a simple plain (square) with lighting and material on it, i want to put an earth texture on it. but nothing appears. I've checked, and think it loads the RGB data correctly so my guess is that there is a problem with this line (data is *char and the image is BMP24)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, outWidt... | You missed to set the Set the texture parameters by glTexParameter.
If you do not generate mipmaps (by glGenerateMipmap), then setting the GL_TEXTURE_MIN_FILTER is important. Since the default filter is GL_NEAREST_MIPMAP_LINEAR the texture would be mipmap incomplete, if you don not change the minifying function to GL_N... |
61,625,722 | 61,626,752 | Why do I get "unhandled exception" error and how can I fix it? | I am trying to write a code that uses 2 recursive functions; 'I' and 'U' and one non-recursive function 'f'. What I am tring to achive is to run the recursive function I "steps1" many times and then stop at this level to then run the recursive funtion U "steps2" many times.
After that, finally run the non-recursive fu... | I compiled and ran your program and it looks like you're getting a stack overflow. The recursion for function I isn't correct. Namely your base case will never be reached. In each location that I is called you only pass 3 parameters, thus counter1 is always going to have a value of 0, the default value. Also, I is alwa... |
61,625,783 | 61,627,651 | How can I remove values from output statement given a condition? - c++ | I'm a little confused as to how to go around this. I have some array variables with some information, and I want to print them out after some calculations. If the value is 0, then I want to print a " " instead. There are 3 arrays that need to get checked however, how would I change the output statement to cater for all... | A single line to std::cout doesn't need to be done in one statement. For example:
std::cout << "First";
std::cout << ", second"
std::cout << ", third\n"
Prints the following line:
First, second, third
Now we can use an if to conditionally print the middle part of the string:
std::cout << a;
if (b != 0) {
std::cout... |
61,625,786 | 61,628,099 | How to add error checking in a class member function? | Given a class and one of its member functions like this:
// constructor
class Stitcher::Stitcher(const std::vector<cv::Mat> imgs)
{
calibrate(imgs);
}
// one of its member functions that gets called upon construction
void Stitcher::calibrate(const std::vector<cv::Mat> imgs)
{
// Do some stuff here
}
When con... | What you could do is throw an exception to indicate a problem that occurs during the execution of your program. The standard library has a number of exception classes that you could use for throwing an exception, all of which derive from std:exception. For example, std::out_of_range.
To throw a standard exception you c... |
61,625,807 | 61,625,909 | Why instantiating a shared_ptr calling destructor? | Can someone explain why is the destructor of class bar being called in the line where the object of the same type is being initialized?
#include <memory>
#include <iostream>
using namespace std;
class bar
{
public:
bar() {}
~bar() { std::cout << "destructor called " << std:... | This statement:
f = std::shared_ptr<foo>(new foo(std::shared_ptr<bar>(new bar())));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
constructs a temporary shared_ptr which goes out of scope at the end of the statement. At that point, the shared_ptr goes away, taking bar with it (since no copies of th... |
61,625,839 | 61,625,886 | Mysterious slowdown when adding doubles to dynamic vector in C++ | I am experiencing some unknown slowdown when adding doubles to a very large dynamic vector of doubles in C++.
As seen below, it appears that slowdown occurs specifically due to adding a double that was calculated from a long-winded sum of cos and sin functions.
When only A_temp1 is added to the dynamic vector, there i... | If you are not using A_temp2 at all, I believe it is a compiler optimization and it is not even calculating the number because you are not using it. When you start using it in your second code. It can't ignore the calculation which causes the slowdown.
Edit: I think the only way to help the excution time in your case i... |
61,625,880 | 61,629,967 | VSCode + cmake + windows 10 -> cmake not in path | I am new to VS Code and CMake in general. I come from 14 years of using Visual Studio and solution files. Now the industry wants me to be cross platform and do things in Linux. Well, I don't want to be a deprecated old man.
I downloaded VSCode and installed the cmake and cmake tools extensions. I created a folder, open... | Visual Studio 16 2019 already includes a CMake installation in C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe. So my guess is that you are using this version inside VSCode.
To run an explicitely installed CMake you should download a CMa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.