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 |
|---|---|---|---|---|
67,042,800 | 67,042,908 | Base class parameter in a derived class' method | Here is my code:
class Base
{
virtual shared_ptr<Base> clone() const = 0;
};
class A : public Base
{
public:
A(const string &str) {
_str = str;
}
shared_ptr<Base> clone() const
{
return make_shared<A>(*this);
}
private:
string _str;
};
class B : public Base
{
public:
B() { ... |
How can I call this function with both class A and B?
Both std::shared_ptr<A> and std::shared_ptr<B> are convertible to std::shared_ptr<Base>, which is what your function expects, so providing a shared pointer will work.
test.AddToStorage("a", std::make_shared<A>("test1"));
test.AddToStorage("b", std::make_shared<A>(... |
67,043,181 | 67,043,359 | How to build a binary tree of unique_ptrs working around std::move? | I am currently trying to create a binary tree, each node of which contains a unique_ptr pointing to some other node in the tree. My question is one about design: I am not entirely sure how to write a recursive function that would build a tree like this without calling move on the pointers contained in the nodes in orde... |
The problem is, my appendChild() function involves a std::vector.push_back(), which requires the child passed in to be moved with std::move(). This is ok for now, the child node has been pushed into the tree at the right position. However, the child variable within this function is now a nullptr, and when I try to pas... |
67,043,810 | 67,043,905 | why we need different #include directives? | sorry, I'm an absolute rookie, I know my question is ignorant.
but I wonder why every time we need to use different #include directives to enable different supports from C++ library ??
Why not just let us use all supports from C++ library from the beginning?
| Separating things into multiple header files keeps things simpler for the compiler and linker. The more code they have to process, the longer the compilation process will take. You don't want them wasting efforts on code you are not interested in.
Also, using multiple header files is good for organization, keeping rela... |
67,043,931 | 67,045,309 | Should I put a C++ macro guard in every header file? | I am writing a little C project. Since I want it to also be included from C++ I thought about using C++ guards to make it work, like:
#ifdef __cplusplus
extern "C" {
#endif
// code
#ifdef __cplusplus
}
#endif
In my project I have some headers that must not be included directly from an eventual C++ file using the proje... |
must not be included directly from an eventual C++ file
Even if they are included indirectly via nested includes, C++ compilation will be applied and without the extern "C" the symbols in the C++ compiled modules will not be the same as those in the C compiled modules that you are linking to.
Apart from that it is go... |
67,044,140 | 67,044,257 | What does (x>>1)&1 result? | I'm working with bits and I don't understand this operator.
unsigned int number = 6;
number = (number>>1)&1;
The resulting value in number is 1 and I don't know why.
6 is 0110 in binary.
If I shift 1 position to the right the result is 0011, which is 3.
The value in number now is 1, which is the last bit in 0011. Does... | First you do a right shift operation. It shifts each bit in its left operand to the right. The number following the operator decides the number of places the bits are shifted.
0110 >> 1 = 0011
Then you perform a bitwise AND operation, which does a logical AND of the bits in each position of a number in its binary form... |
67,044,361 | 67,044,734 | How to specify a C++ pointer to a C function with unknown number of arguments? | I'm writing a C library which I would like to be usable from both C and C++. At one moment, it should take a callback from the user with 0-3 arguments, which will be called at some pointer later. Like this (a copy of the code is available as GitHub Gist too):
// app_c.c
#include <stdio.h>
#include "lib.h"
double f0(vo... | Rather than erase the number of arguments from the callback, you could retain it.
// lib.h
#ifndef LIB_H_
#define LIB_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int arity;
union {
void(*zero)(void);
void(*one)(double);
void(*two)(double, double);
void(*three)(do... |
67,044,496 | 67,044,575 | Deleting first node of a linear linked list | I came across the following code for deleting the first node of a linked list:
Node* removeFirstNode(struct Node* head)
{
if (head == NULL)
return NULL;
// Move the head pointer to the next node
Node* temp = head;
head = head->next;
delete temp;
return head;
}
Can someone expla... |
The temp pointer is needed because the memory for the first node in the linked list needs to be freed using delete after head is reassigned. This prevents a memory leak when calling the function.
The assignment head = head->next moves the beginning of the linked list to the second node, before the first node is delet... |
67,044,505 | 67,045,829 | How to determine if two pixels belong to the same line | I have two white lines on a black background. I need to input the coordinates of two white pixels and get an answer whether these pixels belong to the same line. Lines are one pixel wide.
| Given the constraints of this problem, you can just traverse the path between the two white pixels, summing how many white pixels there are between that path. If they are on the same line, you will sum a lot, otherwise, most of the path will be on the black. Also, you should normalize the sum by the path length, and co... |
67,044,851 | 67,047,569 | Android ndk-build error: undefined symbol: aligned_alloc | I am trying to build Shared Object (.so) files for the ImageMagick library however stuck due to following error while creating .so file
[arm64-v8a] Executable : magick
ld: error: undefined symbol: aligned_alloc
>>> referenced by memory.c:262 (././ImageMagick-7.0.9-17/MagickCore\memory.c:262)
>>> memor... | From the CI logs, it shows up
././ImageMagick-7.0.9-17/MagickCore/memory.c:262:10: warning: implicit declaration of function 'aligned_alloc' is invalid in C99 [-Wimplicit-function-declaration]
which finally ends up in the linker complaining for the missing symbol
ld: error: undefined symbol: aligned_alloc
Try adding ... |
67,044,868 | 67,050,198 | c++ vector one dimensional and two dimensional arrays value assignment | I am confused about c++ two dimensioanal vectors
#include <vector>
int main()
{
//First Code
std::vector<int> oneDimArray;
oneDimArray.push_back(5);
for (int i = 0; i < oneDimArray.size(); i++)
{
std::cout << oneDimArray[i];
}
//Second Code
std::vector<std::vector<int>> twoDimArr... | The reason this is happening is because of two reasons.
The vector you are trying to access is empty
You are trying to put an int into a vector that was supposed to hold vector<int>s.
Fixed code:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> oneDimArray;
oneDimArray.push_back(5);
for... |
67,044,915 | 67,044,998 | How to call a generic function with typename and non-typename template arguments? | I need to implement a function with the following prototype:
template<typename Iterator, size_t NBITS>
void radix_sort(Iterator first, Iterator last) {
// some code
}
If there wasn't the NBITS template argument, it would figure out by itself what Iterator is and I would call the function without the <>. Here I would... | With the current function template, you'll need to provide the Iterator template parameter explicitly if you also want to specify the size_t argument. You can do this by passing in the type of the first argument to the function
std::vector<int> v;
radix_sort<decltype(v.begin()), 42>(v.begin(), v.end());
To avoid havin... |
67,045,175 | 67,055,463 | CLion fails to give suggestions, syntax highlighting, etc | Preface; I am working on a university game project which, other than meaning there are parts of my source that I can't share, should make no difference to my issue. Code shown below has been pruned of (apparent) useless information.
The issue is most prevalent in the Play.cpp file:
#include "Play.h"
#include "../Engine... | It turns out that my Toolchain was configured to use a newer CMake version than CLion supports. Switching to the bundled version solved the issue.
|
67,045,212 | 67,104,405 | Using GDB on qtcreator-not supporting python scripting | I try to debug a trivial helloworld cpp project with qtcreator.
When I start debugging the project, I obtain an error saying:
The selected build of GDB does not support Python scripting.
It cannot be used in Qt Creator.
My system is debian9
My QT version is 5.14.2Here is my .pro file:
QT += widgets
TEMPLATE = app
SO... | As @Mark Plotnik (Thank you Mark) suggested, you have a gdb-minimal installed.
Running dpkg --get-selections | grep gdb, you should have an ouput like the following:
gdb-minimal install
gdbm-l10n install
libgdbm-compat4:amd64 install
libgdbm6:amd64 install
wireless-r... |
67,045,968 | 67,065,261 | Opening powershell with ShellExecuteEX results in the PS session not importing all available modules | Problem: Launching Powershell with ShellExecuteEx is not importing all of the available modules correctly. Or, at least that's how it's presenting. I need to understand why iot's not importing them correctly and how to make the mavailable when going through ShellExecuteEx.
My overall goal is to launch specific predefin... | If I install and import the module within the same command, it works fine. As I said in my update, I don't like or find this answer to be acceptable. It is an answer because it does work. I do hope that someone can assist by providing a better answer and or explanation.
QString example = "Install-Module -Name Microsoft... |
67,046,125 | 67,048,688 | Why there is no output from `cout` but it is ok for `printf` | To clear illustrate the problem, here is a minimal code. Why there is no output for my line cout << z << endl;? I am running it on Mac OS, compiler is Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin20.3.0
#include <iostream>
using namespace std;
int main() {
int x = 15;
int *y = &x;
u... | operator<< does not have an overload for an int* pointer, so the expression cout << y ends up calling the void* overload, which prints the memory address that the pointer is pointing at. It doesn't try to access the data being pointed at. Same with printf("%x", z).
operator<< does have an overload for an unsigned char... |
67,046,127 | 67,046,736 | Not getting output in case of string | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
s[0] = 'a';
cout << s << endl;
return 0;
}
I used this code and ran, but no output is coming don't know why?
But if am using s = ""; then also no output.
But when I use s = " "; then output comes why does this happen?
| You are using an uninitialized string, so assigning a to s[0] does nothing or does undefined behavior. To do this, you have to give s a size, as the options below:
Option 1: Resize
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
s.resize(10);
s[0] = 'a';
cout << s << endl;
retu... |
67,046,162 | 67,103,450 | C++ Class Constructor Arguments From Limited List | I am wondering what was the best way using C++ to make a class constructor take an argument from a limited list. For example, if I have a class called Colour, then the constructor would only accept Red, Green, or Blue and store the value to a private variable. Then I would have a method called printColour which would p... | Thanks for the help! In the end I decided to go with this code (below) because according to this link, ints are not implicitly converted to an enum value.
Code:
#include <iostream>
using namespace std;
typedef enum { C = 1, D = 6 } Options;
class MyClass
{
public:
MyClass(Options);
void printVal(void);
privat... |
67,046,429 | 67,046,611 | Undefined symbols for architecture x86_64 (I have found error, but I can not fix it.) | I know where error comes from. I have already marked it below the c++ code.
I have no idea about this error. Hope someone help me. How to fix this problem?
The error is:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits >&, Stack&)", referenced from:
Path(int, in... | This is a well-known problem with template friends. The problem it that a compiler treats a friend declaration as a non-template, but it is a template. If you insist on the out-of-class definition of operator<<, you can do the following:
template<class T>
class Stack;
template<class T>
std::ostream& operator<<(std::os... |
67,046,499 | 68,442,149 | How to add SWidgetSwitcher and get/set current widget index in Unreal Engine 4? | I'm trying to make a simple menu widget with Slate. I'm able to add canvas, buttons etc like SNew(SCanvas) but I am stuck with SNew(SWidgetSwitcher), on
how to use this and set the widget index. I'm new to this and havn't found much info on Google, so:
How to I add an SWidgetSwitcher and get/set current widget index in... | SNew(SWidgetSwitcher)
.WidgetIndex(this, &SMyUIWidget::GetCurrentTabIndex)
This might help you: https://nerivec.github.io/old-ue4-wiki/pages/slate-tabs.html
|
67,046,739 | 67,047,236 | Comparing Fortran & C++ assembler for int = floor(sqrt(...)) | I have implemented a function in Fortran and C++ each:
#include <math.h>
void dbl_sqrt_c(double *x, double *y){
*y = sqrt(*x - 1.0);
return;
}
pure subroutine my_dbl_sqrt(x,y) bind(c, name="dbl_sqrt_fort")
USE, INTRINSIC :: ISO_C_BINDING
implicit none
real(kind=c_double), intent(in) :: x
real(kind... | TL;DR: You're hobbled by bad defaults and compatibility with obsolete machines: Bad defaults are gcc setting errno for floating-point computations (despite this not being required by the C language), and compatibility with x86 machines that don't have any better SSE instructions than SSE2. If you want decent code gener... |
67,046,890 | 67,047,057 | How do ranges::views achieve O(1) complexity? | On the recently introduced to C++20 Ranges, I know that views achieve composability by using view adaptors. I also know that views don't own their elements and that their nature is lazy, that is to say they only do the actual computation when it's needed.
How do views achieve O(1) complexity on move, copy and assign op... | You recognize that views don't own the elements that they reference or manipulate. But you don't seem to understand that this is why these operations are O(1).
If you have this:
vector<int> v = {...};
auto *vptr = &v;
auto *vptr2 = vptr;
vptr = vptr2;
What is the complexity of the initialization of vref2 relative to ... |
67,047,150 | 67,047,209 | C++: Iterator error only for one of two identical cases | I'm looping over (almost) the same string object in exactly the same way, using iterators, and the second one keeps returning an error. I feel really stupid, am I missing something?
#include <string>
#include <vector>
using namespace std;
struct Sentence
{
string text;
Sentence(const string& text)
: text{te... | string str() const
As you can see here, your str() is declared as returning a std::string, but the actual code does not return anything.
This is called "undefined behavior", and you cannot expect any meaningful results from this point on.
You will need to fix this str() method so they its either declared as returnin... |
67,047,439 | 67,047,578 | Visual studio documentation for c++ | I have installed visual studio for c++
When i hover the mouse over a method or object, the studio offers to search the Internet for information about it. Is it possible to watch the documentation from ide, as in eclipse or intellij idea?
| Yes. on the help menu there is the "set help preference" sub-menu that allows you to switch to a local help viewer. To use that you will have to download documentation sets you find of interest.
|
67,047,662 | 67,047,827 | How to use the default argument in a function? | I have a function that has 2 optional parameters.
Sometimes I need only the 2nd parameter.
declaration:
void function(int a = 0, int b = 0);
call with 1st parameter:
function(10);
call with 2nd parameter only:
function(??,10);
How can I make the 2nd call valid?
The only way to do this, as far as I know, would be to ... | there is no way to do this the plain way, however you could use std::optional which will behave very close:
#include <optional>
void function(std::optional<int> optional_a = {}, std::optional<int> optional_b = {}) {
auto a = optional_a.value_or(0);
auto b = optional_b.value_or(0);
std::cout << a << " " << ... |
67,047,905 | 67,050,478 | C++: MSC not resolving a template operator (gcc and clang ok) | I have a question about a C++ operator overloading on template class and type which is not correctly resolved by Microsoft Visual C++ while it is accepted by gcc and clang (Linux and macOS).
I suspect that this is a bug in MSVC++ but I would like to get the advice of experts before reporting the bug, in case it could b... | If we're being pedantic, in C++17, non-type template arguments cannot have type void*, see [temp.param]/4.2:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
. . .
— pointer to object or pointer to function,
. . .
(Note: it has been rectified in C++20).
So it seems someth... |
67,048,068 | 67,048,452 | c++: Static variable defined in constructor | I'm curious about what is really happening "under the hood" here. I'm creating a Class with an ID variable automatically assigned when the constructor is called, depending on how many instances have been created in the past.
Class:
class MyClass{
int ID;
public:
MyClass(){
static int id{1}; // Seems to be redefin... | For all intents and purposes the behavior is the same as static member variables that are initialized at global scope, which you seem to grasp. The only difference I can see between the two is the scope, the static variable declared in the constructor is only avalilable at constructor scope, whereas a static variable d... |
67,048,242 | 67,048,276 | lambda returns incorrect values when variable is initialised inside lambda but not if initialised in outer scope | Given this code example:
#include <vector>
#include <cstdint>
#include <memory>
#include <iostream>
#include <functional>
enum StudentType { BURSARY, PAYING };
class Student {
public:
Student(const std::vector<int>& grades, StudentType type) : m_grades(grades), m_type(type) {}
uint8_t gradeByIndex(size_t ind... | The captured student variable is a reference to a local variable therefore your lambda has undefined behaviour if called after student goes out of scope. Capture by value to prevent this problem.
The captured entry is a reference to an element in StudentList so the lambda works correctly as long as the reference is sti... |
67,048,428 | 67,050,762 | Highligting widgets in QListWidget | I'm using a QListWidget as a selector of channels for an (somewhat modified) IRC client. I would like to indicate several things, such as unread messages, using QSS to style the entries. So far I have code like this:
class MainWindow : public QWidget {
QListWidgtet *channels;
MainWindow() {
channel... | You have to call polish() of the QStyle for the painting to be updated.
if(QWidget *current_widget = channels->itemWidget(current)){
current_widget->setProperty("selected", true);
current_widget->style()->polish(current_widget);
}
if (QWidget *previous_widget = channels->itemWidget(previous)){
previous_widg... |
67,048,448 | 67,049,396 | Puzzle Bubble SDL game (cascade algorithm) | I am making a puzzle bubble-like game in SDL and I am stuck on the mechanic that makes the bubbles fall when they get stuck in the air with no visible connections. Here is an example of what I mean. When I destroy the orange bubbles, all the others would fall.
All the bubbles in the grid (2D vector) have a struct that... | If you don't need the neighbours to be separate variables, it would be really easier to use some sort of a container instead:
std::list<Bobble*> neighbours;
or
std::vector<Bobble*> neighbours;
With the latter option you can acecss each neighbour easily by element index:
// the last enum element may be useful, or may ... |
67,049,119 | 67,062,936 | libzip zip_source_t buffer is freed even tho I told libzip not to | I face an issue with libzip and I don't know if I did something wrong of if it's a bug in the library.
First I create an archive with zip_source_buffer_create() from a zip file on disk (don't ask why I don't open the file directly).
I set the freep flag to 0 which is supposed to mean I will handle the buffer freeing my... | Don't handle zip archives created with WinRar with libzip............... (create them with libzip)
|
67,049,502 | 67,049,789 | Why modified reference does not change out of thread? | I am currently practising multi threading and memory management, and I am trying to implement the following: Multiple threads will push requests into a deque, and another thread will pop them and print them.
The function pusher gets references to : a mutex, a condition variable, a message deque, a flag indicating wheth... | The issue is here:
cond->wait(locker, [dq, flag]() {return (!dq->empty() && *flag == false); });
Even though dq, flag are references, the above captures them by-value. It's is the same issue for which you used std::ref() when starting the threads.
Change it to &dg, &flag and the code should work.
But you don't nee... |
67,049,689 | 67,054,020 | How do I fix an Invalid Comparator error? | MSVS 16.9.3
Win7-64
I get an invalid comparator error on the second execution of my sort comparator passed to the C++ Sort function provided in <algorithm>. I don't understand why I am getting this error! The sort routine call is:
sort(sorted.begin(), sorted.end(), remsort);
sorted is defined like this:
vector<ADI::RD... | Your comparison function does not fulfill the strict weak ordering requirements. See C++ named requirements: Compare.
In your specific case, you could implement it like this:
bool HOAReports::remsort(ADI::RDA_Asset* lhs, ADI::RDA_Asset* rhs) {
if(lhs->getRem() < rhs->getRem()) return true;
if(rhs->getRem() < lh... |
67,049,706 | 67,049,801 | Inheritance of public typedef with templates | I am trying to access a public typedef defined in the base (A) class from the inherited class (B).
But I still need to qualify the typename with A.
Is there a syntax to explicitely make mytype available to B without resorting to redundant trickery ?
template <typename T>
class A {
public:
typedef T mytype;
};
... | The reason for this is that unqualified lookup doesn’t find members of dependent base classes.
One solution would be to make the lookup qualified:
typename B::mytype
In order not to type this every time you can introduce an alias into B:
using mytype = typename B::mytype;
|
67,049,786 | 67,049,913 | hexa-decimal to decimal conversion (using implicit type casting) | I think there's some problem in my vs code I am new to this coding stuff even after writing the correct code it gives me wrong results in almost every second code I write i get uncertain results Plz guys help me with this , plz check running this code in your machine....
#include <iostream>
using namespace std;
int mai... | There are several problems with the code, but I think that the main one is that you are multiplying p by 8 when it should be 16 (as hex is base-16, not base-8).
You also should take care with invalid inputs. What happens if someone enters an invalid letter 'j' for instance?
Besides, when you calculate the initial lengt... |
67,049,812 | 67,049,966 | write a program that terminate whenever it either reads 10 number or a negative number |
Write a C++ program that reads from the keyboard up to 10 numbers, using a while loop with a SENTINEL, to count and add the positive values and then display the results. Your program should terminate whenever it either reads 10 number or a negative number. You assume at least there is one number.
This is what I've ... | Solution your problem:
#include <iostream>
using namespace std;
int main()
{
const int SENTINEL = 10;
int number;
int count = 0;
int sum = 0;
cout << "enter 10 random numbers" << endl;
while (cin >> number&&count != SENTINEL&&number>0)
{
sum = sum + number;
count++;
... |
67,050,015 | 67,050,341 | function return pointer to parent class from child class | i have this issue but i can't solve it. I only know the InitData function is 100% correct. However i try to find how need to create my classes to make this code work (without do any change to the InitData function)
class Bird
{
public:
int data[10];
int color;
Bird() {
ZeroMemory(data, 10 * 4);
... | Your inheritance is the wrong way around.
Also you don't need to replicate the data in the derived class, because this is what the baseclass is for, so you should call the appropriate constructor, instead of duplicating the code from your baseclass.
class Animal
{
public:
int data[10];
Animal()
{
Z... |
67,050,281 | 67,050,488 | Is there a cleaner way to write template function definitions? | A basic template class might look something like this:
Example.h
template<class T>
class Example {
public:
T doSomething();
};
Example.cpp
#include "Example.h"
template<class T>
T Example<T>::doSomething() {
// ...
return 0;
}
In a class this small, this is fine, but when dealing with larger classes, p... | By the sounds of it, the best option is just to write out everything in full. Unfortunate, but I suppose this is what find/replace is for. Additionally, the code in my question would give linker errors when used in context, unless function definitions were given in the header, or (I think) if template instances were ex... |
67,050,408 | 67,050,445 | Include file includes itself with guards | I have two header files, animation.h and hero.h,
here is the code for animation.h:
#include <SFML/Graphics.hpp>
#include <iostream>
#include "hero.h"
#ifndef ANIMATION
#define ANIMATION
//Class
#endif
And for hero.h:
#include <SFML/Graphics.hpp>
#include <iostream>
#include "animation.h"
#ifndef HERO
#define HERO
... | You should put the header guards before anything else.
On gcc and MSCyou can also use
#pragma once
instead. Probably also on other more modern compilers. Simpliy put this at the top of your include, instead of the #ifdef....
animation.h
#ifndef ANIMATION
#define ANIMATION
#include <SFML/Graphics.hpp>
#include <iostre... |
67,050,443 | 67,051,006 | How can I pass a state to the rebind_alloc constructor in STL? | Suppose I have a custom stateful allocator that I want to use for a STL container. The container is going to use the rebind_alloc trait to allocate its internal elements, thus by default (or by defining rebind<T>::other), I can ask it to use my allocator class for the internals as well.
However, I would like to pass th... | It was actually quite simple, the conversion constructor will be called if the container's constructor was given an allocator instance as argument. It is logical that the container's constructor has to know the allocator instance.
For example, if the container is not given any argument, the default constructor of the a... |
67,050,496 | 67,050,632 | Retrieving values from map <<object>, int> exhibits strange behavior | I am reproducing a problem I have with maps in a project, or which I implemented the following debugging code. I am having trouble retrieving the integer values in a map from Point2 objects as keys.
I have implemented the overloading of the Point2 objects as shown in the code. Point2 objects are ordered according to... | friend bool operator< (const Point2& p1, const Point2& p2 )
{
return p1._label < p2._label;
}
The defined strict weak ordering of this custom class, that's used as a key, in the map, compares each class instance's _label value in order to determine thir strict weak ordering.
The... |
67,051,515 | 67,051,579 | How to search for a word from array in a char string using strstr | my problem is with the strstr function, the string and the array that I want to compare this string against.
My initial code looked like this:
char t[255];
if (strstr(t, "test") || strstr(t, "test2") || strstr(t, "test3"))
{
// found
}
Where t looked something like this:
"xxxxxxx oooooo xxxxx testxxx test2xxxxxxxx... | sizeof(list)/sizeof(list) will always be 1, so you're only checking the first string in your list. However, that first string should still be found. You also don't need the second array index -- you could use just
const char *list[3] = { "test", "test1", "test2" };
int main() {
char t[255] = "xxxxxxx oooooo xxxx... |
67,051,707 | 67,051,731 | undefined reference to a function call | I am writing an image processing application in Vivado HLS with cpp. I am getting a error of saying undefined reference to ISP(a function call) I have seen this error multiple times and looked at similar cases in the stack overflow and was able to debug previously.Mostly it was a mismatch in the datatypes previously, b... | In your header, the declaration of this ISP function includes an int parameter:
int num_ctrl_pts
This parameter is either missing from the function's actual definition, or it is defined as a float instead of an int.
C++ allows functions to be overloaded, so as far as the C++ compiler is concerned this is some other co... |
67,051,835 | 67,052,352 | Calling glBindImageTexture() terminates program | My goal is to make use of compute shaders through C++ and OpenGL.
The problem is that when I call glBindImageTexture() after creating and initializing a texture, it just terminates the program. I tried checking everywhere what could be the culprit, but I could not trace it back.
I'm using glfw as my window and context ... | glBindImageTexture() is only available in GL 4.2+. Yet you're requesting a GL 3.3 context:
...
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "Hello"... |
67,052,287 | 67,052,609 | How can I convert a pointer stored in an std::string, back into a callable function? | I'm storing a pointer to a function as a string:
//callback = std::function<void()> callback
std::stringstream cbPtrToString;
cbPtrToString << &callback;
std::string prtString = cbPtrToString.str();
How can I convert prtString back into a callable function? I've tried this below, but it doesn't do what I thought it w... | Following your example, you have std::function<void()> as your callback. I would first suggest you make that a typedef and some simple conversion functions:
typedef std::function<void()> CallbackType;
std::string CallbackToString(const CallbackType* cb)
{
std::ostringstream oss;
oss << reinterpret_cast<uintpt... |
67,052,759 | 67,055,964 | C++ GDI+ how to draw rectangle with border radius | This is how I draw a rectangle using GDI+.
Graphics g(hdc);
SolidBrush blueColor((Color(255, 74, 134, 232)));
g.FillRectangle(&blueColor, x, y, width, height);
DeleteObject(&blueColor);
Now I want to add some border-radius, how can I do that?
| You can implement this function through GraphicsPath::AddArc and related APIs.
Some code that worked for me:
void GetRoundRectPath(GraphicsPath *pPath, Rect r, int dia)
{
// diameter can't exceed width or height
if(dia > r.Width) dia = r.Width;
if(dia > r.Height) dia = r.Height;
// define a corne... |
67,053,008 | 67,490,658 | folly IOThreadPoolExecutor vs CPUThreadPoolExecutor | I'm trying to learn more about the async abstractions used by this codebase I'm working on.
I'm reading Folly's documentation for two async executor pools in the library, IOThreadPoolExecutor for io bound tasks, and CPUThreadPoolExecutor for cpu bound tasks (https://github.com/facebook/folly/blob/master/folly/docs/Exec... | At a high level IPThreadPoolExecutors should be used only if you need a pool of EventBases. If you need a pool of workers, then use CPUThreadPoolExecutor.
CPUThreadPoolExecutor
Contains a series of priority queues which get constantly picked up by a series of workers. Each worker thread executes threadRun() after creat... |
67,053,535 | 67,053,961 | How to read file with different columns into vector then into class in c++? | I have file that contains
Name Age FavSport
"Michael", 18, Soccer, Cricket, Hockey
"John", 18, Cricket
"Mitchell", 19, Soccer, Hockey
(There are alot more lines of data in file)
I have created a class
class team
{
std::string name;
int age;
vector<std::string> favSport;
team(std::string name, int age, vector<s... | Try this. It works for me.
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
string name;
int age;
vector<string> favSport;
};
class Team {
public:
vector<Student> teamVec;
};
int main() {
std::string line;
std::vector<std::string> tea... |
67,054,346 | 67,054,347 | Why does puts() have a random trailing character when using a pointer only for certain values | This is the code
I know that I'm doing something wrong, but I cannot pin down what it is exactly.
#include <cstdio>
int main()
{
int n = 8;
char * string = new char[n];
for (int i = 0; i < n; i ++ )
{
string[i] = '#';
}
puts(pointer);
delete [] pointer;
return 0;
}
For n < 8, I do not run into ... | You require a trailing '\0', and the buffer must have room for it.
code should be:
#include <cstdio>
int main()
{
int n = 8;
char * pointer = new char[n+1];
for (int i = 0; i < n; i ++ )
{
pointer[i] = '#';
}
pointer[n] = '\0';// note this here, this is the line that does the work
puts(pointer);
... |
67,054,348 | 67,054,864 | C++ : Error while deducing types for templated function | I am trying to play around with type deduction in templates in c++. I am experimenting with type deduction for array arguments, with the following code:
template <typename T, std::size_t N>
constexpr std::size_t func(T (&)[N]) {
return N;
}
This will simply return the length of the input array, Like So:
char arr[]... | Syntax would be
template <typename T, std::size_t N>
constexpr std::size_t func(T (&arr)[N]);
You might use alias to have more natural syntax:
template <typename T, std::size_t N>
using CArray = T[N];
template <typename T, std::size_t N>
constexpr std::size_t func(CArray<T, N>& arr);
|
67,054,474 | 67,054,645 | Connect user custome function to modify VTK object with Qt Widgets | I'm currently working on the conversion of a project initially made under python, allowing to modify the visualization of a .vtk file with a Qt interface essentially made of sliders. The project under python is functional and can be consulted here :
[https://github.com/sebgra/VTK_modelisation/blob/master/Projet_Modelis... | Just use the new signal/slot syntax and a lambda...
QObject::connect(Slider_1, &QSlider::valueChanged,
[&Slider_1, &iren, &contour_bone](int value)
{
modif_1(&Slider_1, &contour_bone, &iren);
});
Note, though, that it might be simpler to just... |
67,055,003 | 67,055,059 | Convert LPSTR to LPCWSTR c++ | LPSTR a = LPSTR("hello");
how to convert a to LPCWSTR?
string in C++ are confusing me, why methods use LPCWSTR and not just LPSTR D:
I hope someone can provide a link where I can learn C++ strings
| LPSTR and LPCWSTR are Windows specific types. They are not c++ strings, but char pointers alias which are C.
The STL - Standard Template Library - which is shipped with C++ provides a std::string class, which is a convinient alias for basic_string<char, std::char_traits<char>, std::allocator<char>>. See the documentati... |
67,055,187 | 67,055,250 | What is the use of templates in cpp while the same task can be performed with function overloading? | Why C++ provides templates ? Same task can be done using function overloading. Is there any advantage of using templates over function overloading?
|
Same task can be done using function overloading
No, it can't
How do you write overloads for types that don't exist yet?
How do you write overloads for types that don't have a name?
How does function overloading help you write multiple similar classes?
And you'd still want templates
Why would you write the same imple... |
67,055,647 | 67,056,326 | How to user iter::product with parameter of length | In the code below, i want to get all products of length n, a parameter given to the function. Apparently, this product functions does not work with a parameter for the length. When I give an integer, the code does not complain.
I also want to iterate over all elements in the product and print them, but it says that it ... | iter::product<n> requires n be a compile-time constant, which it is not.
This library has an open issue about implementing a version that takes a runtime count of repeats.
A tuple is not something that you can loop over with for. The return value of a runtime-count product can't be a tuple, so don't worry about the sec... |
67,056,483 | 67,057,359 | Problem with 2D vector in c++ when printing | class Vertex {
public:
int dist, num;
vector<Vertex*> edges;
Vertex() {}
Vertex(int num) : num(num) {}
};
class K {
public:
void updateMatrix(vector<vector<int>>& matrix) {
vector<vector<Vertex>> vec;
for (vector<int> in : matrix) {
vector<Vertex> neu;
ve... | vec.push_back(neu); puts a copy of the (empty) variable neu into vec. Changes to neu after this don't affect the copy.
You should move that to after the inner loop.
|
67,056,667 | 67,057,049 | Building MinGW with Mingw-builds fails | I have been building mingw-w64 using mingw-builds (https://github.com/niXman/mingw-builds) successfully for a long time. Now I wanted to build g++ 10.3, but somehow it does not work anymore. I have found no related questions and I am not aware of any mailing list dealing with such issues.
I am working with mingw-builds... | There has been something wrong with my SSL certificates. I also have not been able to use pacman anymore. My attempts to fix the installation have failed, therefore I have reinstalled msys2. Now it works like a charm.
|
67,057,387 | 67,057,488 | How do I use dynamically sized data structures that are persistent in memory | I'm working on building a range minimum query program in C++ but I'm having a hard time working with dynamically sized vectors that are used throughout the program. Right now I am using a size_t** to make a 2d array of indexes to an array of elements, but it's not very nice to work with. I would much rather leverage ex... | The key to replacing your current explicit memory handling with std::vector, you don't need the allocation loop.
All you need is e.g.
table = std::vector<std::vector<size_t>>(numElems, std::vector<size_t>(numElems));
That will create a vector of vectors, with all sizes already set and all elements allocated and zero-i... |
67,057,724 | 67,057,885 | What is the purpose of sized array as function argument is c and c++? | Consider the following functions:
void func1(int unsized_array[]){}
void func2(int sized_array[10]){}
void func3(int *pointer){}
According to the result of:
std::cout << std::is_same<decltype(func1), decltype(func2)>::value << std::endl;
std::cout << std::is_same<decltype(func2), decltype(func3)>::value << std... |
Since array declarators generally may have size expressions (as when defining an array other than in a parameter or when declaring a parameter that contains an array as a sub-part, such as a pointer to an array), it would take more work to exclude it from the grammar than to leave it in harmlessly. (There are numerous... |
67,058,057 | 67,058,642 | std::bitset constexpr >64bit value | I want to have a bitset constexpr variable in my program. bitset can have unsigned long long value as a constructor which is 64bit value, I need 100 bit value. As per this Q&A, we can use constructor that takes a string as an argument and initialize it that way, but it won't be constexpr value.
Is there any possible wa... | the constructor std::bitset<N>(uint64_t) is the only useful constexpr callable constructor here:
constexpr bitset(unsigned long long _Val) noexcept : _Array{static_cast<_Ty>(_Need_mask ? _Val & _Mask : _Val)} {}
and that will only provide 64 bits of information.
But since it is possible to initalize a std::bitset at c... |
67,058,179 | 67,058,378 | wordexp_t fails when folder contains a space | My code:
QString clsDebugService::strGetUserFolder(QString strFolder) {
QString strCopy(strFolder);
if ( strCopy.isEmpty() ) {
strCopy = "~";
}
const QChar cqcSeperator(QDir::separator());
QString strFullPath;
//Ensure path is correct before use, this will handle translation of ~ if used... | The actually fix for this:
QString clsDebugService::strGetUserFolder(QString strFolder) {
QString strCopy(strFolder);
if ( strCopy.indexOf(" ") != -1 ) {
//Ensure any spaces in the path are escaped
strCopy.replace(" ", "\\ ");
} else if ( strCopy.isEmpty() ) {
strCopy = "~";
}
co... |
67,058,567 | 67,058,959 | Why is it necessary to use the friend modifier for overloading the * operator in C++? | I have decided to implement the matrix operations as an exercise during my C++ studying. I have chosen the approach based on the templated class (to avoid dynamic memory allocation) and operators overloading
#include <cstdint>
#include <iostream>
template<class T, uint8_t ROWS, uint8_t COLUMNS>
class Matrix {
publ... | For binary operation XXX, such as lhs XXX rhs,
Free function syntax would be Ret operator XXX(const LHS&, const RHS&)
(When defined within a class, it should be friend)
For member method of LHS, it would be Ret LHS::operator XXX(RHS) const
(when defined within the class, LHS:: should be omitted)
With friend, you declar... |
67,058,579 | 67,059,019 | Get QVariantMap from QVariant(QVariantList) | I have QVariant(QVariantList), in that some QVariantMap. How can I pull QVariantMap from QVariantList?
| Assuming your QVariant is called my_variant, you can extract its content the following way:
// Get the list (since the underlying type of my_variant is QVariantList)
QVariantList va_list = my_variant.toList();
for(int i = 0; i < va_list.size(); ++i)
{
// Get the map
QVariantMap va_map = va_list[i].toMap();
... |
67,058,651 | 67,059,514 | Trying to initialize a linked list using array | I need to define a class of linked list,List, in a way such that object of class can be defined in two ways,
List obj1 = L1();//head=0
List obj2 = L2(given_arr[], size of array) // I would be given an array, whose elements are elements of list
so, I need to form a construter for both,
for obj1, Its easy.
List(){head=0... | Make these changes to your main().
int main() {
int barr[] = {9, 89, 0, 43}; // No need to specify size if you're initializing
// List* M = new List(); // unused
// Your array is barr, barr[4] makes no sense. You also don't allocate the List,
// the list allocates
List L = List(barr, sizeof(barr) / siz... |
67,058,698 | 67,059,155 | C++ is giving different wrong results for same arithmetic expression | I have a very simple calculation where I calculate the distance between each individual cell to center in a 2D space. I know that the O(n) solution is redundant and I derived the formula for O(1) solution. But what I am trying to understand is: Why do these two analogous calculations give me two different results?
Her... | Typical int (signed 32bit) can store only upto 2,147,483,647 (2**31 - 1).
The calculation of ii*ii will exceed this limit when ii becomes larger than 46340.
You are using unsigned long long for result, so casting to that before calculation will improve the behavior.
#include <iostream>
using namespace std;
int main()
{... |
67,058,894 | 67,069,844 | Boost.log - Get current file name when using file rotation | I know that this question may be a duplicate but I want to know whether there is still no possibility to get the current log file name when there is a file backend with filename rotation?!
Thanks in advance.
Edit:
With filename rotation I mean something like the following where the filename changes when the log file ge... | As sehe mentioned:
It's a property of the backend.
Therefor I managed to separate the sink initialization from the corresponding backend:
typedef sinks::synchronous_sink<sinks::text_file_backend> fileSink;
boost::shared_ptr<fileSink> fileSinkSink;
fileSinkSink = logging::add_file_log(
keywords::file_name = "..\\L... |
67,059,221 | 67,061,351 | Why does this C++ function not output what I want? | #include <iostream.h>
using namespace std;
int main() {
int i, n = 5, k, a;
cin >> k;
cin >> a;
int v[] = { 1,2,3,4,5 };
for (i = 0; i < n; i++) {
v[i] = i + 1;
}
for (i = n; i >= k - 1; i--) {
v[i + 1] = v[i];
}
v[k - 1] = a;
for (i = 0; i < n + 1; i++) {
... | The first loop is redundant, v is already set to { 1, 2, 3, 4, 5}.
The second loop has a buffer overflow. "i" starts at 5, so v[i+1] tries to access the sixth array element, however the array has only indexes zero to four (five elements).
Finally, for the "v[k - 1] = a" statement, since k=2 and a=10, this puts 10 at i... |
67,059,699 | 67,059,796 | error: ‘Namefunction’ was not declared in this scope | I am new to C++ and I had problems with running this small example of inputing number of rectangle that we want to calculate the area each every one of them.
Here is my code:
#include<iostream>
#include<conio.h>
using namespace std;
class Rectangle{
private:
float length;
float width;
public:
void input()
... | Member functions must be called using the dot. You'll have to loop over your objects:
int main()
{
Rectangle a[30];
int n;
cout<<"input n:"; cin>>n;
cout<<"Input all Rectangle data:"<<endl;
for (auto& r : a) {
r.inputAll(a,n);
}
cout<<"Output all Rectangle data:"<<endl;
for (auto& r : a) {
r.out... |
67,059,884 | 67,060,003 | Why clang-tidy suggests to add [[nodiscard]] everywhere? | I have a C++ project where clang-tidy is suggesting to add [[nodiscard]] everywhere. Is this a good practice ? The understanding I have is that [[nodiscard]] should be used only when ignoring the return value could be fatal for program. I have an object Car and it has a member const unsigned int m_ID. Should the getter... | This option is apparently "modernize-use-nodiscard", so you can deactivate that if you prefer.
It should be noted that the rules this option outlines are not the rules the C++ standard committee themselves use for when to apply [[nodiscard]]. Those rules being:
It should be added where:
For existing API’s
not using ... |
67,060,183 | 67,068,324 | Eigen3: Cast Dynamic Matrix to Static Matrix | is possible to cast a dynamic matrix to a static one and if yes what woud be the best solution?
Example:
Eigen::MatrixXd a = Eigen::Matrixxd::Zero(4,4);
to
Eigen::Matrix<double, a.rows(), a.cols()> b = a; //?
Cheers!
| From documentation.
The three mandatory template parameters of Matrix are:
Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>.
RowsAtCompileTime and ColsAtCompileTime are the number of rows and columns of the > matrix as known at compile time
When you use Eigen::MatrixXd,
The RowsAtCompileTime and... |
67,060,186 | 67,060,251 | C++ Can I write a function within an expression? | I'm writing a (my own language) to C++ transpiler. I'd like to be able to offer a kind of virtual sub function that is transpiled into being part of the C++ code in the same scope in which it is called.
Here is an example of the type of C++ code I'd want to generate:
if (a == {if (getValue(d) == 5) { long r = next(); n... | If I correctly get what you are doing, you can simply use lambda expression here. This of course requires C++11
if (a ==
[&] () {
if (getValue(d) == 5) {
long r = next();
next();
return r;
} else {
return 0;
}
}()) {
dosomething();
}... |
67,060,619 | 67,073,177 | Rationale for explicit conversion function on functor | While I was on a short break, my workplace switched to using a static code analyzer.
They ran it over the project I am working on and one particular problem flagged by the analyzer goes like this (simplified example):
struct calcSomething
{
int result;
calcSomething() : result(0) {}
void operator()(const ... | I would do away with any conversion operators altogether. What's wrong with:
int result = std::for_each(...).get();
where get() does the same as your current operator int.
You know that the result of for_each is not an integer, it's your function object. Why, why would you want to avoid making the conversion from a f... |
67,060,812 | 67,061,523 | reinterpret_cast to know the type of the event at compilation time | I have an application based on events.
The issue is that I have a lot of different types of events and some classes listen a lot.
Currently, when I want to receive an event, I create a function taking the type of message as a parameter and I subscribe to it.
I would like to have a single function which receives all the... | You want to have one event queue that handles different kinds of events. I get it, you can see this kind of thing with C# objects that have a bajillion customization hooks with different arguments; they have one subscription system for all of them, and cast to make sure that the types agree.
If you want a central bott... |
67,060,846 | 67,060,911 | Segmentation fault(core dumped) in CPP | I am confused a bit. I narrowed down it to:
Why having this line:
Node *root, *rootSafe = NULL;
give error:
Segmentation fault(core dumped)
While just switching it like below:
Node *rootSafe, *root = NULL;
runs perfect.
Here is the code, you can test.
#include <iostream>
using namespace std;
struct Node{
int data;... | Without fiddling with your code, I think this:
Node *root, *rootSafe = NULL;
Doesn't do what you think it does. Do you think it sets both to NULL? It doesn't. root gets some random value and rootSafe gets NULL.
This might be what you really want:
Node *root = NULL, *rootSafe = NULL;
Frankly, I personally hate (and it... |
67,060,885 | 67,071,629 | how do I configure VS code to build in Release mode (clang + macOS) | I am new to VS code. I have configured it using Clang on macOS using the provided [VS code documentation] (https://code.visualstudio.com/docs/cpp/config-clang-mac)
It works, I can build and debug. Great!
My question is: how do I configure VS Code to build in Release mode? I don't seem to be able to find any info in the... | Sorry, for the last answer...
So first of all, I need to claim that I'm not really familiar to Clang Family, but I did some research and found that there are two special groups out in tasks.json which VSCode provides: Build and Test. So, I guess that we need to build it in release mode manually where again I don't have... |
67,061,058 | 67,061,886 | Why pointer to pointer was used in the code? | Why pointer to pointer has been used rather than single pointer in the code? Also do you think the destructor was written wrong if it is how can i make it correct?
pointer to pointer: employee** _arr;
You can see the code below:
#include<iostream>
class employee {
private:
std::string _name;
std::string _surn... |
Why pointer to pointer was used in the code?
This is known only by the author who wrote the code. We can make a reasonable guess that their intention may have been to:
Allocate a dynamic array of objects, using a bare pointer to the first element of that array.
Indirectly point to objects stored elsewhere, hence th... |
67,061,064 | 67,061,118 | Printing character pointer versus printing character by dereferencing | char c = 'a';
char* p = &c;
cout << p << endl;
cout << *p << endl;
This is a code written in C++ language.
Why in the first cout statement the program tries to print until it finds a null character and in the second statement it just prints a single character?
| In C++, pointers to char are often considered a "C string" by convention -- which is a null-terminated string of chars. This is an expected convention in much of the C++ standard library -- and this holds true in std::ostream as well.
In particular, in your two calls:
The pointer p will call std::ostream's operator<<(... |
67,061,682 | 67,062,585 | How to read file into class in C++? | I am reading File that contains
Boss, level, Specials,
"FireMen", 3, "Flame,Thrower", Fire,Breath
"Medusa", 6, "Snake,Poison"
"Hype", 10, "One,punch,Knock", Fly,Kick, "Dragon,Breath"
I am trying to read it into class with objects boss, level and specials
I am having problem read... | This code reads your file and stores the data in the std::vector Info using stringstreams and other things to parse.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
class Boss {
std::string Name;
int Level;
std::vector<... |
67,061,856 | 67,061,985 | Strange behaviour in C++ | template <typename T> T& larger(T& a, T& b)
{
return (a>b?a:b);
}
std::string first {"vv"};
std::string second {"That is the question in californian"};
int main(){
std::cout << larger(first,second) << std::endl;
}
This should return [if a greater than b , then a , else b ]; but it returns a for me .("vv")... | operator< compares lexicographically for std::string. This means that it compares character by character, starting from the first, and only if they are equal, it compares the next one.
As you can easily verify, it holds that 'v' > 'T'. That is because lowercase letters come after uppercase letters in ASCII encoding.
|
67,062,207 | 67,064,448 | How to pan audio sample data naturally? | I'm developing Flutter plugin which is targeting only Android for now. It's kind of synthesis thing; Users can load audio file into memory, and they can adjust pitch (not pitch shift) and play multiple sound with the least delay using audio library called Oboe.
I managed to get PCM data from audio files which MediaCode... | Pan rules or pan laws are implemented a bit different from manufacturer to manufacturer.
One implementation that is frequently used is that when sounds are panned fully to one side, that side is played at full volume, where as the other side is attenuated fully. if the sound is played at center, both sides are attenuat... |
67,062,409 | 67,062,866 | Why is variable declared in an if-statement still in scope in else block? | Consider this code:
if (int* p = nullptr) {
}
else {
std::cout << *p << std::endl;
}
This compiles with clang 7.0.1 with -std=c++17, -Wall, -Wextra and -pedantic-errors without a single warning generated.
I've got two questions:
How is this possible? I always thought that scope of such variables ends with the if-... |
Why is variable declared in an if-statement still in scope in else block?
Because the standard says that it is. It was designed so presumably because it is useful.
How is this possible?
It's unclear why it wouldn't be possible.
I always thought that scope of such variables ends with the if-block.
You assumed wr... |
67,062,435 | 67,064,306 | Strange segfault in unique_ptr | After a small modification in my code I encountered a segfault while running it and I can't figure out why.
Here is the code working :
std::shared_ptr<UCHAR> myClass::myMethod(const char *str)
{
size_t strLen = strlen(str);
ULONG paddedLen = (strLen % this->bufferLen)
? ((strLen / blockSize) + 1) * this... |
std::unique_ptr<UCHAR> padded = std::make_unique<UCHAR>(paddedLen + 1); <-- Added +1 here
std::unique_ptr<UCHAR> buffer = std::make_unique<UCHAR>(this->bufferLen); <---Crashes here
You are allocating single UCHARs each time, whose values are paddedLen + 1 and this->bufferLen, respectively. You want arrays whose le... |
67,063,120 | 67,063,450 | The strcpy_s function doesn't work in my code | This function is supposed to copy a char[] into the allocated storage. For some reason the buffer is always too small for this operation.
str(char* f) {
len = strlen(f);
txt = (char*)malloc(len); //txt is a pointer to a char
strcpy_s(txt, len, f);
}
|
For some reason the buffer is always too small for this operation.
You forgot to allocate memory for the null terminator. An empty string requires space for one character (the terminator). A string of length one requires space for two characters (1 + 1). A string of length len requires space for len + 1 characters.
T... |
67,063,189 | 67,063,602 | How to change the mouse cursor to something else in c++? | How can I change the mouse cursor to something else in c++, Windows? I mean, change the pointer to another system default, for example, the hand icon.
I don't know what code I can provide you, since I don't really have anything for the mouse. The only thing I have for the mouse, that isn't in use, is to hide it. If thi... | Use SDL_SetCursor If you want a system cursor, you can pass the return value of SDL_CreateSystemCursor to that function. See the documentation:
https://wiki.libsdl.org/SDL_SetCursor
https://wiki.libsdl.org/SDL_CreateSystemCursor
https://web.archive.org/web/20210211163214/https://wiki.libsdl.org/SDL_CreateSystemCursor
T... |
67,063,594 | 67,064,381 | Can I use Q_PROPERTY or Q_INVOKE in class that no derivered from QObject? | So I need to use some macroses to integrate my c++ code with qml but I really dont know if I can use Q_PROPERTY or Q_INVOKE without derivering my class from QObject and without using Q_OBJECT macros.
| Yes, it is possible to put Q_PROPERTY in a struct, when also declaring it as a Q_GADGET, but without changed-signals. And according to Exposing Q_INVOKABLE in Q_GADGET to QML it also seems possible to put a Q_INVOKABLE on a Q_GADGET.
|
67,063,641 | 67,064,520 | Are Rust smart pointers std::rc::Rc and std::sync::Arc analogous to the C++ smart pointers std::shared_ptr and std::atomic_shared_ptr respectively? | Is there analogy between Rust smart pointers std::rc::Rc and std::sync::Arc with the C++ smart pointers std::shared_ptr and std::atomic_shared_ptr? For me, they look the same, but probably there are some implementation nuances. For example in C++ std::shared_ptr the reference count in the control block is atomic despit... | Rust's Arc<T> is largely equivalent to C++'s shared_ptr<T>
Both are "smart pointers" that provide shared ownership of a value via reference counting. They both use atomics for internal operations so that ownership can be tracked between threads safely.
One notable difference is the C++ std::shared_ptr implementation pr... |
67,064,876 | 67,065,211 | how endl mainly affects fully buffered streams? | https://www.cplusplus.com/doc/tutorial/basic_io/
In the following site, just before cin heading, it is stated that
The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an additional behavior: the stream's buffer (if any) is flushed, which means that the output is re... | There are three main buffering strategies used for output streams:
No buffering - Every write to the stream is immediately written to the underlying output device.
Line buffering - Writes to the stream are stored in memory until a newline character is written or the buffer is full, at which point the buffer is flushed... |
67,065,286 | 67,065,554 | How do I enable a template base upon comparison of values? | I am trying to figure out how to "enable" a templated method based upon the comparison between two template arguments.
For example:
enum class LoggerLevel {
FATAL = 0,
ERROR = 1,
WARNING = 2
};
template <LoggerLevel LOGGER_LEVEL>
class Logger {
public:
template <LoggerLevel LEVEL>
void log(const ch... | Something like this. Desired behavior could be achieved by using std::enable_if when overloads are enabled or disabled based on log level.
#include <iostream>
#include <type_traits>
enum LogLevel {
FATAL = 0,
ERROR = 1,
WARNING = 2
};
template <LogLevel LOGGER_LEVEL>
class Logger {
public:
template <L... |
67,065,428 | 67,065,738 | Virtual function calling a non-virtual function and vice versa | I have a class A as a base class of class B.
I have called the non-virtual function, abc(), within my virtual function, xyz(), as mentioned below.
Due to run-time polymorphism, B:xyz is called – I understand this.
However, I don't understand, why was it followed by B:abc and not A:abc, as abc is a non-virtual function.... | Calls to your non-virtual abc function are resolved, effectively, at compile time: so, when that is called from within another member function of class B, the class B version of the function is called, and is passed a pointer (this) to the object from which it is being called; similarly, if called from within a class A... |
67,065,762 | 67,066,142 | What are constant members in C++? | class Foo
{
public:
const int a;
const int* x;
int* const y;
Foo() : a{ 0 }, y{ new int(20) } {
x = new int(10);
}
};
int main()
{
Foo f;
// f.a = 100; // cannot
f.x = new int(100);
// f.y = new int(100); // cannot
}
When const int a is defined as fields of a class,
it is ... | The "const int* x" is a (non-const) pointer to a const int. Since x is non-const, it need not be initialized upon construction.
Here are some examples:
class C
{
public:
C() :
const_int(1),
const_int_again(2),
const_ptr_to_non_const_int(nullptr),
const_ptr_to_const_int(nullptr)
{}
priv... |
67,065,863 | 67,066,011 | How do I edit the source files of a c++ project in Visual Studio? | I know this seems like a strange question, but apparently the answer isn't a simple as "Open it in Visual Studio and edit it".
I have an idea for this project, and I would like to try my hand at implementing it.
Despite appearances, I do have a background in programming, just not much in c++. I do a lot of .Net stuff d... | CMake is used to build the project, that is compile and link the needed files to make the executables/libraries. As with many open source projects, you are left to your own devices to use it in an IDE. This has the advantage every contributor can use their own prefered environment. It has the disadvantage that it can b... |
67,065,994 | 67,066,846 | How to store a position in an array and use for later in c++? | I have an array that displays like this:
I want the items in the array to be saved to be replaced later. (the "@" symbol is the player)
The controls work by replacing the players current position with a '.' and replacing the next '.' with the '@' symbol according to which direction the player is moving. Here's the cod... | You already store the position of the player in x and y, so you know how to do this. The position of E is constant, so you can reflect that by using const int variables. Before your loop:
int main()
{
const int e_x = 5; // Please note I haven't counted this, I leave that to you
const int e_y = 15; // These shou... |
67,067,129 | 67,067,187 | what happens in memory for move in C++ | I am reading c++ primer move section and confused about the move implementation.
Let us say we have one vector that has 4 elements that occupy 4 consecutive memory locations.
MEM[0~3]. The capacity of the vector is 4.
Assuming MEM[4] is now not available as it is occupied by another thread or program or due to whatever... | This is completely outside the scope of the C++ standard.
There's nothing in the standard that prohibits this optimization. It's certainly possible that a particular C++ implementation determines that the std::vector that already used up its reserve()d capacity can be expanded without allocating larger storage and movi... |
67,067,409 | 67,067,508 | Re-initializing random distribution | Is it reasonable to expect that a distribution from <random> re-initialized before each next number request behaves the same way as if it was initialized once? In other words, does this:
std::default_random_engine generator;
int p[10]={};
for (int i=0; i<nrolls; ++i) {
std::uniform_int_distribution<int> distribution(0... | I essentially do what your first implementation does. Construct one every time I need a distribution.
That said, yes, the behavior of the different distributions are guaranteed by the standard to behave in specific ways.
STL recommends, that since distributions are relatively cheap, don't worry about constructing one e... |
67,067,459 | 67,067,792 | C++ Extract integers from text file and make a vector | I am trying to make an integer vector by extracting integers from the text file.
In the file, there are 10 numbers separated by a comma.
1,2,3,4,5,6,7,8,9,10
Like this.And my code is below
int main()
{
ifstream read;
read.open("input.txt");
vector<int> arr;
if (read)
{
int value;
wh... | Here is a simple example for doing the work
#include<fstream>
#include<vector>
int main() {
std::ifstream read("input.txt");
std::vector<int> arr;
if(read) {
int value;
while(read >> vlaue) {
arr.push_back(value);
read.get(); //ignore the separator character
... |
67,067,460 | 67,067,526 | error on gcc not clang: cannot convert from '<brace-enclosed initializer list>' to 'std::vector<> | The following code produces an error only with gcc:
could not convert '{{"John", 32}, {"Theo", 23}, {"Aun", 43}, {"Vivien", 67}}' from '<brace-enclosed initializer list>' to 'std::vector<Person>'
{"Vivien", 67}};
#include <vector>
struct Person{
//const char* name; // <-- Compiles... | This is likely due to literal strings being const char* to char[], and therefore without an implicit constructor, the correct aggregate initializer may not be known, and if you want a quick way to compile this with GCC, either do one of the following:
std::vector<Person> parr1 = {
Person {"John", 32},
Person {"... |
67,067,516 | 67,067,582 | Why does assigning an int to a std::variant<long int, ...> fail? | I feel like I'm missing something obvious about int type promotion when assigning to a variant.
On gcc version 9.3.0 (Ubuntu 9.3.0-11ubuntu0~18.04.1), compiling with -std=c++17, the following code fails to compile:
#include <variant>
#include <iostream>
int main()
{
std::variant<long int, bool> v; // works fi... | Assigning to a variant does not simply assign to the currently active type in the variant. Instead, the type of the right hand side is used to determine which of the possible types (the alternatives) is the best match for the right hand side. Then, that type is assigned to.
Thus, v = 1; does not automatically assign to... |
67,067,913 | 67,080,654 | binding c++ class I'm not able to find the constructor | I'm working on binding a simple c++ class into javascript. I'm doing this via Emscripten 2.0.17.
I bound hello_world.cpp
#include <iostream>
class hello {
public:
hello() { std::cout << "Hello world!!!\n"; }
};
#include <emscripten/bind.h>
namespace emcc = emscripten;
EMSCRIPTEN_BINDINGS(jshello)... | Exposing a class with Emscripten
If you want to expose a C++ class with Emscripten you need these steps, write your C++ code:
// hello_world.cpp
#include <iostream>
class Hello {
public:
Hello() {
std::cout << "Hello world!!!\n" << std::endl;
}
void saySomething() {
std::cou... |
67,068,169 | 67,068,214 | How to fix code that is outputting 2 lines instead of one using if statements | My code compiles and when I run it and enter a number, then it will output 2 lines of code instead of one. I'm not sure if there is something wrong with my if-statement that is causing it. But I want to know what it causing my program to output 2 lines instead of 1 with if-statements?
#include <iostream>
#include <fstr... | Replace the or || with and &&
if (weight >= 1 && weight < 10) {// der code}
|
67,068,389 | 67,068,659 | why can't i use the value of area in volume? i get Volume: -1405824736 | To Create a class called Rectangle with length breadth and area.Use appropriate member function to read length and breadth from the user and to calculate area of a rectangle. Create a derived class called Box form the class rectangle.Use appropriate member function to read height and calculate volume.
#include <iostrea... | Your surprise at the output of your program indicates to me that you think the object r and the Rectangle sub-object of b are somehow the same thing. They are not.
Your code suffers from the following problems.
You are not initializing the member variables of the classes properly.
Box::input is not accurate. It needs ... |
67,068,441 | 67,069,194 | Why does `iota(0) | take(0)` not model ranges::sized_range in C++20? | Consider the following code snippet:
#include <ranges>
auto r = std::views::iota(0) | std::views::take(0);
static_assert(std::ranges::sized_range<decltype(r)>);
gcc-trunk rejects it for required-expression std::ranges::size(r) is invalid. Why does r not model ranges::sized_range, i,e, why can't I use std::ranges::siz... | views::take only yields a sized range if the given range itself was sized. And views::iota isn't a sized range unless you use one of the two-element constructors that give it a size. Which you did not.
As for why take_view is only sized if the underlying iterator is sized, this is because take_view stops when the numbe... |
67,068,485 | 67,068,530 | macro in template class not work as I expected | I have a macro defined in a template class to use the real class Name.
It may be not clear, and the code is below:
#include <iostream>
void Test_CB()
{
}
#define TEST_INTERFACE(xx) Test_##xx()
template <class T>
class CA
{
public:
void Write()
{
TEST_INTERFACE(T);
}
};
class CB : public CA<CB>... | This is because template resolution happens during compile phase and pre-processor directives are resolved before compilation. Hence in this case when pre-processor is run, the macro receives the class as T hence the macro is replaced with "T".
What you need is this : typeid
add #include <typeinfo>
and replace the cout... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.