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,600,322 | 62,606,425 | SDL_Texture renders black after resize unless it is redrawn | I've got a bit of a nasty bug for you folks. (Yes, it's probably my bug and not SDL's.) I have been in the process of writing a modern C++ wrapper for SDL and everything appears to be working as intended. However, my Texture class has a strange bug: if it is redrawn after a resize, it looks fine, but if it is not, it b... | SDL doesn't promise to keep target textures data. There are cases, especially with d3d or mobile, where data is lost due to some big state change. Changing window size may sound not that big, but on some hardware/driver configurations is causes problems, I suppose that's the reason why SDL detects resize and drops all ... |
62,600,380 | 62,600,446 | how to return a list of objects without destroying them | How to fix the function 'func' so that it returns the objects without being destroyed?
function 'func' must add the objects to a list and return them but be destroyed
The Smoothy abstract class has a purely virtual description method (). DecoratorSmoothy
contains a smoothy, description () and getPret () methods return ... | In func you are storing the address of function local variables in l. So when you return l from the function, all the Smoothy* are now pointing to invalid memory.
To fix this, you can allocate memory for each pointer you add to l, like this:
l.push_back(new Smoothy{a1}); // instead of l.push_back(&a1);
// etc. for a2... |
62,600,764 | 62,601,299 | Is it possible to assign an C++ pointer to an attribute of a Python object, and retrieve it as a C++ pointer in another C++ function? | I'm making a C++ extension for Python, and I'm trying to do something like:
// this function assigns a C++ pointer to as attribute of a python object
void function1(PyObject* p){
// equivalent of p.attr = cpp_attr;
MyClass* cpp_attr = new MyClass();
PyObject* args = PyTuple_Pack(cpp_attr);
PyObject_SetA... | Assuming your call to PyTuple_Pack is correct, then you've created a PyTupleObject which has a structure:
typedef struct {
PyObject_VAR_HEAD
PyObject *ob_item[1];
} PyTupleObject;
The PyTupleObject inherits from the generic PyObject struct which has the following members:
struct _object *_ob_next;
struct _object *... |
62,600,775 | 62,600,832 | C++ enter key on console with empty line not registering | I noticed if when prompted to enter my choice, if I press enter (creating an empty line) it didn't detect my input as a 0 length input but rather it just allowed me to enter on the next line down. How do I stop this in an easy way so even if its an empty input it still registers
#include <iostream>
int main()
{
std... | Instead of:
std::cin >> MMOption;
you can do:
std::getline(std::cin, MMOption);
which will read empty lines as well. std::getline needs #include <string> as well.
|
62,600,941 | 62,602,181 | CMake: can't find my header file in a different directory | I have a CMake project with these relevant folders:
project_folder
-src
|--main.c
peripherals
|--something.h
|--something.c
My CMake in project_folder includes:
add_subdirectory(peripherals)
if (NOT $ENV{TARGET_SOURCES} STREQUAL "")
target_sources(app PRIVATE $ENV{TARGET_SOURCES})
else()
target_sources(app PR... | You can either do "#include "../peripherals/i2c_test.h" in your main.cpp
OR
in your CMake in project_folder:
target_include_directories(app ${CMAKE_CURRENT_SOURCE_DIR})
and then in main.c:
#include <peripherals/i2c_test.h>
....
|
62,601,267 | 62,611,348 | Export C++ Package with Abstract and Normal Classes to Python | I would like to export a lot of abstract and normal classes from C++ to Python. It is essentially a whole package coded in C++ and would like it to be ran in Python. Instead of individually wrapping each classes, is there a way to easily wrap them and have them work in Python?
| boost python and pybind11 allow you to "export" C++ classes as python object.
Both propose similar approaches based on templates. Pybind11 solution is said to be easier to use. If you use Microsoft toolchain, you can refer to this page to see how to design/build python bindings using pybind11:
https://learn.microsoft.c... |
62,601,530 | 62,602,465 | How to install OpenCV for C/C++ on Ubuntu | I want to install the C/C++ interfaces for OpenCV. I have already installed it for Python, which was a very straightforward process, I just had to issue the command pip3 install opencv-python and it got installed.
I have followed many sites on how to install OpenCV for C/C++, but they teach of installing it from the so... | One option is to use the package manger apt
sudo apt-get install -y libopencv-dev
and then link your source to the libraries.
|
62,601,754 | 62,602,050 | How to change just one item of QCombobox to editable by user | I have 4 items in my QCombobox,
'Bryce king'
'James White'
'Russo W'
'Custom Manager'
So, when I click on "Custom Manager", it should change to editable and I must be able to enter my own desired name.
I have tried to achieve this behavior using QtCreator, and in the properties, I can set it to editable but that woul... | First make sure your combobox's editable property is set to false.
Then you can use the QComboBox::currentIndexChanged signal and check the value of the current index and then make the combobox editable. Example:
void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
if (arg1 == "Custom Manager") {... |
62,601,933 | 62,602,010 | How do I list my currently open open files in Xcode? | VS Code has a nice feature which shows your working files on the upper left corner. Visual Studio doesn't have it, but there's a plugin that makes it possible in Visual Studio too, which can be found on the marketplace.
Is there anything like this in Xcode or for Xcode? How do switch on that view/panel/dialog in Xcode,... | Xcode doesn't have plugins (anymore). They don't have a feature exactly like the one in VSCode, but you can have the left panel show some recently opened files with the clock icon on the bottom of the navigator panel (see photo).
Also, if you are willing to lose a couple of first-party features, you can do some hackin... |
62,602,165 | 62,602,185 | Why don't function pointer arguments affect memory size? | Recently I was looking at the src code for the gl3w library. I noticed that it used a new type of structure for me: a union. I found out that a union was a way for multiple data types to exist in the same place. But what I noticed was that it was switching between the type without reassigning values. It was switching f... | A function pointer is still just a pointer, i.e. it contains a memory address.
It doesn't contain anything about what the pointer points to. That's part of the language, not the representation of a pointer.
|
62,602,210 | 62,602,525 | Template c++ compiler differences VC++ different output | I had written some c++ code in Visual Studio and was trying to run it on my c++ code on a linux server. When I tried to compile it with G++ however, it failed to compile with tons of errors. I looked through the error and was able to simplify the problem to this:
template<int x>
struct Struct
{
template<int y>
... | template<int x>
struct Struct
{
template<int y>
static void F()
{
Struct<y>::F<0>(); // does not compile?
}
};
should not compile. You need to specify for the compiler that F in fact requires a template list, since F is a dependent template type. Otherwise the compiler will assume that the next... |
62,602,232 | 62,602,490 | Using boost to create multiple child processes to be run asynchronously | How do I spawn multiple child processes that should run asynchronously? Do I use a vector of child processes? I'm afraid the code below doesn't do what I'm trying to accomplish. Any other suggestions for a different way to pass arguments to the child process is also welcome!
#include <iostream>
#include <string>
#inclu... | you are waiting for each process before starting the next one . instead you should spawn them all then wait for them outside the loop . here is the edited code :
#include <iostream>
#include <string>
#include <sstream>
#include "boost/process.hpp"
int main()
{
namespace bp = boost::process;
std::string child_... |
62,602,597 | 62,602,679 | Why are pointers inside of a vector changing when being returned from a function? | In my actual application, I'm using a doubly-connected edge list to store subsections of a plane but I've attempted to reduce the code to display my issue.
I have a list containing a custom struct that I need to convert into a vector of pointers to the objects stored in my list. When I do this, inside the function wher... | You need to accept the structs by reference, otherwise the pointers that you create inside the function are referring to copies of the original MyStruct objects.
static std::vector<MyStruct*> structPointers(
std::list<MyStruct>& structs) // <-- take by reference
Here's a demo.
|
62,602,714 | 62,602,745 | how to create a class so that the vector works std::vector<MyClass<int>> v{ 1,2,3 }; | I need a class so that the instruction works
int main() {
// create a vector with values 10,2,3
std::vector<MyClass<int>> v{ 10,2,3 };
//print values
for (const auto& m : v) std::cout << m.value() << ",";
return 0;
}
| Simply write a template class:
template<typename T>
class MyClass {
private:
T val;
public:
MyClass(T a) : val{std::move(a)} {}
T value() const { return val; }
};
Note that if you mark the constructor as explicit:
explicit MyClass(T a) : val{std::move(a)} {}
Then you will have to explicitly construct the valu... |
62,602,785 | 62,604,389 | c++ Read contents of xml file | I am still learning c++ and need some help reading the contents of an xml file.
Here's the format of my xml file:
<Rotary>
<UserInformation>
<Name>myName</Name>
<Age>myAge</Age>
</UserInformation>
</Rotary>
My c++ program needs to read the values of Name and Age so that I can check it on a SQL DB. I'm real... | Uhoh. That API looks hypercomplicated. TinyXML is geared for performance, but nothing else really.
So. Choosing your library is the most important step: What XML parser should I use in C++?
Now, in most circumstances where you can use TinyXML you can use PugiXML. PugiXML has a much friendlier interface. Most importantl... |
62,602,945 | 62,603,434 | How retrieve complete filename with NtQueryDirectoryFile in recursive mode? | I'm using this code to go through all files and directories recursively.
Now i want know how extract complete filename (path + filename + extension)? the following line(also present on reference code) give only filename + exension (without directory name).
DbgPrint("%s%8I64u <%wZ>\n", prefix, DirInfo->EndOfFile.QuadPar... | if we want not simple enumerate folders/files but with full name, need write appropriate code. for example:
#define ALLOCSIZE PAGE_SIZE
// int nLevel, PSTR prefix for debug only
void ntTraverse(POBJECT_ATTRIBUTES poa, int nLevel, PSTR prefix)
{
if (IoGetRemainingStackSize() < PAGE_SIZE)
{
DbgPrint("no ... |
62,603,396 | 62,603,490 | Problem with running thread class on c++ by using ubuntu terminal | I decided to make some threads research in C++.
Everything was great, Visual Studio compiled it easily.
But when I decided to compile all of that stuff by using Ubuntu terminal for Windows - I ran into mistake below.
I tried to compile like:
g++ -o thread ThreadTest.cpp
g++ --std=c++17 -o thread ThreadTest.cpp
Have a... | In order to use threads you have to ensure that you're linking the proper library. To do so, just add -lpthread as in:
g++ -o thread ThreadTest.cpp -lpthread
|
62,603,618 | 62,604,500 | PDB symbols could not be loaded (igvk32.pdb not loaded) | While compiling my Vulkan program I was getting this error
I have tried the Microsoft symbol services but it didn't work.
| When debugging your own code you do not need none of those, because you already have the correct driver binary on your PC. You will not be getting any additional info (symbols such as function names in the driver), since the drivers are not open-source.
I think in default VS settings it should land you on the last know... |
62,603,714 | 62,603,779 | Why stack and heap are so much separated in memory? | I' am learning c++ and executing this code
#include<stdio>
using namespace std;
int main(){
char* buffer = new char[5];
printf("%p", &buffer); // 000000000061fe10
cout<<endl;
printf("%p", buffer); // 0000000000796b700
}
gives me 2 memory locations that are totally sepa... | The layout of memory depends on the operating system, the program loader, which is usually supplied with the operating system, rules regarding executable files, and requests given to the linker. You have not specified which operating system you are using, so a definite answer is not possible.
However, memory addresses ... |
62,603,926 | 62,603,973 | why is this code's vector iterator not stopped? | I am a very beginner for c++.
When I do exercise problem, I met the problem.
under code !!
I expected do from factors.size() to 0.
But, It didn't work like.
It return to me, from factors.size() to 0, -1(4294967295), -2(4294967294), ...
Why is this code not return 0 and not stop?
If you know, please let me explain.
... | This loop:
for (iter=factors.size()-1 ; iter >= 0 ; --iter)
is guaranteed to never terminate, since iter, which is vector<int>::size_type, is an unsigned type. When you subtract 1 from an unsigned 0 you get a large positive number, instead of a negative number. Since iter never becomes negative, the loop condition is ... |
62,604,259 | 62,688,153 | what is the difference between memory allocated by VirtualAlloc and the memory allocated by std::vector | i tried to understand it but all what i understood so far is that using VirtualAlloc can allocate large memory pages for large buffers for example and std::vector too but VirtualAlloc i can commit the page i can set the permission to read,write , or execute and i can't do that with std::vector or can i? am basically tr... | std::vector is a container that manages an array on the back end and provides functions that help you interact with it easily, with the bonus of being able to increase and decrease it's size. This is implemented as part of the C++ Standard Library.
VirtualAlloc() is a Windows API function and only works on Windows. I... |
62,604,262 | 62,604,341 | Throwing exception in initialisation list? | I have the following code:
In Game.h:
mtm::Dimensions dimensions;
std::vector<std::shared_ptr<Character>> board;
In Game.cpp:
Game::Game(int height, int width) : dimensions(height, width), board(height * width, nullptr)
{
if (height <= 0 || width <= 0) {
throw mtm::IllegalArgument();
}
}
But as you m... | If you cannot do the check in mtm::Dimensions, it really should be there, you can use a helper function:
int throw_if_not_positive(int x) {
if (x <= 0) throw mtm::IllegalArgument();
return x;
}
Game::Game(int height, int width) :
dimensions(throw_if_not_positive(height),
throw_if_not_positi... |
62,604,541 | 62,604,582 | Copying the data of a child class of a parent to another class with same parent | This is a tricky answer to find using google since there are many similar questions but different.
Basically the idea is that, I have ProjectA and ProjectB where they both inherit ProjectBase. They parse the data differently but other that each having his own members they both update also the members from ProjectBase.
... | This is one of the cases where object slicing is actually what you want. If you upcast the target object reference then the implicit ProjectBase copy-assignment operator will do what you want.
static_cast<ProjectBase &>(*projectb) = *projecta;
This will assign only the inherited data members of ProjectBase from *proje... |
62,604,603 | 62,604,611 | Why is my node set as a nullptr after I have set it = new Node? | I have initialized a node pointer as nullptr and passed it as reference into a helper function. Inside the helper function, I set the pointer which was previously nullptr equal to new Pointer. However, after the function ends, it is set to nullptr again.
void helper(vector<int>& nums, int start, int end, TreeNode* root... |
passed it as reference into a helper function
No, the pointer is passed by value itself. The parameter root is just a copy of the argument, any modification on the pointer itself inside the function has nothing to do with the argument.
Change it to pass-by-reference:
void helper(vector<int>& nums, int start, int end,... |
62,604,738 | 62,605,078 | C++ class - initialization list - recursion - passing by value | I have created a StateNode class which is not making a copy of itself when I try to pass by value. During the running of my algorithm I receive a 'segmentation fault' error, which is been caused by the StateNode class, once it is being passed to the recursive function. However the 'segmentation fault' only occurs on ab... | First of all you should read on the Rule of zero. As you don't manually manage any resource you shouldn't have any user defined copy ctor, copy assign and destructor.
I see nothing wrong with your code. The seg fault is probably caused by the high level of recursion deep.
|
62,604,843 | 62,606,329 | Finding the minimum value | I can't begin to understand how to approach this problem. Can someone help me to just point me in the direction as to how I can approach it?
N tasks are given and there are M workers that are available. Each worker can takes different times to complete each task. The time taken by each worker for every task is given. A... | The best way I can think to solve this is using recursion. I would implement this by having a list of unusable workers and a running sum passed to each call, and a global variable of minimum value.
This would also work best if you had a matrix of values. So like matrix[0] = {1, 2, 3}; matrix[1] = {3, 4, 5}. I haven't h... |
62,604,919 | 62,604,928 | How to get rid of a number after the result being shown? | I have to write a program that calculates the formula inputted from the user. For example:"input: 1+2", "output: 3", but I keep getting a number after the answer like this:"input: 1+2", "output: 3-12". How do I get rid of that -12 behind the 3? And why is it giving me that number? Here is the code:
#include <iostream>
... | The expression in the if statement:
if(x='+')
doesn't compare x to +, but instead assigns + to x. That means every single one of your if statements evaluates to true, and you get 3 numbers as output, i.e. 3, -1, and 2.
The correct way to do a comparison is:
if(x == '+')
If you turn on all your warnings, the compiler ... |
62,605,275 | 62,605,486 | QGraphicsItems not showing up QGraphicsScene | I'm trying to build a custom widget with a QGraphicsScene inside it.
class Graphics:public QWidget{
public:
Graphis();
}
Graphics::Graphics(){
QGraphicsScene* scene = new QGraphicsScene(this);
QGridLayout* grid = new QGridLayout;
QGraphicsView* view = new QGraphicsView(this);
... | Try it like this instead; I think one problem is that scene->width() and scene->height() are very likely both returning 0, at least on your first call to them, since sceneRect() defaults to returning a QRect big enough to fit the current contents of the scene (which is initially empty):
Graphics::Graphics(){
QGraph... |
62,605,754 | 62,605,865 | error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'const int')| | I was just learning macros and working of pointers/references through a simple program of calculating area.
Here's the code:
#include <iostream>
#define PI = 3.141592653589793238
#define AREA(new_r) (PI*new_r*new_r)
#define PERIMETER(new_r) (2*PI*new_r)
using namespace std;
int main()
{
cout<<"Enter the radius:";
... | There are couple of issues with the code.
#define PI = 3.141592653589793238
The proper format to declare macro is: #define <macroName> <macroValue>. There is no need to use = sign. And so the proper way should be #define PI 3.141592653589793238.
#define AREA(r) (PI*new_r*new_r)
#define PERIMETER(r) (2*PI*new_r)
It... |
62,605,777 | 62,606,394 | Between Python and c++ 2d array initialization. What is this ? and why? | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
I came up... | In your C++ code:
vector<vector<int>> matrix(m, vector<int>(n, 0));
you're creating a vector of m vectors each containing n elements initialised to 0. That's like a 2d matrix of m rows x n columns.
The equivalent code in Python is:
arr = [[0 for x in range(n)] for y in range(m)]
which is a list comprehension. This sy... |
62,605,863 | 62,608,175 | Can I redefine a c++ static const defined in a OpenCascade/OCCT header at runtime? | Maybe this is simple but I would like to dynamically redefine a constant set in a library header, so that I don't have to recompile it every time it should be changed. In OpenCascade's Precision.hxx the constant "Precision::Confusion" is defined as:
class Precision
{
public:
...
static Standard_Real Confusion() { re... | If you want to play with this constant affecting everything in your code and in OCCT itself without re-compilation of every piece of code using it, you may move definition of constant to .cxx file.
// Precision.hxx
class Precision
{
public:
...
Standard_EXPORT static Standard_Real Confusion();
...
}
// Precision.cxx... |
62,605,887 | 62,605,956 | Is i++ or ++i better for this program? | i'm trying to create a program which checks if input is is an int or a string.
This is the code:
// CPP program to check if a given string
// is a valid integer
#include <iostream>
using namespace std;
// Returns true if s is a number else false
bool isNumber(string s)
{
for (int i = 0; i < s.length(); i+... | I prefer the form ++i in C++, because i may be an iterator or other object with overloaded operator++. In those cases, the form i++ generates a temporary object to hold the previous value of i, while the form ++i does not. The compiler may optimize away that temporary object, but it’s not required to, and in some cases... |
62,605,902 | 62,606,254 | Fraction in any kind of in any kind of orders | Hi I have a homework that update function input Fraction in any types
But I don't know what I wrong :< Can you help me
template <class T> struct Fraction {
T num, denom; //num - Numerator ; demon-Denominator
};
template <class T>
void inputFraction(T a[], int &n) {
cout << "Enter n:"; //number of Fractions
... | Clearly you have some way to go in understanding templates. Writing template code isn't just a matter of putting template <class T> in front of everything.
main cannot be a template
It's clear that you are trying to write code where you can have fractions of different basic types, Fraction<int> or Fraction<long> for ... |
62,606,252 | 62,606,681 | SIGSTP error in lead game problem of codechef. TLG problem | `
#include<bits/stdc++.h>
#include <iostream>
#include<vector>
using namespace std;
int main() {
// your code goes here
int t;
cin >> t;
vector<int>v1, v2;
v1.push_back(0);
v2.push_back(0);
while (t--)
{
int a, b;
cin >> a >> b;
if (a > b)
v1.push_bac... | Submitting this code didn't got me SIGSTP but I got Wrong Answer verdict. This is due to the fact that you are not checking the cumulative scores of the players but directly comparing the current scores and pushing them in the vectors accordingly. You can maintain two variables to store the cumulative scores of the pla... |
62,606,340 | 62,725,355 | Automatically generate import module for dynamic loading .so library | I want link open source 3rdparty library as dynamically loaded shared library on Linux. It is need to allow use it as optional plugin. It is AWS-SDK for C++ library but it is not important for question and uses as example. I build .so library and could statically link it and use they API in my code. When i removed libr... | There is no builtin way to do this with GNU tools but generation of necessary boilerplate code (dlopen, dlsym, etc.) can be easily automated (see e.g. the Implib.so project).
|
62,606,403 | 62,607,118 | UML Design Pattern and implementation into C++ classes | I am trying to learn Adapter Design Pattern UML with C++ and in one of the videos in youtube displayed this content - my issue is translating the UML picture to C++ class / code:
What I really get confused is:
The Clinet -------> [solid line] association to interface Target. What does this means generally I have seen... |
The Clinet -------> [solid line] association to interface Target. What does this means generally I have seen classes implementing interface something like Adapter class implementing Target
no, the Client does not implement/inherit Target, so
class Client : public Target {
...
};
is wrong.
The association can indi... |
62,606,466 | 62,748,470 | How to sort an array of order 300000? | I'm new to competitive programming and I came across ICPC Challenge on Codeforces. The first problem is https://codeforces.com/contest/1376/problem/A1 this and they gave file that has 30000 inputs. They basically ask you to sort list of integers in non-decreasing order.
I started off by implementing a bubble sort code ... | You can manually implement Merge Sort algorithms. Or just call the built-in C++ sort function.
#include <bits/stdc++.h>
using namespace std;
int main(){
freopen("sort.in", "r", stdin);
freopen("output.out", "w", stdout);
int n, , arr[500000];
cin >> n;
for(int i=0; i<n; i++){
cin >> arr[... |
62,606,952 | 62,608,094 | OpenMP parallel for with ordered and critical directives | I've been trying to understand how OpenMP parallel for loop works when combined with critical sections and ordered directives. There are a couple of code samples which I find confusing:
1. OpenMP parallel for loop is used to initialize the array s with the loop index i and the thread ID. No ordered directives or critic... |
I am failing to figure out why s contains the i indices (first number) in a strict sequence despite the absence of the ordered directives and why printf("i: %d tid: %d\n", i, tid) shows them in a different order?
With static scheduling there is a fixed mapping between loop iteration and thread that executes it, which... |
62,607,154 | 62,607,233 | how can I rotate an object around a point other than the origin point with glm::rotate? | I am trying to make my world rotate around my camera no matter where my camera is. I am not doing any crazy math yet, I am leaving middle school this year and I don't know what quaternions are. My problem is that every time I use glm::rotate function for anything it only allows me to rotate around an axis at the origin... | What you actually do is to rotate the model:
model_view = look * rotate
If you want to rotate the view, then you have to swap the order of the matrices. Note, the matrix multiplication is not Commutative:
model_view = rotate * look
For your code that menas:
glm::mat4 rotate = glm::rotate(glm::mat4(1.0f), Rrotation, t... |
62,607,261 | 62,610,346 | Defining a variable in a header file doesn't give an error | I am writing some code to test that variable shouldn't be defined in a header file. However, there isn't any error. I just can't figure it out.
Please tell me why an error does not occur when I run build.bat. The variable is defined in the header file, which is included by two source files.
The structure of the CMake p... | First, forget about the header file. That's a distraction. In essence, the question is about having two source files that define the same name:
// file1.cpp
int a = 1;
// file2.cpp
int a = 1;
and the question is, why doesn't compiling and linking this code give an error?
The technical answer is that such a redefiniti... |
62,607,474 | 62,607,817 | How to optimise this code of sorting,this is not exeuting within the time limits.This question is from hackerrank | How to reduce the time compexity of this code,this is not exeuting within the time
exact ques from hackerrank--
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a... | The vector a is being rotated by k in the while loop. The whole loop can be removed by adding k and using modulo when accessing elements in a:
ans.push_back(a[(queries[i]+k)%a.size()]);
Note: you might need handling of negative values of k.
Note: Maybe it should be minus instead of plus.
An alternative could be to use... |
62,607,492 | 62,607,538 | set::find() not working with user define data type | When I am searching for a key which is not present in my set then find() instead of returning iterator to end is returning an iterator to an another object which is not equal to key but present in set.
I have no idea whats going wrong.
CODE
class node{
public:
int a, b;
node(int a, int b):a(a), b(b){}
boo... | When comparing objects as equal or not std::set uses the comparison function (i.e. greater<node> which uses node::operator>) but not node::operator== (as you expected).
In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a).
For node(3,6) ... |
62,607,597 | 62,607,873 | How to assing a vector to a matrix in eigen | I want to assign a vector to a matrix of Dynamic size. As in the following code:
Eigen::Vector3f VectorCam; // Vector in camera frame
Eigen::MatrixXf VectorsCam; // Matrix contains the vectors
for (int i=0; i<=theta1.size(); i++)
{
std::cout << "I'm In theta1.size for loop" << std::endl;
... | Before calling VectorsCam.col(i) you must make sure, VectorsCam has at least i+1 columns. And when assigning VectorsCam.col(i) = VectorCam; the number of rows in VectorsCam must match the number of rows in VectorCam.
Before the loop write
Eigen::MatrixXf VectorsCam(3, theta1.size()); // Matrix contains the vectors
(an... |
62,607,618 | 62,819,562 | QtCharts setRange issue | I want to display some data using QtCharts. When I set my data then nothing is displayed. I think the problem is with the setRange method.
Code:
chart.h:
#ifndef CHART_H
#define CHART_H
#include <QChart>
#include <QTimer>
#include <QAbstractAxis>
#include <QSplineSeries>
#include <QValueAxis>
#include <QDebug>
QT_CHA... | I have fixed the issue by using QtNetworkMonitor example from GitHub. The issue is resolved.
|
62,607,661 | 62,607,694 | Capitalizing letters | I have got a small problem. I want to capitalize on doubled letters in a string. I managed to compile a program, but not successfully.
#include <iostream>
#include <cctype>
#include <string>
std::string::iterator function(
std::string::const_iterator a,
std::string::const_iterator b,
std::string::const_itera... | You have a couple of issues there.
Firstly, your function promised to return std::string::iterator
std::string::iterator function(....)
{
//... return statement is missing here!
}
and you are not keeping the promise. This will leads to undefined behaviour. For example, in your case, it just compiles and does not gi... |
62,607,708 | 62,609,561 | Why SDL_RenderCopy and SDL_RenderCopyEx take non-const textures? | I'm optimizing my SDL code and adding const qualifiers wherever possible and stumbled upon the following declaration of SDL_RenderCopy:
int SDL_RenderCopy(SDL_Renderer* renderer,
SDL_Texture* texture,
const SDL_Rect* srcrect,
const SDL_Rect* dstrect)
The te... | Short answer: RenderCopy keeps track of when texture was used by modifying texture->last_command_generation: https://hg.libsdl.org/SDL/file/355a4f94a782/src/render/SDL_render.c#l2997
texture->last_command_generation = renderer->render_command_generation;
retval = QueueCmdCopy(renderer, texture, &real_srcrect, &real_ds... |
62,607,819 | 62,622,332 | QT question about how to use a pointer to MainWindow | I know how to use a pointer to Widget like Widget* fatherPtr = (Widget*)parentWidget();.
But in MainWindow it doesn't work when I use MainWindow* ptr = (MainWindow*)parentWidget();. It seem that it's an invalid pointer. How to solve it? I am anxious to get the correct solution, thank you very much!
| I had solved my question by using the function declared in MainWindow:
MainWindow* MainWindow::getMainWindow()
{
foreach(QWidget *w, qApp->topLevelWidgets())
if (MainWindow* mainWin = qobject_cast<MainWindow*>(w))
return mainWin;
return nullptr;
}
Thank you to everyone who helped me
|
62,607,824 | 62,607,967 | Create a env file containing default values in c++ | I'm creating a c++ project that contains some specific configurations. Those configs can be calibrated depending the scenario.
As the problem that I trying to solve is a optimization problem and configurations like BigM and cycles are values that makes difference depending the instance I believe that a configuration f... | A common way to solve this problem is to pass the values as command line parameters:
./myapp --NUM_STABILIZED 1000000 --bigM 1000000
This approach requires you to parse the command line. You can use a library for this, for example cxxopts. Default values could be used if there are no command line parameters.
You could... |
62,608,100 | 62,608,186 | Operators overloading add using operator+ for a class-template | I need a function to add values to v[i] using the operator+
the vector v contains the values 10,2 and 3.
#include <iostream>
#include <vector>
template<typename T>
class Measurement
{
private:
T val;
public:
Measurement(T a)
: val{ a }
{}
T value() const { return val; }
Measurement<T>... | Just add the val of the instance to other nr
Measurement<T>& operator+(const T& nr)
{
this->val += nr;
return *this;
}
However, overloading the operator+ for this might be misleading and should be avoiding such. Therefore I would suggest the traditional way
Measurement<T> operator+(const T& nr)
{
Measurement... |
62,608,120 | 62,608,522 | "Warning: Comma within array index expression" but comma is separating function arguments | MSVC reports
warning C4709: comma operator within array index expression
on the following line:
intersections[img::at(rotJ, rotI)];
Without knowing more, is there any chance that this warning is valid?
| The warning C4709: comma operator within array index expression is a rather buggy warning and has numerous reports all over the internet. See for e.g this or this or this (9 years old).
So the answer is, it is misleading.
Note that if someone were to use the comma-operator within the array index:
int a[3] = {1, 2, 3};
... |
62,608,228 | 62,610,474 | Is there any function in C++ equivalent to the get function for dictionary in python? | Am trying to solve this problem statement.
It basically wants you to change the duplicates in the given vector to a unique form:
Ex: ["name","name","name1"] -> ["name","name2","name1"]... you get the idea
So I thought of using std::map to create a dictionary (I could also have used unordered_map here)
This is how I us... | Your important part code is equivalent to:
for (const auto& name : names) {
map_of_names[name] += 1;
}
If name is not found, then the value type is default-constructed, and default-constructed int is 0.
You could do something similar in Python, using defaultdict:
import collections
file_names = ["file1", "file2", ... |
62,608,423 | 62,608,545 | Why static_cast enum class that underlying type is int8_t to get an unexpected value? |
compiler : clang++
c++ standard : c++20
I tried to run the code, and the results met my expectations very well.
#include <iostream>
using namespace std;
int main()
{
enum class Num : int
{
one = 1,
two = 2,
zero = 0
};
Num e = Num::one;
auto a = static_cast<std::unde... | int8_t maps to char, and this type is by default printed as its character representation. The character with value 1 is a control character which you can't see.
So, cout << (int8_t)65 will print A and not 65 because the single character 'A' has value 65.
You can avoid that by casting to int before printing: cout << (in... |
62,608,431 | 62,608,452 | Store coefficients in an array in header file ("does not name a type" error) | I want to create a class to solve a numerical analysis problem, and I have to store somewhere an array of doubles that I will need several times. So I just created an header file to hold those constants
#ifndef COEFFS_H_
#define COEFFS_H_
#include <iostream>
#include <complex>
using namespace std;
const int p = ... | Two errors, first the correct syntax is this
double alpha[p] = { 1.83, -7.15, ... };
You can't write executable code outside of a function as you were doing.
Second even with this correct syntax by defining your array in a header file you are running the risk of multiple definition errors. The correct technique is to ... |
62,608,756 | 62,609,391 | Insertion at n'th place in Linked List showing Segmentation error | void Insert(int data, int n){
Node* temp1 = new Node();
temp1 -> data = data;
temp1 -> next = NULL;
if(n == 1){
temp1 -> next = head;
head = temp1;
return;
}
else{
Node* temp2 = head;
for(int i; i< n-2; i++){
temp2 = temp2 -> next;
}
... | void Insert(int data, int n)
{
Node* add = new Node(); // Node to be added
add -> data = data;
add -> next = NULL;
if(n == 1)
{
add -> next = head;
head = temp1;
return;
}
else
{
Node* temp2 = head;
Node* prev = NULL; //Previous pointer
for(int i=0; i< n-2; i... |
62,608,802 | 62,610,190 | I am getting this strange compilation error in C++ | I was doing the Coin change problem, I am trying to do it using Dynamic Programming. But I am getting this compilation which I don't quite understand. Someone told me that I have to assign the 'dp' array dynamically, but he was not sure why. PLease explain this concept .
#include<bits/stdc++.h>
using namespace std;
int... | There are two problems in the code.
First, in the function int countWaysToMakeChange(int denominations[], int numDenominations, int value)
int dp[value+1][numDenominations+1];
is illegal. Array bounds must be compile-time constants. Some compilers allow this sort of things as an extension (and it's legal in C), but it... |
62,609,167 | 62,612,120 | how to use cv::VideoCapture::waitAny() in opencv | I've been trying to find a way to asynchronously check to see if the next frame of the camera that I get using videocapture is ready.
I came across waitAny() which is described to "Wait for ready frames from VideoCapture.".
in the OpenCV documentation, I didn't find any useful info on how to use this or what are the us... | An approach that IMO is fairly common is to have a pair of threads -- one that "produces" frames from VideoCapture (calls VideoCapture::read() in a loop), and another that actually uses these frames (a "consumer"). The producer pushes images onto a queue (that's shared across two threads), while the consumer pops them.... |
62,609,367 | 62,609,413 | c++ - const member func, that can be called upon lvalue instances only, using a ref-qualifier | I'm trying to enforce a const 'getter' method of a class to be called upon only lvalue instances of the class, via a ref-qualifier and for some reason getting an unexpected result (I'm compiling with clang 6.0.1 with C++ 17 support, via c++1z flag, on Windows):
The declaration bool getVal() const &; allows the method t... | Use bool getVal() const &;, but add a deleted overload for rvalues:
bool getVal() const && = delete;
|
62,609,370 | 62,609,897 | How to shorten nested namespaces in a return type which is private to an inner class? | This question is about dealing with a long nested private class namespace in a method return type in .cpp files.
There have been previous questions on avoiding long names and nested namespaces in a cpp file, but they don't seem to cover my use case.
I have a private nested class with a private type specific to that cla... | This seems to work:
auto outer::inner::manipulate_foos(footype f1, footype f2) -> footype { ... }
|
62,609,758 | 62,610,343 | Updating results during runtime with Ranges | Using Range library for C++14/17/20 extension I noticed that when i store some results of range::views::method() operations that, during runtime, every change or update of the original data will cause the same changes to it's new constructed results, even after the event (instruction).
A link is there, but what is the ... | Yes, because that is the intended behavior of ranges::views. It's supposed to be a non-owning view on some data. If that underlying data changes, then the view has no choice but to see those changes, since it doesn't have its own data that holds on to the previous state.
One exception to this is ranges::views::single w... |
62,609,805 | 62,610,143 | How can I have a fallback run-time implementation in a constexpr function | Context
I'm making a math library and I need to use sqrt().
As sqrt() is not a constexpr function I've implemented a constexpr version of sqrt() and a faster that std::sqrt() that uses assembly, so must be used on run-time.
Now, I'm using all this to calculate the length of a vector, and this function can be constexpr ... | The only standard-compliant solution is to use std::is_constant_evaluated, as suggested by cigien:
constexpr inline Real length() const
{
return std::is_constant_evaluated()
? fast_sqrt<Real>(lengthSquared())
: const_sqrt<Real>(lengthSquared());
}
The problem with this approach is that std::is_... |
62,610,185 | 62,610,268 | How to convert a std::ifstream to std::basic_istream<CharT, Traits>&? | I have the following method:
template<typename CharT, typename Traits, typename Alloc>
auto getline_n(std::basic_istream<CharT, Traits>& in, std::basic_string<CharT, Traits, Alloc>& str, std::streamsize n) -> decltype(in)
Full version of the this method included at the bottom.
I need to be able to convert a std::ifstr... | You don't.
Your std::ifstream is already derived from std::basic_istream<CharT, Traits>.
The function is defined that way so that you could pass a [reference to] another kind of stream instead, if you wanted to.
Absent errors elsewhere in your program, this code already works.
|
62,610,433 | 62,610,666 | access and print data in a tuple and display it using a template function using C++14 | i have a list like follows
my_mixed_list = {"Sample String", int_value, user_data_type}
I want to use C++11 std::tuple to display above list in simple white separated way.
may be like this:
template <typename T>
void display_mixed_items (std::tuple <T> mixed) {
for (const auto& mixed_ele : mixed) std::cou... | You can get by creating your own for_tuple function to iterate over tuples:
template<typename T, typename F, std::size_t... S>
void for_tuple_impl(std::index_sequence<S...>, T&& tup, F& function) {
using expand_t = int[];
(void) expand_t{(void(function(std::get<S>(std::forward<T>(tup)))), 0)..., 0};
}
template... |
62,610,834 | 62,610,962 | How to implement the same method in classes derived from an abstract base? | I have an abstract class Job and other classes that implement it like:
Waiter and Builder, all of them implement my function in the same way.
For example:
Waiter::changeScore()
{
score += top_score;
}
How may I prevent this kind of code duplication?
Constraints:
I want to keep Job abstract.
Each Waiter or Builde... | Not all member functions of an abstract class need to be pure virtual (as long as at least one is). Your changeScore member is an ideal candidate as a 'real' base class function. Further, not only does it not need to be pure virtual, it doesn't even need to be virtual at all (unless you want your polymorphism to change... |
62,611,017 | 62,612,913 | Why does the following code not result in moving the object instead of copying? | #include <iostream>
#include <time.h>
class A
{
public:
A() { std::cout << "a ctor\n"; }
A(const A&) { std::cout << "a copy ctor\n"; }
A(A&&) { std::cout << "a move ctor\n"; }
};
A f(int i)
{
A a1;
return i != 0 ? a1 : A{};
}
int main()
{
srand(time(0));
f(rand());
return 0;
}
The output is:... | The difference you're seeing is due to the use of the ternary/conditional operator. The ternary operator determines a common type and value category for its second and third operands, and that is determined at compile time. See here.
In your case:
return i != 0 ? a1 : A{};
the common type is A and the common value cat... |
62,611,060 | 62,611,126 | Is it possible to create an array with subscripts of variable type through the template? | It might be used like this
str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2
| Yes, declaring str and num as follows
template <typename>
std::string str;
template <typename>
int num;
Are template variables, available starting from C++14.
But take in count that all str variables are of type std::string and that all num variables are of type int.
As pointed by Davis Herrings, using specialization... |
62,611,207 | 62,611,347 | typedef decltype function pointer not returning proper output (cout) | I'm having a problem using decltype to create a typedef function pointer to "foo". printf works but with a warning: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘bar {aka int (*)(int)}’ [-Wformat=] and cout displays "1". I'm sort of a newbie when it comes to function pointers so I don't ... | You have to create variable of type bar and initialize it with foo address.
because () has higher precedence than *, you have to use parentheses (*var)(80) to dereference pointer to function, after that you can call it:
typedef decltype(&foo) bar;
bar b = &foo;
printf("printf: %d\n", ((*b)(70))); //work with a warning:... |
62,611,676 | 62,612,344 | Template constructor is not considered | I'm implementing a version of std::experimental::observer_ptr with some own additions. I also want to add a constructor taking a std::unique_ptr. In addition, I want to be able to construct from convertible pointer types. Based on a similar example in the reference, this is what I came up with:
template <typename T>
cl... | Your templated constructor is incorrect, since the default type of enable_if_t is void, and you can't assign 0 to that.
You can fix it like this:
template <typename U, std::enable_if_t<std::is_convertible_v<U*, element_type*>, int> = 0>
observer_ptr(const std::unique_ptr<U>& ptr) noexcept : m_ptr(ptr.get()) {}
Here's ... |
62,611,799 | 62,612,034 | Inheriting static variable in classes? | Given an abstract class called Job and other classes that inherit it like Teacher, Worker ,etc...
I want those classes to inherit something like a static variable -I'm saying like since it's not allowed to inherit static according to what I read- for Job (Like Salary) with different values for each class, how may I do ... | I hesitate to post this answer, because I think the code as posted is just fine, but if you really want to eliminate the salary variable, then you can do this:
class Job
{
...
virtual int GetSalary () = 0;
};
class Teacher : public Job
{
...
int GetSalary () override { return 100; }
};
class Worker : ... |
62,612,405 | 62,640,703 | /usr/bin/ld: cannot find -lc++ | I am following a tutorial on building an audio classifier here and when reach to the step where I run the sh build.sh I get the cannot find -lc++ error.
Kindly, any advice on how to fix this error would be highly appreciated.
Building standalone classifier
mkdir -p build
rm -rf *.gcda
rm -rf *.gcno
clang -c -DTF_LITE_D... | Replace clang by clang++ or g++. Then -lc++ becomes "automagically" linked.
Of course, spend a few days reading the documentation of GCC and of Clang (and of ld from binutils; since both clang++ and g++ are running ld). Read carefully about invoking GCC. The order of program arguments to g++ (and also to clang++) are... |
62,613,068 | 62,613,778 | Good practice for error handling and cleaning up resources in SDL? | When using SDL, I have been handling errors (e.g. during SDL initialisation) by returning false whenever an error is encountered in a function, and true otherwise. The cleaning-up is then performed by calling a close() function at the very end of the main() function, as such:
int main(){
if(!init()){
// do ... |
Use atexit() to handle SDL_Quit() and IMG_Quit()?
I wouldn't use atexit. Other alternatives give you a better control over when the cleanup happens.
Use unique_ptr (or other smart pointers) by initialising SDL object normally and provide a deleter class for cleaning-up.
It could work, but I don't like this ... |
62,613,101 | 62,625,860 | How can we elimate break statement in C/C++ programs to support compiler for auto vectorization? | There are some of the rules to be followed while programming, making the program easy for the compiler to auto vectorize.
Some of the rules include:
No 'break' statements(The loop should have single flow)
No 'if' statements(Only masked assignment allowed) and many other
It would be great to know what steps can be tak... |
It would be great to know what steps can be taken in order to replace these conditional break statements.
Generally speaking, you don't.
A break statement within a loop exists to terminate the loop, typically based on a condition other than the loop's normal termination condition. Loops usually have a terminal condit... |
62,613,420 | 62,614,489 | Importing a C# DLL into C++ for use with JNI | I am writing a program in Java which must use a DLL file (which is one written in C#), I figured the best way to do this is to write a C++ program as an interface, and then use JNI. The C++ program will be responsible for using the DLL in a JNI friendly way so that I can then call it from my Java program.
I'm trying to... | You can avoid C++ and make calls from Java to C# and back directly, but you'll have to bootstrap the whole thing from C# side:
In your Java program create a class and expose a JNI method:
public class Foo {
static native void bar(); // This method will be implemented in C#
}
Compile the Java program into a JAR ... |
62,613,560 | 62,619,677 | POSIX shared memory model | Is there a memory model specification for POSIX shared memory (across processes)?
I'm hoping that there's something to comparable to the C++ memory model, in order to answer questions like the following:
Is there a definition of a data race?
Are data races undefined behavior (as in C++)?
Is there something to constrai... | According to POSIX specification, a shared memory object is defined as
An object that represents memory that can be mapped concurrently into the address space of more than one process.
On platforms as Linux, the memory object when mapped is equivalent to an anonymous mapping: this is a mapping of the physical RAM (or... |
62,613,795 | 62,614,847 | Can two consecutive arrays of the same type be treated as one? | Consider the follwing code:
struct S {
int a[2] = {1, 1};
int b[3] = {2, 2 ,2};
};
int main() {
S s;
for (auto *p = std::begin(s.a); p != std::end(s.a); p++)
std::cout << *p << std::endl;
for (auto *p = std::begin(s.b); p != std::end(s.b); p++)
std::cout << *p << std::endl;
... | For standard layout types, there is a note:
There might therefore be unnamed padding within a standard-layout struct object inserted by an implementation, but not at its beginning, as necessary to achieve appropriate alignment.
so there may be padding in between the members a and b.
Even if there's no padding, std::b... |
62,614,261 | 62,616,848 | Check if windows10 is installed C++ | I must check if windows 10 is installed on machine, because my program supports only win10.
I tried this solution that I already found on stackoverflow.
if (IsWindowsVersionOrGreater(10, 0, 0))
{
//nothing
}
else
{
MessageBox(NULL, "Your OS is not supported.", "Version Not Supported"... | Have you looked at GetVersionEx() function and OSVERSIONINFOEX structure?
Possible usage:
void print_os_info()
{
OSVERSIONINFOEX info;
ZeroMemory(&info, sizeof(OSVERSIONINFOEX));
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx(&info);
printf("Windows version: %u.%u\n", info.dwMajo... |
62,614,386 | 62,614,640 | Iterating over unordered_map of vectors | I know this is some basic stuff but I can't manage to iterate over an unordered_map of std::vectors and print the content of each vector. My unordered_map looks like this:
std::unordered_map<std::string, std::vector<int> > _dict;
And for now I can just print the first attribute of the map:
for (auto &it : _dict)
{
... | C++17: Structured binding declaration in a range-based for loop
As of C++17, you may use a structured binding declaration as the range declaration in a range-based for loop, along with std::copy and std::ostream_iterator to write the consecutive std::vector elements to std::cout:
#include <algorithm>
#include <iostream... |
62,614,421 | 62,615,411 | Is it possible to get pixels from OpenGL buffer at the original size? | I have a 4K project using OpenGL. So all my images are 4K based and it renders ok on my full-screen 1080p computer. OpenGL just resizes nicely without problems. But I want to use something like glReadPixels() to read the buffer but from the 4K origin. So far I couldn't figure out if this is even possible. Not sure what... | Use a framebuffer object to render your scene at the resolution you like and read back the data from there. If you still want the "live preview" in the window, just blit the FBO contents to your default framebuffer (and scale them down in that step).
|
62,614,886 | 62,615,103 | Is it more efficient to use array of pairs than using vector pair? | I was getting TLE when I was using a vector of pair as:
vector<pair<int,int>> v;
for(int i=0;i<n;++i)
v.push_back(make_pair(a,b));
sort(v.begin(),v.end());
and it got accepted when I changed the code to:
pair<int,int> v[n];
for(int i=0;i<n;++i)
{
v[i].first=a;
v[i].second=b;
}
sort(v,v+n);
I want to u... | In these lines
vector<pair<int,int>> v;
for(int i=0;i<n;++i)
v.push_back(make_pair(a,b))
you create a vector of std::pair<int,int>, and trying to put the element at the end of it while iterating n times. During these iterations, the v (vector of pairs), may undergo several reallocations as the std::vector::capaci... |
62,614,887 | 62,614,986 | Yes or No program for asking permission to rate an app | I am preety new in coding (like 2 weeks in) and I have been trying to make programs out of my mind to practice, so don't be so rough on me :D. What I tried today is to make a program that requires to insert a letter, because i have been playing with int function, so i wanted to change it a bit.
So I've been trying to m... | Things I've changed:
Changing responsetype from char to boolean
Changed the overall structures to a switch case instead of if-statement
Added getchar() on the end so the program doesn't automatically shut down at the end
#include <iostream>
int main() {
char Answer;
bool responsetype = false;
std::cout<<"Please r... |
62,614,915 | 62,616,097 | MSVC Find where a symbol is coming from | Situation:
I am using CI to compile a Windows version of my project using CMake and MSVC
It errors out right at the end complaining of two missing symbols (__std_system_error_allocate_message and __std_system_error_deallocate_message)
When I replicate the build process on my own computer, the build finishes fine and t... | @Richard Critten pointed me on the right path, the problem was due to having different versions of the MSVC toolchain on each system. GitLab's CI runners were using build tools version 16.2.3.0 while I was using a more recent 16.6.1.0. Uninstalling that and installing 16.2.3 from this page reproduced the error. Recompi... |
62,615,473 | 62,616,875 | C++ - Move assignment operator without custom swap function? | I'm reading Stroustrup's book (4th ed) and saw this example:
template<typename T, typename A = allocator<T>>
struct vector_base { // memory structure for vector
A alloc; // allocator
T* elem; // start of allocation
T* space; // end of element sequence, start of space a... | Looks like this is a duplicate of Usage of std::swap() inside move assignment should cause endless recursion (and causes), but it is an example from Stroustrup's book. Seems like Stroustrup does define a custom swap function; I seem to have missed it.
EDIT: I haven't found the swap function. Seems like it's a mistake o... |
62,615,834 | 62,622,370 | how to implement adding a price to an object without modifying the uml diagram c++ | I don't know how to implement adding a price to a menu so I don't change the uml chart.
Description of the requirements:
Abstract class Menu has a purely virtual method description().
Withlemon and Withcoffee contains a menu and method
description() that adds text “With lemon”, respectively “with
coffee”, in the descr... | Problems with the diagram
First, the diagram doesn't correspond to the narrative:
There is already a price and a getPrice(). You can therefore do exactly as with description(): just provide your own implementation.
Then, it doesn't show that description is purely virtual in Menu: the operation should have been shown... |
62,615,938 | 62,616,017 | Problem reading file and storing it in unordered_map | I'm trying to read a file and store it's content into an unordered_map but I've got a little problem. This is my unordered_map:
std::unordered_map<std::string, std::vector<double>> _users;
And this is the content of the file that I'm trying to read:
Mike 4 NA 8 NA NA
Lena NA 8 4 NA 9
I want to store the content in _u... | For your inner loop, you could do:
std::string stringval;
while (iss >> stringval)
{
double value;
try
{
value = std::stod (stringval);
}
catch (...)
{
value = 0.0;
}
dict[key].push_back(value);
}
|
62,616,223 | 62,623,161 | How to turn Variadic Templates into multiple single templates?(C++ Competitive Programming Debugging Template) | My debugging template is:
#define ts to_string
string ts(char c) { return string(1, c); }
string ts(bool b) { return b ? "true" : "false"; }
string ts(const char* s) { return (string)s; }
string ts(string s) { return s; }
template<class A> string ts(complex<A> c) {
stringstream ss; ss << c; return ss.str(); }
str... | Codeforces community has helped me and told me the correct solution.
#define ts to_string
string ts(char c) { return string(1, c); }
string ts(bool b) { return b ? "true" : "false"; }
string ts(const char* s) { return (string)s; }
string ts(string s) { return s; }
template<class A> string ts(complex<A> c) {
string... |
62,616,242 | 62,616,447 | ProjectileMovement does not work at second spawning | I'm doing a simple paddle game with Blueprints at first and C++ after.
I have the current workflow in my blueprint game mode:
And this is my code base on:
void APaddleGameGameMode::SpawnBall()
{
UWorld *world = GetWorld();
if (world)
{
Ref_GameBall = world->SpawnActorDeferred<APaddleGameBall>(APadd... | SpawnActorDeferred function defers the BeginPlay, giving a opportunity to the caller to set parameters beforehand, it means, the spawned actor if in a half-way to being full constructed(is a half actor) until the FinishSpawningActor function is called, wherever it is put; it means, a valid actor instance that didn't re... |
62,616,834 | 67,941,120 | vcruntime.h missing from Windows include folder? | I'm a beginner and I'm trying to build an open source project for the first time in Windows, but I keep running into file not found errors when building. What I've found so far is that a header file called corecrt.h is located at C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\. This file would include anot... | I too had the same issue, but found the cause which was the Include directories were not specified correctly. To fix this I did the following with Visual Studio:
Right click on the project name, and then click on Properties.
Under Configuration Properties, select VC++ Directories.
The Include directories should conta... |
62,616,855 | 62,617,313 | How to specify an application icon for C++ Visual Studio 2019? | I've seen this documentation for C#/Visual Basic application icons, but there is nothing I can find for how to do this with the C++ version.
This StackOverflow question is for Visual Studio 2008, not 2019. This one is also obsolete, as it works for Visual Studio 2017 but not Visual Studio 2019.
| After some fiddling I figured it out. This answer for VS2017 was basically correct, but it didn't fully explain what you have to do to get it to work and the documentation it links to was vague enough to confuse me, so I'll post this answer as the VS2019 version with full and complete easy-to-follow instructions.
Navi... |
62,616,994 | 62,617,032 | Shannon's Entropy Algorithm Returning negative values | note: project is in C, not C++
float entr = 0;
for(int i = 0; i < map->entry_count; ++i)
{
float x = (float)map->entry[i].occ / map->entry_count;
if(x > 0)
{
entr -= x * log(x) / log(2);
}
}
return entr;
when my map has 3 occurences of value 15, the entropy returned is -4.214.. something
when m... | The x in x * log(x) should be the probability of the item for x. That could be calculated as the number of times the item occurs divided by the total number of occurrences of items. But it is calculated as map->entry[i].occ / map->entry_count;, which appears to be the number of times the item occurs divided by the numb... |
62,617,106 | 62,627,259 | How to connect signal and slot with another object in qt --solved | I am doing a qt project, my goal is to draw something based on my input. The signal is in the main, and the drawing is in another object, I am not able to connect them.
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Frequency fre; //this is the class that does the drawing
QWidget *window =... | Since I can't put all this in the comment section, I'm going to put it here:
I copied your code and I'm not able to reproduce the error with Qt version 5.14.0, because when I change the value in any way, the method, void MyObject::setVolume(int value) is being called.
This code should work for you. Possibly, you are ru... |
62,617,297 | 62,617,317 | why is there a compiler warning for boolean switch statement? | why does the code below produce the warning:
"warning: switch condition has boolean value"
#include <iostream>
using namespace std;
int main() {
const bool yes = true;
switch (yes) {
case true: cout << "sure" << endl; break;
case false: cout << "nope" << endl;
}
retur... | My guess is that the compiler-writers wanted to warn you about potential mistakes like this:
char c;
[...]
switch(c==getchar()) // oops! Probably not what was intended
{
case 'a': cout << "you entered a" << endl; break; // will never be called
case 'b': cout << "you entered b" << endl; break; // will never... |
62,617,405 | 62,617,514 | Should I totally hide the internal class in my C++ header file when designing my SDK? | I am designing a SDK written in C++.
I have a question: could or should I totally hide the internal class in my public C++ header file?
The code snippets are like the following (in the header file MyPublicClass.h):
namespace PublicNamespace
{
namespace InternalNamespace
{
class MyInternalClass;
}
cla... | Don't use void or void * unless there is absolutely no alternative -- using void-pointers prevents the compiler from catching mistakes at compile-time, and leads to pain and suffering.
Using a clearly-labelled InternalNamespace should be good enough (assuming the programmers using your API aren't deliberately looking f... |
62,617,418 | 62,617,662 | Avoiding incrementing in if statement in C++ | I would like to avoid incrementing and decrementing in if-statement since there is a segmentation fault error in the following code while checking conditions (if we start with p = 1 and k = 1 for example):
if (((heights[k--][p--] < heights[k][p]) || (heights[k--][p--] == heights[k][p])) &&
((heights[k--][p++] ... | As others have indicated, replacing 'k--' with 'k-1' and 'k++' with 'k+1' for all 'k' and 'p' variables may resolve the segmentation error. 'k+1' is a reference to the next array index after 'k', while 'k++' increments the value of 'k' after it's used. It's also good programming practice to avoid using expressions as a... |
62,617,618 | 62,648,963 | /usr/bin/locale: source file is not valid UTF-8 | using g++ to compile cpp file in macOS.
macOS v10.15.4
Apple clang version 11.0.3 (clang-1103.0.32.62)
hello.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "hello word" << endl;
return 0;
}
in terminal I run:
g++ hello.cpp
| CPLUS_INCLUDE_PATH environment variable has an incorrect value.
Simple fix:
export CPLUS_INCLUDE_PATH=":/usr/local/include"
|
62,617,664 | 62,617,776 | Cpp thread object and shared_ptr issue | When I read the document in cppreference here
https://en.cppreference.com/w/cpp/memory/shared_ptr#Example
I am wondering what the possible value of the first lp.use_count() printed out is? I marked it with "<<<<<" in output content.
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mut... | I wouldn't rely on that value anyway.
In multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed load)
Check the reference for more information: https://en.cppreference.com/w/cpp/memory/shared_ptr/use_count
|
62,617,947 | 62,618,093 | Will an ostream flush other stream? | I'm curious about why I output by different ostream, and don't flush them, but when program exited, they won't mess up the order, does an ostream flush others stream?how C++ standard library make they communicate?
#include <iostream>
int main()
{
std::clog << "flush test1 by clog\n";
std::cout << "flush test1 ... | The clog stream is usually the same as the cerr stream, which is, depending on your library either line-buffer or not buffered meaning that at least after a line break (\n) it is written onto your terminal. cout on the other hand might be either fully buffered (only written if the buffer is full or flushed), line-buffe... |
62,617,956 | 62,618,403 | What this lines in bubble sort algorithm means? | In Introduction to programming with C++ 6th edition book, it explain the bubble sort algorithm with C++ and i understand it, but there is two lines of code I'm not understand why they in the code, when I tried to understand code I erase them and nothing changed and the algorithm still working.
So I still confused about... | To keep it simple,
1st pass of Bubble Sort => Maximum element in array gets the new appropriate position.
2nd pass => Second maximum element in array gets the new appropriate position.
.
.
.
Nth pass => Nth element in array gets the new appropriate position.
Variable lastSwap stores the maximum index of the array where... |
62,617,985 | 62,618,038 | how to solve this question without using extra space? | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
for(int i=0 ; i<matrix.size() ; ++i){
for(int j=0 ; matrix[i].size() ; ++j){
if(matrix[i][j]==0){
... | I guess you are trying to solve it in one pass, which is a good thing, but sometimes it would make the solution complicated.
This solution is pretty easy to understand, would pass through, and it does not require extra space, yet we would be doing it with multiple passes, which is totally fine because the time complexi... |
62,618,142 | 62,618,217 | Why does C++ programs return a code instead of the answer when it's too big? | I am coding a C++ program to calculate a math problem. I first write:
int x = 1
int y = 1
int z = 1
int answer = x * y * z
cout << answer << endl;
And when I build and run that, it prints 1. But when I do this:
int x = 1234;
int y = 5243;
int z = 1142;
int answer = x * y * z;
cout << answer << endl... | It's not a code, it's the value as stored in the integer result. You're experiencing integer overflow. An int can only hold values of a certain size, and when you exceed that size you end up with bit patters that aren't what you want but that are still storable in an int. Sometimes those bit patterns are the integer re... |
62,619,233 | 62,619,256 | How to define a boolean operator to compare an exact attribute of a class? | #include <cstring>
using namespace std;
class Student
{private:
char _name[20];
char _no[20];
int _score;
public:
Student(int score){_score = score;}
bool operator>(Student s);
};
bool Student::operator>(Student s, Student b)
{ return s._score > b._score;
};
int main() {
Student a(70);
S... | Operators inside the class take their first argument (if there are two arguments) from the class object itself.
Put the operator outside the class
bool operator>(Student s, Student b)
{
return s._score > b._score;
};
Or, the operator inside:
bool Student::operator>(Student b)
{
return _score > b._score;
};
|
62,619,273 | 62,622,063 | Errors during linking GLFW files | I have built GLFW from source and trying to build applications with it on Ubuntu Linux. But, g++ is always throwing errors about undefined references. I have followed many sites and posts, but they didn't solve my problem. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3... | I have followed this site and solved my problem. I had to use the command gcc -o glfw_prog glfw_prog.cpp $(pkg-config --static --libs glfw3) -lGLEW. I just had to add the extra -lGLEW flag along with the pkg-config search path.
More specifically, this is the complete and system-independent command:
gcc -o glfw_prog glf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.