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,530,377 | 67,530,448 | C++ function overloading char called instead of double | I have a bunch of overloaded functions to take on specific int sizes, float, double, char and std::string.
eg:
#include <cstdint>
#include <iostream>
void some_func(uint8_t& src) {
std::cout << "inside uint8_t" << std::endl;
}
void some_func(uint16_t& src) {
std::cout << "inside uint16_t" << std::endl;
}
void s... | Non-const lvalue references can't be initialized with rvalues. (bool)true; and (double)3.14 are rvalues.
The only overload with a const lvalue reference parameter (which can be initialized with rvalues) is the const char& src one, that's why it's used.
Since the type is different (char vs bool/double), a temporary char... |
67,530,513 | 67,531,126 | Which solution is best, create connections, or call methods directly in QT? | Developing a pdf reader app. QT 5.11.0
GitHub
I have a class PdfPresenter that contains the UI business logic for the View.
class PdfPresenter
{
public:
PdfPresenter(PdfViewer* parentPdfViewer);
~PdfPresenter();
SOME CODE HERE
public:
void OnClick(const QPoint event);//some logic
private://fields
Link... | This is a good rule of thumb:
If you know the exactly one place you want to notify, use a direct call.
If you don't know how many, or which, places you want to notify, emit a signal.
|
67,530,976 | 67,531,174 | What's wrong with my code? It shows an unwanted result | #include <bits/stdc++.h>
#define ll unsigned long long int
using namespace std;
ll solve(ll arr[], ll n, ll b, ll x, ll pos) {
if(n == b)
return n;
ll idx = pos - 1;
for(ll i = n -1; i >= idx; --i) {
arr[i + 1] = arr[i];
}
arr[idx] = x;
return (n + 1);
}
signed main() {
ll t;
cin >> t;
... | You need to learn how to debug your code. If you can't do that with a debugger, write a function which prints to the screen the relevant information, such as the following:
void paxDebug(const char *desc, ll arr[], ll sz, ll n, ll b, ll x, ll pos) {
cout << desc << "\n";
cout << "n = " << n << " b = " << b << "... |
67,531,015 | 67,531,176 | error: invalid conversion from 'void*' to 'node_t*' | Whenever I try running the code below, I get the following error on line 34:
error: invalid conversion from 'void*' to 'node_t*'
I'm new to pointers and linked lists, and I was watching a tutorial on how to use them (this one: Understanding and implementing a Linked List in C and Java), and I copied the most of it ex... | Replace malloc with new
Perhaps read https://www.geeksforgeeks.org/malloc-vs-new/
Note the line
node_t *result = new node_t;
in the below code
#include <iostream>
using namespace std;
typedef struct node {
int value;
struct node *next;
} node_t;
void printlist(node_t *head){
node_t *temporary = head;
... |
67,531,703 | 67,947,801 | Set tab close button position on vertical tabs issue | I want to change the default tab widget close button and set my icon instead. The problem is that it draws the icon on the text. I want to draw the X to the right.
Code:
void AppTabBar::paintEvent(QPaintEvent *event)
{
QStylePainter painter(this);
QStyleOptionTab opt;
for (int i = 0; i < this->count(); i++... | Finally! I have fixed the issue with vertical tab close button position.
Code:
if (tabPos != AppTabPosition::Top && tabPos != AppTabPosition::Bottom) {
s.transpose();
if (this->tabsClosable()) { // check if tab is closable
QRect optRect = opt.rect;
optRect.setX(90); // set X pos of close button... |
67,531,994 | 67,532,300 | Why subtract from 256 when assigning signed char to unsigned char in C++? | in Bjarne's "The C++ Programming Language" book, the following piece of code on chars is given:
signed char sc = -140;
unsigned char uc = sc;
cout << uc // prints 't'
1Q) chars are 1byte (8 bits) in my hardware. what is the binary representation of -140? is it possible to represent -140 using 8 bits. I would think ran... | First of all: Unless you're writing something very low-level that requires bit-representation manipulation - avoid writing this kind of code like the plague. It's hard to read, easy to get wrong, confusing, and often exhibits implementation-defined/undefined behavior.
To answer your question though:
The code assumed yo... |
67,532,028 | 67,532,072 | Why does a stack allocated int array not have explicit type int*? | In the following program, I am allocating a new array on the stack and one on the heap. The type of the stack allocated array is int and the type of the heap allocated array is int*. However, when passed into PrintArray they appear to both be int*. Why is the type of the stack allocated array not explicitly written as ... |
The type of the stack allocated array is int and the type of the heap allocated array is int*
That is wrong. The type of the array is int [5] in both cases. Don't confuse the array with the pointer to the first element. Consider simpler example:
int* ptr = new int;
Here ptr is of type int*, but the object you alloc... |
67,532,456 | 67,532,580 | How do I access a static member of class inside an inner class? | #include <iostream>
using namespace std;
class outer {
public :
int a=10; //non-static
static int peek; //static
int fun()
{
i.show();
cout<<i.x;
}
class inner {
public :
int x=25;
int show()
{
cout<<peek;
}
... | You can define the static variable outside the class definition:
#include <iostream>
class outer {
public:
int a = 10; //non-static
static int peek; //static
void fun() {
i.show();
std::cout << i.x << '\n';
}
class inner {
public:
int x = 25;
vo... |
67,532,930 | 67,532,979 | Error in getting ASCII of character in C++ | I saw this question : How to convert an ASCII char to its ASCII int value?
The most voted answer (https://stackoverflow.com/a/15999291/14911094) states the solution as :
Just do this:
int(k)
But i am having issues with this.
My code is :
std::cout << char(144) << std::endl;
std::cout << (int)(char(144)) << std::endl;
... | If your platform is using ASCII for the character encoding (most do these days), then bear in mind that ASCII is only a 7 bit encoding.
It so happens that char is a signed type on your platform. (The signedness or otherwise of char doesn't matter for ASCII as only the first 7 bits are required.)
Hence char(144) gives y... |
67,533,171 | 67,534,438 | Unable to understand why this 19 lines C++ code is doing the required task (using recursion) so I made its stack but there is still an issue | So, my question is to write a C++ program to print all the substrings of a given string using recursion. It was in a free youtube course in which the teacher just tells questions and their answer without a detailed explanation. So, I copied that code and executed it and it was working but I wanted to check how the stac... | You can instrument the function to see more clearly what happens:
#include<iostream>
using namespace std;
void sub( string s, string ans="",int stack_counter =0)
{
std::cout << "\n";
std::cout << stack_counter << " inp " << s << " " << ans << "\n";
if(s.length()==0)
{
cout<<ans<<endl;
r... |
67,533,208 | 67,533,591 | implementation of stacks using vector - segmentation fault in peek() function | #include <iostream>
#include <vector>
using namespace std;
class Stack{
public:
vector<string> vc;
int length=0;
void peek(){
if(vc.size()==0){
cout<< "The stack is empty"<<endl;
}
cout<< vc[length]<<endl; //----> does not work;
//cout<<vc[vc.size()-1]; ---> does not work either
... | There are a few problems in your code:
void peek(){
if(vc.size()==0){
cout<< "The stack is empty"<<endl;
}
cout<< vc[length]<<endl; //----> does not work;
}
If vc.size() == 0, you print out a message, and then proceed to index into the empty vector. You should return inside that if, to avo... |
67,533,537 | 67,535,742 | Time complexity of typeid and dynamic_cast operations in C++ | Setting aside all the concerns about the necessity of using typeid and dynamic_cast and their questionable effects on code maintenance, is there any information about the performance of these two dynamic type introspection mechanisms? The Wikipedia article on RTTI claims that:
The use of typeid, in a non-polymorphic c... | The language standard doesn't impose any requirements about the complexity of either operation. As such, the statement that you quote isn't backed up by specification. It is presumably based on either how the functionality can be, or has been implemented in practice.
Bigger problem with the claim of preferability is th... |
67,533,615 | 67,533,907 | C++ - Can you overload a function with different parameters but define it only once? | I'm a beginner in c++ and I'm trying to make a simple command line game. I have three classes:
class DynamicEntity : public Entity { // Entity class has only int x, y variables and getters/setters
protected:
enum direction {RIGHT = 77, LEFT = 75, UP = 72, DOWN = 80};
public:
posWrap getNextPos()... |
I want to know if it is possible to pass in a Player class to checkCollisions and inside the method, use the Player version of getNextPos, without explicitly writing another definition of checkCollisions.
You seem to misunderstand how overloading and virtual dispatch works. This function
static char checkCollisions(D... |
67,533,635 | 67,898,880 | Opencv Image Registration - MapperGradEuclid | I'm trying to find the translation & rotation of an image with the reference template image.
The template image is one of the following pictures.
Since the resolution is quite small (320*240) we would like to solve the alignment problem with the image registration class of opencv (Image Registration). We don't want to... | The solution was not only one, but several different aligning methods.
Those image registration techniques only work if the target is already close to the template position. Therefore I was not using it anymore.
To achieve mentioned aligning problem the pipeline of several methods did the job :
PCA (basic shift and ro... |
67,534,450 | 67,534,772 | What goes into the scope of a contructor defined outside the class? | I am studying some advance c++ code and I am struggling to understand what the author was trying to define in the scope of the constructor he defines outside the class:
The code looks something like this:
class myclass(){} // defined somewhere else.
myclass::myclass(const char *x, const char *y, const char *z):
... | The example is ill-formed because the class definition doesn't declare the constructor that is defined, nor the sub objects that the constructor initialises.
what the author was trying to define
The author has defined a class, and a constructor.
Essentially what I need to know is what can I do in the scope (i.e. in ... |
67,534,543 | 67,535,487 | Why is ranges::basic_istream_view::begin() not cached? | I found that c++20 ranges::basic_istream_view is slightly different from the range-v3 version.
The most important difference is that the std::ranges::basic_istream_view does not cache its begin(), so that each begin()s will return the next iterator with the value that has been read (godbolt):
auto words = std::istrings... | In the definition of the range concept, in [range.range], we have:
template<class T>
concept range =
requires(T& t) {
ranges::begin(t); // sometimes equality-preserving (see below)
ranges::end(t);
};
where the "see below" parts are (emphasis mine):
Given an expression t such that decltype((t))... |
67,535,009 | 67,535,568 | Generate a recursive series faster (similar to Fibonacci) | Hi have to calculate the n term of a series, being n really big, and it has to be done as fast as posible.
The series is defined by the following function:
f(0) = 1
f(1) = 1
f(2n) = f(n)
f(2n+1) = f(n) + f(n-1)
I know I have to use memoization. I did this code but the problem is that with big n values is giving segmen... | I think recursion is the right idea here, because you only need the last value and it actually doesn't depend on that many prior values. The best case is, if your input is a power of 2, say 2^n. Then you only need the values of n inputs.
Although the performance is worse in other cases, it should still be much better t... |
67,535,310 | 67,535,956 | Using rand() in header file | I want to populate an array with three different random integers.
int itemA[3] = {rand() % 20 + 1, rand() % 20 + 1, rand() % 20 + 1};
Currently I can only seed the random integer if it is in the main. Can someone tell me how to seed it in the header file where my array is?
From what I've found so far, I think I need s... | This is a surprisingly deep and important question—so much so that it’s mentioned in my profile. The answer is simple: you don’t do this in the header, even though inline variables make it possible to do so. The reason is important: as global state, the seed must be set once (consider that, if multiple headers each s... |
67,535,556 | 67,535,569 | Getting error while declaring size of 2D vector | I want to declare my 2D vector first, then give it a size.
But why I am getting error?
Can anyone explain me?
int main() {
vector<vector<int>> a;
a = vector<int>(16, vector<int>(15));
cout << a.size() << a[0].size();
}
The reason for doing it is that I don't know the size before but after getting the input... | vector<int> is not a 2D vector.
Instead of this:
a = vector<int>(16, vector<int>(15));
You should use this:
a = vector<vector<int>>(16, vector<int>(15));
|
67,535,746 | 67,535,767 | seeking clarity regarding std::cout and std::endl | I am trying to get a better understanding of what happens to the buffer when we do not use std::endl after std::cout.
Let us consider the following piece of C++ code -
int main(int argc, char** argv) {
std::cout << "Hello World!";
return 0;
}
As per my understanding, std::cout would add the string Hello W... | Yes, since all streams are flushed at their destructors, and global std::cout object will be destructed upon program exit, the string will be printed.
Note, however, that there will be no new line character in the end of the printed string, so console prompt would look unusual (and ugly) with your regular prompt immedi... |
67,535,946 | 67,536,682 | C++11 conditional data type | I wrote a C++11 function that conditionally initializes an object. Consider the following example:
arma::mat some_function(bool a, bool b, unsigned long int c) {
if(a) {
if(b) {
arma::sp_mat d(c, c);
} else {
arma::SpMat<short> d(c, c);
}
} else {
if(b) {
arma::mat d(c, c, fill::ze... | template<class F>
arma::mat some_function(bool a, bool b, unsigned long int c, F f) {
if(a) {
if(b) {
arma::sp_mat d(c, c);
return f(d);
}
arma::SpMat<short> d(c, c);
return f(d);
}
if(b) {
arma::mat d(c, c, fill::zeros);
return f(d);
}
arma::Mat<short> d(c, c, fill::zeros)... |
67,535,958 | 67,536,018 | Is assigning to a field of temporary object undefined behavior? | I compiled the following code with gcc and clang with -O1 and -std=c++20 flags, and it seems to work as expected.
#include <iostream>
struct S { int i; };
template<typename T>
T *get_address(T&& t) { return &t; }
void print_value_from_temporary(S *const s) {
std::cout << s->i << '\n';
s->i = 0;
std::cout... |
Is the s->i = 0; line an undefined behavior?
No. The temporary will be destroyed after the full expression, which includes the execution of the function body of print_value_from_temporary. For s->i = 0; in print_value_from_temporary the temporary has not been destroyed yet.
All temporary objects are destroyed as the... |
67,536,140 | 67,544,941 | How to resize and areo snap frameless windows qt6 | Im designed a form in qt designers
I also make my program frameless with using Qt::FramelessWindowHint and Qt::WA_TranslucentBackground
currently I coded drag windows manually in my program in this way
bool Qt6Gui::eventFilter(QObject* obj, QEvent* event)
{
switch (event->type())
{
case QEvent::MouseButtonD... | after some more searching I finally found this on github its exactly what I wanted.
|
67,536,263 | 67,536,348 | My paired vectors are not getting sorted in C++ | I have made paired vectors and I want to sort one vector according to the values of other vector, but when I run my program the vectors aren't getting sorted. They just remain the same. And I think it is because of the pair that I have made I have actually just copied the code to perform paired sorts from internet and ... | Copies of the original vectors are passed to the arguments vector<int> a and vector<int> b. Modifying the copies will not affect what are passed in caller.
Add & after the types to make them references to reflect changes in the function to the caller.
Also Variable-Length Array like pair<int, int> pairt[n]; is not in t... |
67,537,079 | 67,542,256 | Do we need metaclasses to do this, or is reflection enough? | So I have been quite looking forward to metaclasses. I then heard that it won't be in c++23, as they think we first need reflection and reification in the language before we should add metaclasses.
Looking over c++23 reflection, there appears to be reification capabilties. Are they sufficient to solve what metaclasse... |
Looking over c++23 reflection, there appears to be reification capabilties. Are they sufficient to solve what metaclasses would do; ie, are metaclasses just syntactic sugar?
Calling it C++23 reflection is... optimistic. But the answer is yes. To quote from P2237:
metaclasses are just syntactic sugar on top of the fe... |
67,537,343 | 67,537,380 | Why is this code giving me segmentation, ? when we print only count then it gives answer and when print ans[4] or any value then it gives error? | I am getting segmentation error , it gives output when only print ans[k] inside the function then it
gives corrct output but in main when I try to print ans[k] then it gives segmentation
i am new at progamming so i don't know more about it so please help me it's my assigment
question is
I have to create a array ... | I didn't read your code well and there may be other errors, but at least the combination of
vector<int> arr(1000001,0);
and
for (int k = 5; k <= 4000001; k += 4)
{
if (isPrime(k))
{
arr[k] = 1;
}
}
is bad because arr[k] will go further th... |
67,537,957 | 67,538,859 | C++ Evil Getter Setter against Factory/Builder design pattern | I'm trying to learn the design pattern norme (like refacturing guru), and i have some problem to understand how i could merge the idea of bad design with public getter/setter and factory/Builder that need "out of constructor" variable setter.
for example with the answer of this article to article to Design pattern
As y... | Ok i think the comments are right, the way i see the solution is the following :
No Setter, the only way to interact with the object will be with function with a purpose.
For exemple, modify HP, add a DoDamage function that will return false if the ship is destoyed and will internally modify the hp (and maybe the dama... |
67,537,981 | 67,538,693 | Create a std::string from char[] with strndup like semantics | I have a
char txt_msg[80];
The array can contain up to 80 characters, e.g. there is no guarantee that there is a terminating null. If there are less than 80 characters however, there is a terminating null.
Right now I'm using this to get a std::string from this:
std::string(txt_msg, txt_msg + ::strnlen(txt_msg, sizeof... | I would probably have done something like this:
char txt_msg[80];
auto s = std::string(std::begin(txt_msg), std::find(std::begin(txt_msg), std::end(txt_msg), '\0'));
std::find will return the position of either the first null terminator or the end of the array.
|
67,538,079 | 67,615,177 | Which options should I enable in conanfile.txt to use with QML/ QtQuick? | I try to set up an environment with conan using qt/5.15.2@bincrafters/stable.
Getting the following error when running the code
"main.qml:1:1: module "QtQuick" is not installed"
Need to find out how to install QML correctly with Conan.
| As you found out yourself for QtQuick you need at least qtdeclarative=True, you can also add these options for the controls library:
qtquickcontrols=True # for QQC1
qtquickcontrols2=True # for QQC2
On Linux, I've also found adding these modules to be useful:
config=-xcb
qttools=True
qttranslations=True
qtvirtualkeybo... |
67,538,287 | 67,538,295 | boost::algorithm hex and unhex showing unexpected results | Edit: looks like I made a dumb mistake :)
Anyone have any idea why the below code results in 2 different hex strings?
There seems to be an extra byte at the beginning. Does boost's hex and unhex not work well together or am I missing something? Better alternatives welcome for C++17!
std::string hex(const std::vector<ui... | The extra byte is here:
std::vector<uint8_t> bytes = {0};
You should remove the extra byte like this:
std::vector<uint8_t> bytes;
|
67,538,341 | 67,538,415 | Can NRVO be turned off in debug builds? | In the program as follows
#include <iostream>
struct A
{
A() { std::cout << "0"; }
A( const A & ) { std::cout << "1"; }
A( A && ) noexcept { std::cout << "2"; }
};
A foo()
{
A res;
return res;
}
int main()
{
const A a = foo();
(void)a;
}
I expected named returned value optimization ta... | Since mandatory copy elision doesn't apply here, yes, compiler is not obligated to optimize away a move in any builds, be it debug or optimized ones.
It is allowed, but not required.
|
67,538,463 | 67,540,615 | Should I bother about user might mess up my program's files? | I am writing a C++ program for Linux which creates some files on the disk during the work. These files contain information about program's internal objects state, so that the next time the program is started it reads these files to resume previous session. Some of these files are also being read/written to during the e... | First, check your resources and if it is worth the effort. Will the user be even tempted to trace and edit these files?
If so, my advice is this: Don't be concerned whether or not the file has been modified. Rather you should validate the input you get (from the file).
This may not be the most satisfying answer, but er... |
67,538,574 | 67,539,174 | Go through the array from left to right and collect as many numbers as possible | CSES problem (https://cses.fi/problemset/task/2216/).
You are given an array that contains each number between 1…n exactly once. Your task is to collect the numbers from 1 to n in increasing order.
On each round, you go through the array from left to right and collect as many numbers as possible. What will be the total... | Let me explain my thought process in detail so that it will be easier for you next time when you face the same type of problem.
First of all, a mistake I often made when faced with this kind of problem is the urge to simulate the process. What do I mean by "simulating the process" mentioned in the problem statement? Th... |
67,539,060 | 67,539,318 | Is there any drawback to using '\n' at the start instead of end? | Mostly I see people using \n at the end of string but putting \n at the beginning makes more sense to me since now I don't have to keep track of what will be printed next.
For example-
std::cout<<"Some string\n"; //syntax 1
Suppose after this the control goes to some other function where I don't need a new line but u... | It is not at all "personal preference" - the two solutions are semantically different. You would use one over the other when the requirements of your application demand it.
One critical point though is on many platforms \n causes any buffered text to be flushed and the text to be output. If you delay the \n you may n... |
67,539,095 | 67,833,199 | Finding the cycle in a directed graph | I was solving a problem to determine whether a graph contains a cycle. I solved it using the coloring method (in the visited array I will mark, 0 if it has never visited, 1 if it is visited, and 2 if the tour of vertex is done)
for this I wrote the code:
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[20... | par[v] - parent node of v, pr - previously visited node:
void dfs(int u, int pr = -1){
if(vis[u]==1) {
vector<int> cycle();
int cur = pr;
while(cur != u) {
cycle.push_back(cur);
cur = par[cur]
}
cycle.push_back(u);
chk = 1;
return;
... |
67,539,702 | 67,539,837 | Problem to run opencv patented SIFT and SURF although flag DOPENCV_ENABLE_NONFREE=ON is set | I'm currently working on opencv vers. 4.5.1 and I want to use SIFT and SURF but I run into the well known problem that they're patented. I already know that under 4.5.1 there is the possibility to use the flags DOPENCV_ENABLE_NONFREE=ON and DBUILD_opencv_xfeatures2d=ON. But when I use the following command for cmake
cm... | Build OpenCV with the following command:
cmake -D CMAKE_BUILD_TYPE=Release \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=path/to/opencv_contrib/modules \
-D OPENCV_ENABLE_NONFREE=ON \
path/to/opencv
|
67,539,793 | 67,599,299 | How do I get position.bin from ngraph.native? | I'm using ngraph family libraries to build some graphs in browser.
I've tried to run layout using ngraph.native but all that I get is ~10k .bin files without position.bin.
Am I missing something? What should I do after I get all those .bin files?
Here's what I tried:
creating graph in node.js
converting graph to binar... | Ok. Guess I figured out how to get positions.bin
I took a look at ngraph.offline.layout source and found that positions.bin is created after all iterations are completed.
So. Here are my changes that helped to get positions.bin (all changes made in file main.cpp (ngraph.native/demo/gcc/main.cpp):
in void save() change... |
67,539,887 | 67,539,979 | How to make `boost::stacktrace` formattable with `fmt::format` | I'm struggling to get boost's stack trace library to interoperate with fmt, the trouble seems to be that I can't quite specialize a boost::stacktrace::basic_stacktrace. Anybody know what the underlying issue is?
#include <fmt/core.h>
#include <boost/stacktrace.hpp>
using BoostTraceStackFrame = std::remove_reference_t<... | Just three small things:
Missing/wrong headers. You need to include fmt/ranges.h in order to support formatting ranges.
Wrong overload. The function for formatting into an iterator is fmt::format_to, not fmt::format.
These:
using BoostTraceStackFrame = std::remove_reference_t<decltype(boost::stacktrace::stacktrace... |
67,540,015 | 67,540,090 | Can´t find proper MSVCP140d.dll dependency while loading my own DLL, even though its present in the folder | today I encountered a problem.
I´m building my own DLL(C++), that is used as a plugin to OpenCities Map. On my local computer(the same computer that is used for developing the project), everything works fine, my DLL is loaded without troubles and everything is okay. However, today I tried the same thing on virtual mach... | You should not be shipping code based on the debugging versions of the runtime library DLLs. Microsoft do not support this. DLL names are not case-sensitive, BTW, so that's a red herring.
|
67,540,139 | 67,540,548 | strange index issue for a simple vector | I have one array like {7, 3, 1, 5, 2} for example. I want to get a max value from one index onwards, so the result should be like {7, 5, 5, 5, 2}. I just use a for loop like below. It throws strange heap overflow problem.
int maxProfit(vector<int>& prices) {
vector<int> maxRight;
int runningMax = 0;
... | As the variable i declared in the for loop
for(auto i=(prices.size()-1);i>=0;i--){
has the unsigned integer type std::vector<int>::size_type then you will get an infinite loop because when i is equal to 0 then the expression i-- will afain produces a non-negative number.
Another problem is that the for loop will again... |
67,540,907 | 67,544,242 | using one Qcombobox to set value to several labels, C++ | im trying to set the value from a combobox to multiple Qlabels, the idea is to populate the QcomboBox with all the values, then according to the number, (ejem 15.6) the corresponding label should change the problem is, theres too many of them to simply use a switch of something similar, but all the names of the labels ... | If I would do something like this, I would probably create a QHash<QString, QLabel*> and use that as a cache to find the matching QLabel for each name.
Declaration:
QHash<QString, QLabel*> m_hash
Storing value:
m_hash[labelName] = labelPtr;
Reading value:
QLabel* labelPtr = m_hash.value(labelName, nullptr);
if (label... |
67,540,922 | 67,541,967 | Replace accentuated vowels with common vowels in c++ | I have a string with text in spanish, and i want to replace certain characters like this:
character
replace-with:
á
a
é
e
í
i
ó
o
ú
u
ñ
n
I've tried this without result:
std::string RemoverTildes(std::string str){
std::string sinTildes = str.c_str();
for(int i = 0; i < str.length(); i++){
... | You can use a Unicode (UTF-16LE) wchar_t to operate with this characters. You can read more about char types here.
Here is your code with use example.
#include <iostream>
void tildesRemover(wchar_t* wideString) {
auto stringLen = sizeof(wideString);
for (int i = 0; i < stringLen; i++){
if (wideString[i] == L'á... |
67,541,058 | 67,541,158 | Is there a difference between using 'this' keyword in the constructor of a class or not using it in C++ | Posts that I have read that are related to my question and have answered part of it:
Using 'this' keyword in constructor
Difference between using keyword new in constructor and in data portion of a class
My question:
My specific question follows on from the topic here:
Using 'this' keyword in constructor
Are the answer... | No need to use 'this' keyword in the constructor unless you have the same name for a class attribute and a parameter.
Gui::Gui(const double organismSize, const double foodSize )
{
organismSize =organismSize; // we have an ambiguity, the compiler cannot make a difference between the parameter and the attribute
f... |
67,541,169 | 67,541,223 | Some friend functions of a template class exhibit undefined reference | Was originally working on a question someone else asked earlier: Why string is not printed?C++. Seeing that OP was not quite utilizing the template for DataOut and GetData, so I was trying to make them template as well.
Here's the code I end up having:
#include <iostream>
#include <string>
template<class T>
class Arra... | You declared two (families of) non-template friend functions
template<class T>
class Array{
public:
T U[10];
friend void DataOut(const Array&);
friend void GetData(Array&);
};
If you want that such a non-template function would be a friend function for a specialization of the class template you have to de... |
67,541,244 | 67,541,872 | Implementing Accept for UDP | UDP sockets have a 'connect' call, but do not have an 'accept' call for server applications. There are socket APIs that benefit performance-wise from a connected UDP socket (e.g. recvmmsg/sendmmsg) and is the best performing system call for a single-flow with very high packet rates (any thing higher requires kernel-byp... | There's no built-in capacity to clone a socket. You would need to keep track of whatever options you set on one socket and set those on a new socket.
You have a larger problem however. If you have multiple UDP sockets open on the same port and a unicast packet comes in, only one of those sockets will receive it and y... |
67,541,281 | 67,542,963 | Doing dynamic_cast over parameter pack | Consider such code:
struct A
{
A() = default;
virtual ~A() = default;
};
struct B : public A
{
B() = default;
virtual ~B() = default;
};
struct C : public A
{
C() = default;
virtual ~C() = default;
};
struct D : public A
{
D() = default;
virtual ~D() = default;
};
struct E : public A... | In C++17 and later, you can use a fold-expression.
template <typename... CLASSES>
bool AreObjectsEqual(std::vector<A*>& vec)
{
return std::all_of(vec.begin(), vec.end(),
[](const auto v)
{
return (... || (dynamic_cast<CLASSES*>(v) != nullptr));
});
}
In C++11 & 14, there's a som... |
67,541,594 | 67,541,686 | Should I increment or decrement the reverse iterator? | As given here, a good way to iterate backwards through a list is to use rbegin(), as below:
list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();
for( ; iter != m_Objs.rend(); ++iter) {
}
Unfortunately, I cannot remember whether to ++iter or --iter. Because we are going backwards, using --iter, too, seems logica... | The only reason to have a reverse iterator is to go backwards through the sequence. If you were OK with using -- you could just use a regular iterator. Always use ++.
|
67,541,785 | 67,542,037 | Error when assigning a unique pointer that is returned by a function to a variable | I am using a library called "Pixel Game Engine", which has a Sprite and a Decal class. The documentation uses std::unique_ptr to create them, so I want to do the same to avoid any complications that may come later on.
Here is my code:
class Asset
{
private:
typedef std::unique_ptr<olc::Sprite> uniq... | MakeDecalFromSprite passes a uniqueSprite by value, which involves making a copy. But std::unique_ptr has a deleted copy constructor so when you try to call MakeDecalFromSprite you get a compilation error.
The solution is to pass sprite by const reference instead:
uniqueDecal MakeDecalFromSprite(const uniqueSprite& s... |
67,541,800 | 67,542,870 | benefits of passing const reference vs values in function in c++ for primitive types | I want to know what might be the possible advantages of passing by value over passing by const reference for primitive types like int, char, float, double, etc. to function? Is there any performance benefit for passing by value?
Example:
int sum(const int x,const int y);
or
int sum(const int& x,const int& y);
For the... | In every ABI I know of, references are passed via something equivalent to pointers. So when the compiler cannot inline the function or otherwise must follow the ABI, it will pass pointers there.
Pointers are often larger than values; but more importantly, pointers do not point at registers, and while the top of the st... |
67,542,019 | 67,542,243 | In what order are objects initialized when mixing pointers and non-pointer objects? | Take the following code:
Foo *foo = fooFactory();
Bar bar(foo);
I have three questions:
Is this safe? In other words, am I guaranteed that fooFactory() will be called and foo initialized before Bar's constructor is run (assuming fooFactory() doesn't throw)?
Does the answer to question #1 change if this is part of a f... | In C++ (and C), statements execute (or appear to execute) in the order they appear in the source code. Under the as-if rule, out-of-order execution may occur when statement B has no dependencies on statement A in order to improve performance. Thus, given:
int i = 1;
int j = 2;
int k = i + j;
The first two statements... |
67,542,333 | 67,547,035 | Cannot store bind_front_handler return value in variable | With these present in other parts of my codebase,
namespace net = boost::asio;
using boost::asio::ip::tcp;
boost::asio::io_context& io_context_;
tcp::acceptor acceptor_;
void server::on_accept(boost::beast::error_code ec, boost::asio::ip::tcp::socket socket);
I have noticed that this piece of code compiles:
auto stra... | Indeed, you should not be doing that. The bind-front wrapper wants to be a temporary (in that it is move only). You could "fix" it by doing
acceptor_.async_accept(strand, std::move(call_next));
(after which you will have to remember that call_next may not be used again because it has been moved-from).
I would pers... |
67,542,605 | 67,542,960 | Bazel shared library does not include all symbols | I am trying to build a shared library using bazel (mediapipe) and linking dependencies without sources or headers fails to include the dependency symbols.
Here is sorta psudo code example
cc_binary(
name = "library.so",
deps = ["//project:dependency"],
linkshared = 1,
)
Some other file:
cc_library(
name... | Unix linkers traditionally drop symbols that are not required by the top-level target (i.e., code in "library.so" cc_binary). Bazel will ask the linker to forcefully include all code in a cc_library rule in the final top-level link if alwayslink = True is set on it.
|
67,542,799 | 67,543,359 | explicit constructor is not a candidate | It is an implementation of class String in The C++ Programming Language.
This is my code and I just show a part of them to eliminate the unrelated stuff.
#include <iostream>
class String {
public:
explicit String(const char *x);
explicit String(const String &x);
friend String operator+(const String &, con... | You declare your copy constructor explicit, this means ... well... you need to be explicit when doing a copy:
friend String operator+(const String &, const char *) {
// ...
return ret;
// ^~~~
// this is a copy, it's an error because it's implicit
}
friend String ope... |
67,542,882 | 67,542,905 | Why does the fold expression not apply to for loop? | Below is from an authoritative C++ proposal:
template<class... TYPES>
constexpr void tuple<TYPES...>::swap(tuple& other)
{
for...(constexpr size_t N : view::iota(0uz, sizeof...(TYPES)))
{
swap(get<N>(*this), get<N>(other));
}
}
However, I cannot compile the following code in the same way:
#include ... | Because fold expressions are... expressions. A for loop is a statement. ... unpacking applies (with one or two exceptions) to expressions, not to statements.
|
67,542,945 | 67,543,143 | Trying to Create an array holding a Struct in C++? | I am trying to create an array using a struct in c++ which takes two variables i.e value and weight. So I created an array which will have value and weight in one element like this
Arr[]={{1,2},{3,4}}...and i want that if i called
Arr[0].value and Arr[0].weight then it should return 1 and 2 respectively but I think I'm... | Your biggest compile issues are this:
You got to give your Item a default constructor, otherwise, it can't exist in an uninitialized array.
struct Item
{
int value, weight;
// Constructor
Item(int value, int weight)
{
this->value = value;
this->weight = weight;
}
Item() : value(... |
67,543,098 | 67,633,324 | Why copy constructor called twice in heap array initialization? | For the following C++14 code, why does g++'s generated code for new A[1]{x} seem to invoke the copy constructor twice?
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "default ctor" << endl; }
A(const A& o) { cout << "copy ctor" << endl; }
~A() { cout << "dtor... | TL;DR: It's likely a GCC defect, a misinterpretation of {x} as temporary in this context. For each element in new A[N]{x1, x2, ... xN}, the copy constructor should get called once according to [decl.init] and [new.expr]. Instead, GCC likely interprets it as initializer list and thus in part as intermediate rvalue. We c... |
67,543,306 | 67,543,339 | C++ Calling return member function outputs "?before initialization" | When I run this code, I get this output.
main.cpp
#include <iostream>
#include "Date.h"
#include <string>
int main()
{
//Create
Date date = Date(1 , 1, 2000);
std::string str = date.GetDate();
std::cout << "Initial parameters: " << str << "\n";
//Use setters to change
date.SetDay(30);
date... | The + operator in "/" + GetDay() and "/" + GetYear() are not concatenating strings but moving the pointer pointing at the first element of the array "/" ({'/', '\0'}) GetDay() and GetYear() elements ahead.
GetYear() returns a large value, so the pointer goes to some "random" position and before initialization seems hap... |
67,543,559 | 67,543,721 | while overloading new if i delete an object pointer does it also deallocate the memory given dynamically to data members? | #include<iostream>
#include<stdlib.h>
using namespace std;
class quasar{
int quark;
int *series;
public:
quasar(){
quark=0;
}
quasar(int a){
quark=a;
}
void *operator new(size_t){
quasar*p;
p=(quasar*)malloc(sizeof(quasar));
p->series=ne... | No, the series won't be deleted, you have to explicitly delete a pointer.
You can do that in a destructor like this:
~quasar() {
delete[] series;
}
You can also only add this to your delete-operator delete[] series;, but then it will only be deleted if you are working with a pointer to a quasar object.
You might wan... |
67,543,636 | 67,552,159 | Perfectly transform a 2-tuple into a pair | I want an utility to transform a std::tuple<T,U> to std::pair<T,U>, while leaving a std::tuple<T, U, V, W...> unchanged.
Furthermore, I want this utility to
be a function object, not a function, so that I can pass it around as I like;
enforce that it's input must be a std::tuple;
taking advantage of move semantics whe... | template<class...Fs>
struct overloaded : Fs... {
using Fs::operator()...;
};
template<class...Fs>
overloaded(Fs&&...)->overloaded<std::decay_t<Fs>...>;
auto move_tuples = []<class...Ts>(std::tuple<Ts...> x){return std::move(x);};
auto to_pair = []<class A, class B>(std::tuple<A, B> x){
return std::pair<A,B>( std::... |
67,543,770 | 67,543,811 | Check if a lambda is noexcept | I'm trying to check if a lambda is noexcept or not
but it looks like noexcept(lambda) doesn't do what I think it should.
auto lambda = [&](Widget& w){
w.build();
};
auto isNoexcept = noexcept(lambda) ? "yes" : "no";
std::cout << "IsNoexcept: " << isNoexcept << std::endl;
This prints "IsNoexcept: yes" even throug... | The lambda needs to be called, e.g.
auto isNoexcept = noexcept(lambda(std::declval<Widget&>())) ? "yes" : "no";
noexcept is used to check the expression throws or not, while the expression lambda, the lambda itself won't throw, until it's invoked (with specified arguments).
|
67,544,292 | 67,544,453 | Is there a way to forbid a function to be called more than one time? | I'm making a terminal app just to increase my OOP skills. I have this RunApplication()function and LoginCustomer()function to make a customer log in to the application.
This code is my RunApplicationfunction:
void RunApplication(){
while (key!='q'){
printUI();
std::cin >> key;
if (key == '1'){
L... |
My question is can I forbid a function to be called more than one time in a program(or main) ?
You can use local static variables to have a guarantee that the code is called only once.
Example:
struct FunctionObject
{
FunctionObject()
{
std::cout << "I will be called only once" << std::endl;
} ... |
67,545,142 | 67,545,231 | Runtime Error of no member named children in Trie ,even though children is clearly defined in Trie class | Hi I'm a beginner in C++ trying to implement basic trie structure .Someone please help. Any feedback is welcome.I'm getting a runtime error of
Line 15: Char 25: error: no member named 'children' in 'Trie'
if(present->children[word[i]-'a']==NULL)
I have tried to solve this for past 2 days. Still no idea.
cla... | In this constructor
Trie() {
string val="";
Trie* children[26];
bool flag=false;
}
you created a local array children that will not be alive and visible outside the constructor.
The class has only one data member
Trie* root=new Trie();
that can be accessed inside member functions of the... |
67,545,241 | 67,545,352 | Searching an unordered set of objects by attribute and returning the corresponding object | I need FindIngredient to return a const Ingredient & when searching by Ingredient.name. I need to used unordered_set. So I think I need 2 of them one to contain the objects and another one just to contain the string attributes name in order to search by string.
Is my approach ok or can I achieve it using only unordere... | If you don't mind slower algorithm of search (O(N) time) then you can do a simple loop:
for (auto it = ingredients.begin(); it != ingredients.end(); ++it)
if (it->Name == name)
return *it; // Return found ingredient.
throw "Ingredient not found";
Loop above can be made even shorter:
for (auto const & e: in... |
67,545,298 | 67,545,376 | What is the type of string_type for filesystem::path constructor? | In the documentation for std::filesystem at cppreference it shows the path constructor taking a string_type&&. I'm looking for the constructor that just takes an ordinary (const) char* character pointer. It doesn't say anywhere what type string_type is. I'm wondering whether it'll implicitly construct an std::string wh... | As stated here, normally it's std::wstring on Windows and std::string everywhere else.
Passing const char * (or a different string type) should invoke a different constructor: (5)
template< class Source >
path( const Source& source, format fmt = auto_format );
|
67,545,845 | 67,545,933 | How to pass in a 3D array with set x index as a 2D array? | I have a 3D array arr[x][y][z], where at a given point x is a constant, and I want to pass in are[const][y][z] as a 2D pointer. The following lines are how I attempted to do so:
double tmpMatrix[msize][msize][msize];<- array declaration
...
test(msize, (double*)(tmpMatrix[i]));<- function calling
...
void test(int ... | There is a wrong comment to this function declaration
void test(int msize, double * m) <- function which takes in 2D arrays
Neither parameter of the function is declared as a two dimensional array or a pointer to a two-dimensional array.
It seems you mean
void test(int n, double ( * m )[msize][msize] ); <- function wh... |
67,545,937 | 67,548,367 | WinApi: IO Completion Ports | Explain, please:
From MSDN: https://learn.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports#supported-io-functions
Consider what happens with a concurrency value of one and multiple
threads waiting in the GetQueuedCompletionStatus function call. In
this case, if the queue always has completion packets wait... | It is using the extreme example of NumberOfConcurrentThreads set to 1 but still having multiple threads calling GetQueuedCompletionStatus. It is saying that under those circumstances (that of there always being a packet queued) the first thread to return a packet will simply continue returning packets and the other th... |
67,546,129 | 67,569,649 | Using Boost Python Numpy ndarray as a Class member variable | I'm looking forward to pass an Python-Object to an Boost Python Class. This Object has an ndarray as attribute and I want to store this ndarray as a private member variable in this Class to use it later on. I could'n find a proper way to do this and I get Compiler Errors when declaring a boost::python::numpy::ndarray v... | So with the help from @unddoch it was finally possible to solve this problem. It turned out that it is not possible to use two extraxt functions in a row, but somehow the following is possible:
FlatlandCBS(p::object railEnv) :
m_railEnv(railEnv),
m_map(
p::extract<np::ndarray>(
railEnv
.attr(... |
67,546,163 | 67,547,946 | Issues with having both subscriber and publisher in the same node | Currently, I have a node that has to have both the subscriber and publisher. However, I am having certain errors when I catkin build.
#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msgs/Float32.h>
void laserCallBack(const sensor_msgs::LaserScan::ConstPtr &msg) {
... | For msg you should use:
msg->ranges[360]
And since "pub" is declared in your main function you cannot call it in a different function. You can first declare it globally and initialize it in the main function.
eg:
#include <geometry_msgs/Twist.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msg... |
67,546,529 | 67,547,593 | Why is std::common_iterator just std::forward_iterator? | C++20 introduced a std::common_iterator that is capable of representing a non-common range of elements (where the types of the iterator and sentinel differ) as a common range (where they are the same), its synopsis defines as:
template<input_or_output_iterator I, sentinel_for<I> S>
requires (!same_as<I, S> && ... | If you have a non-common range of iterators, and you need to transform it into a common range, then you basically have two choices.
You can either compute what the ending iterator would be by successively incrementing the beginning iterator until it is equal to the sentinel, or you can do trickery. common_iterator is f... |
67,547,203 | 67,547,290 | std::vector does not save new data | I am trying to make a function to genereate bezier curves and save each x,y position in a matrix. The row number indicates the number of objects I will set the coordinates to and the number of columns is the number of points (coordinates) generated by the function. I am trying to generate two curves for two objects usi... | The new values are saved to the vector, but you didn't read the new values and instead of that you are reading the values firstly added twice.
The new values are added to the vector without clearing the vector, so the new values will be added after the values that are already added.
If you want to read new values, you ... |
67,547,428 | 67,547,485 | Why linked list is not inserting data when it is empty? | I wrote this piece of code in C++ for the function Insert At Tail in a linked list but when the list is empty it is not inserting the data.
This is the picture of it:- https://i.stack.imgur.com/wKkXk.png
I don't know why the lines from 35 to 39 are not executed.
This is my code:-
#include <iostream>
using namespace std... | void Insert_At_Tail(node *head, int data)
In C++, by default function parametes are passed by value. This head parameter is a copy of the parameter that the caller passes in.
head = new node(data);
This sets the new head pointer. This is fine, but because this head is a copy of the original parameter, this does ab... |
67,547,790 | 67,548,091 | Given a variable whose type is `uint16_t`, is there any difference between (int16_t) uVal and *(int16_t*)&uVal? | It seems that they are equivalent. But I can't figure why.
Here is related code snippet:
#include<iostream>
void foo(uint16_t uVal)
{
int16_t auxVal1 = (int16_t) uVal;
int16_t auxVal2 = *(int16_t*)&uVal;
std::cout << auxVal1<< std::endl;
std::cout << auxVal2<< std::endl;
std::cout << (uint16_t)au... | (int16_t)uval converts the uint16_t value to a int16_t value. For 1 this works as expected, for 0xffff it is implementation-defined behavior because 0xffff does not fit in the bounds of int16_t. (https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions). Since C++20, it is defined such that i... |
67,547,924 | 67,548,354 | How do I reference another class into another class in C++? | I've been trying to reference another class inside of a class in C++ and I have no idea how.
I have created a small program to demonstrate the issue
#include <iostream>
class foo{
public:
int variable1 = 012;
};
class bar{
public:
int getFooVariable(){
return variable1; // How would I get bar t... | You're looking for dependency injection:
class foo
{
public:
int variable1 = 012;
};
class bar
{
foo _foo;
public:
bar(foo& fooInjected) :
_foo(fooInjected)
{}
int getFooVariable() { return _foo.variable1; }
};
There is an idea of inversion of control: bar has no control over the creation ... |
67,548,408 | 67,548,451 | How to pass reference of specific location in a vector to a pointer? | I have a function that I am making use of that takes in a pointer to a location in a vector and is going to iterate it. For example:
#include <iostream>
#include <vector>
void funcy(int *n, double *x) {
for (int i = 0; i < *n; i++) {
std::cout << x[i] << std::endl;
} // next i
} // funcy()
int main(... | As you can just use the []-operator for vectors, you can write funcy(&m, &x[1]);.
If you want to use at(), you can write funcy(&m, &x.at(1));.
|
67,548,459 | 67,548,521 | C++ multithreading and passing templated arguments <typename T>(T arg) | I have this code which is working without anny issue:
void function_exit(dispatcher& d) { /* .. */ }
// ...
std::thread th(function_exit, std::ref(main_disp));
th.detach();
now I tried create another class which hold std::thread which produce errors on compilation
thread_control mtc;
mtc.create<dispatcher&>(function_e... | if (std::is_reference<Arg>::value)
For a given Arg, this will evaluate to either true or false, of course.
However both the code that executes when this condition is true, and the code that executes when this condition is false must be valid C++.
m_thread = std::thread(function, value);
If Arg is a reference, this ... |
67,549,023 | 67,550,027 | Why is the GNU scientific library matrix multiplication slower than numpy.matmul? | Why is it that the matrix multiplication with Numpy is much faster than gsl_blas_sgemm from GSL, for instance:
import numpy as np
import time
N = 1000
M = np.zeros(shape=(N, N), dtype=np.float)
for i in range(N):
for j in range(N):
M[i, j] = 0.23 + 100*i + j
tic = time.time()
np.matmul(M, M)
toc = time... | TL;DR: the C++ code and Numpy do not use the same matrix-multiplication library.
The matrix multiplication of the GSL library is not optimized. On my machine, it runs sequentially, does not use SIMD instructions (SSE/AVX), does not efficiently unroll the loops to perform register tiling. I also suspect it also does not... |
67,549,274 | 67,549,362 | C++ Segmentation fault while trying to create a vector of vectors | I want to create a vector of vectors in C++ with dimensions nx2 where n(rows) is given by user. I am trying to insert values in this vector using a for loop but As soon as give the value of n(rows), it gives a Segmentation fault error
What to do?
#include <iostream>
#include <vector>
#include <cstdlib>
#define col 2
us... | You need to resize a vector before inserting elements. Or use push_back to insert incrementally.
vector<vector<int>> vec;
vec.resize(row);
for (int i = 0; i < row; ++i)
{
vec[i].resize(col);
for (int j = 0; j < col; ++j)
{
cin >> vec[i][j];
}
}
OR:... |
67,549,299 | 67,549,469 | Vectorize on array of bool in c++ | I have an array of bool (or any equivalent structure). I need to count the number of true between the nth and mth position. Is it possible to get the compiler to vectorize this so that 64 or more elements are checked in one go?
| That already happens if you compile with -O3 and potentially -march=native:
#include <algorithm>
#include <iostream>
void count(char* v) {
auto x = std::count(&v[0], &v[100], true);
std::cout << x << std::endl;
}
With gcc, this gives you a bunch of vp* instructions, which means that the count is vectorized. Y... |
67,549,323 | 67,549,425 | Convert char array to uint64_t array | I want to convert an unsigned char [32] array into a 4-element uint64_t array.
I'm fairly new to C++ coding and am really stuck.
unsigned char in_put [32] = { 1a, 2a, 3a, 4a, 5a, 6a, 7a, 8a, 1b, 2b, 3b, 4b, 5b, 6b, 7b, 8b, 1c, 2c, 3c, 4c, 5c, 6c, 7c, 8c, 1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d }
and I expect to get
uint64_t ou... | I will write one simple function:
inline uint64_t fourCh2uint64 (const unsigned char charArr[4]) {
return uint64_t(charArr[6]) << 56 | uint64_t (charArr[7]) << 48 |
uint64_t(charArr[4]) << 40 | uint64_t (charArr[5]) << 32 |
uint64_t(charArr[2]) << 24 | uint64_t (charArr[3]) << 16 |
... |
67,549,440 | 67,549,571 | Can't convert string to int c++ | I'm making a simple number reverse program and I've tried many different ways to convert the string to an int but all I get is errors or "core dumped" while executing or compiling. I'm new to C++.
#include <bits/stdc++.h>
using namespace std;
void solve(){
string n, ans="";
cin >> n;
for(int i=0; i<n.le... | Your for loop is accessing an out-of-bounds element of the n string on its first iteration: when i is zero, you are attempting to access the n.length() element of n but the last element is at position n.length() - 1. Remember that arrays, strings and other 'containers' in C++ start at element 0 and end at element n-1 –... |
67,549,588 | 67,549,943 | How can i pass a function as a function parameter in another function? | I am trying to use an Arduino library and to use one of it's functions as a parameter in my own function, but I don't know how can I do that.
I tried the code below but I get an error.
Any help will be appreciated.
P.S: I do not have an option to use auto keyword.
using namespace httpsserver;
HTTPServer Http;
typedef v... | A member function pointer is not a function pointer.
typedef void (httpsserver::*Register)(HTTPNode*); // My typedef
Register Node = &httpsserver::registerNode;
usage:
void Get(void(httpsserver::*Register)(httpsserver::HTTPNode*), const std::string& path);
Get (&httpsserver::registerNode, "");
you have to pass the ht... |
67,549,602 | 67,550,305 | Program skipping second while loop (reading into int and string vectors respectively using cin) | I don't understand why my 2nd while loop to read input into a vector is not iterating. I've tried using getchar() to flush the input buffer (even tho I think the previous endl does this anyway) between the 1st part (read int vector from input then output) and 2nd part (read string vector from input, then output). Here ... | Your problem is that std::cin buffer already contains EOF or other input that will cause second loop to be skipped. Try this:
std::cin.clear();
std::cin.ignore();
right before this part of code
//part 2
vector<string> text; // empty vector
string inp_text;
while (cin >> inp_text)
text.push_back(inp_text);
|
67,549,836 | 67,549,933 | Array Sum with Pointers i have a problem in the sum | I have this code. and I have a problem with it. When I run it for these numbers "1,1,1,1,1" it answers me right but when I use these numbers "2,1,3,2,2" or any other numbers it answers me wrong. What is the problem?
#include <iostream>
using namespace std;
int main() {
int size = 5;
int array1[size];
int i... | So you have one problem
p = &array1[j];
What you are doing is taking the address of jth element of an array. In you case j is uninitialized which leads to UB since j might contain any variable.
To fix this you can initialize j to 0 (j = 0). Or to just get an address of first element in array you can do following:
p = ... |
67,549,853 | 67,550,021 | Why putting new structures into reallocated c-array crashes program? | I wanted to see how c-arrays work. I made a few programs with malloc(), calloc() and realloc(). Every worked, except for this one:
#include <iostream>
using namespace std;
struct student
{
string name;
string surname;
int age;
};
int main(){
student* arr = (student*)malloc(2*sizeof(student));
if(arr... | Beside wrong malloc implementation there are also other errors that can be fixed.
for(int i = 0;i<2;i++){
student st;
cout<<"Enter name of "<<i+1<<". student: ";
cin>>st.name;
cout<<endl<<"Enter surname of "<<i+1<<". student: ";
cin>>st.surname;
cout<<endl<<"Enter age of "<<i+1<<". student: ";
... |
67,549,859 | 67,550,201 | How to check if predicate is true in c++? | I get what they are supposed to do, but I don't know how to check if, for example, int data fulfils Pred pred when they are given to a function.
For example, I have this function in a singly linked list:
Node<T>* extract(Node<T>*& head, Pred pred)
with these values to check head->data:
extract(listAi,[](int n) {return ... | the argument to the pred object will be the significant data member within Node<T>. E.g. the current node in the list enumeration being performed within extract.
Foregoing the ill-advised manual memory management (all of this is academic, since in the real world you'd use proper C++ containers and algorithms)
#include ... |
67,549,974 | 67,550,214 | Extern Lambda Function | How could I extern the following lambda function from a source file to a header so I can use it in a different source file?
const auto perform_checks = [&]()
{
const auto func =
GetFunctionPEB(static_cast<LPWSTR>(L"ntdll.dll"), "NtSetDebugFilterState");
auto* func_bytes = reinterpret_cast<BYTE*>(func);... | Well maybe this in the direction you want
#include <functional>
#include <iostream>
// In header file
extern std::function<void(void)> externedFunction;
// In c++ file
std::function<void(void)> externedFunction = [](){
std::string msg = "performing checks";
const auto perform_checks = [msg]()
{
s... |
67,550,272 | 67,551,933 | cppcheck considers that variables used in macro are not used | For example, I have this snippet:
const int array_type = model.accessors[accessor_index].type;
Assert(array_type == TypeCode<T>(), "");
And I get this error:
Src/Engine/Animation/GltfLib.cpp:103:26: style: Variable 'array_type' is assigned a value that is never used. [unreadVariable]
const int array_type = model.a... | The warning is telling you that: when Assert is disabled, you are creating a variable that is never used.
I would suggest moving the statement into the assert statement; however, you can also use the processor to remove the code when debugging is disabled.
Assert(model.accessors[accessor_index].type == TypeCode<T>(), "... |
67,550,290 | 67,550,318 | A boolean class member that compares the address of the class instance that is never used in code, but is public? | This is a public function inside of a class which is meant to compare the addresses of instances of class RotaryEncoder.
I'm having trouble understanding what it does because it is never used in the code apart from declaration/definition.
bool RotaryEncoder::operator==(RotaryEncoder& b)
{
return (this == &b);
}
Any ... | It compares addresses of the objects. That means an instance can only be "equal to" itself and no other instance. It's like replacing a == b with &a == &b. Note that this method most likely should be marked with const noexcept as well as [[nodiscard]]. And perhaps even constexpr, but that depends on the design. The arg... |
67,551,074 | 67,551,211 | Does using postincrement within a fold-expression give unsequenced behaviour? | Recently I've came up with an idea how enumerate elements in a parameter pack (Pulses) and I've been happy with the solution for a while:
lastValue = 0.0; i = -1;
lastValue += (... + ((time <= endtimes[++i] && time >= delays[i]) ? static_cast<Pulses*>(fields[i])->operator()(time - delays[i]) : 0.0));
however now as I'... | Clang is right, the code causes UB.
Evaluation rules for fold expressions are exactly the same as for normal expressions.
Evaluations of the two operands of + (and of most binary operators) is unsequenced relative to one another (i.e. can happen in any order, possibly interleaved), and unsequenced changes of scalar var... |
67,551,172 | 67,551,362 | How is abstraction an advantage of OOP if it can also be done procedurally? | I am completely new to programming and don't understand why abstraction is an advantage of OOP. All sites mention abstraction as one of the key advantages of OOP but this can be achieved procedurally also.
If I write:
int add(int x, int y){
return x + y;
}
int main() {
int z = add(3,4);
}
Abstraction is used to... | Your question is not bad, but it is a bit naive. It's quite obvious that you're asking about topics quite ahead of you. Good thing you're curious though. I mean no offense.
Abstraction is not a binary thing that a language supports or not. Languages does more or less abstraction, but all languages are abstractions abov... |
67,551,202 | 67,551,524 | Can you output data in C++ without using any includes? | This is a thought experiment.
This question is intentionally trying to do something easy in a difficult way. I am aware of the many ways to do this using iostream, std.h, etc. Please do not suggest answers that circumvent the challenge.
Using C++,
Only using main() without any header files included, is it possible to w... | If you want to have no code outside of main, in C you could do this:
int main()
{
int puts(const char *);
puts("Sup!\n");
return 0;
}
Or the same thing with printf, or any other C standard library function.
It wouldn't work in C++ though, since in C++ the puts declaration needs extern "C" to disable name m... |
67,551,213 | 67,551,625 | Read process's 'stdout' output in Win32 C++ Desktop Application | I started a Visual C++ Desktop Application (win32) and created a button, that creates a process.
Here is the button code:
INT_PTR CALLBACK Btn_Click(HWND hWnd)
{
wchar_t cmd[] = L"cmd.exe /c testprogram.exe";
STARTUPINFOW startInf;
memset(&startInf, 0, sizeof startInf);
PROCESS_INFORMATION procInf;
... | If your UI thread stops pumping messages Windows treats it as frozen. This means you should not perform blocking I/O on this thread.
You could use asynchronous (overlapped) I/O with ReadFile but doing the whole child process operation in another thread is a lot easier. The button press would start the thread and once t... |
67,551,337 | 67,551,411 | First duplicate in a vector | I have the following code that finds first duplicate in a vector of integers:
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int find_duplicate(const vector<int> &v)
{
unordered_set<int> numbers;
for(const auto num : v)
{
if (numbers.count(num) > 0)
... | The C++ standard library is built around iterators rather than indices. If you change your find_duplicate function to return an iterator, this can be concisely written as:
auto find_duplicate(const vector<int> &v)
{
unordered_set<int> numbers;
return std::find_if(v.begin(), v.end(),
[&](int num) { retu... |
67,551,591 | 67,551,724 | How can I fix an assertion failure that states 'vector subscript out of range' | Other questions that I viewed before posting this question:
Debug Assertion Failed: Vector subscript out of range
Debug Assertion Failed Vector Subscript Out of Range C++
I am working on a Boids project, details of which can be found here:
https://www.red3d.com/cwr/boids/
From what I can gather my issue is something to... | I see nothing in this code that can cause an out of bounds access. However, you should not increment i on any loop iteration that removes an organism, otherwise you will skip the next organism in the list.
Imagine on the 1st loop iteration, the organism at index 0 needs to be removed. Subsequent organisms move down the... |
67,551,677 | 67,551,993 | C++ multiple type assignment | I not very familiar with C++, have some issues with the multiple assignments
int a = 0, b = 0;
works
int i;
double d;
char c;
c = i = d = 42;
also works
but why this does not works.
int a = 4, float b = 4.5, bool ab = TRUE;
| This is to do with the allowed syntax. The format is, in very high-level terms, roughly:
type varName [ = expr ][, varName [ = expr ] ]?;
Where there is no allowance at all for another type to be introduced mid-stream.
In practice declaring multiple variables per line can lead to a lot of ambiguity and confusion.
Quic... |
67,552,172 | 67,552,193 | How come non-static methods can be called without an object inside the class? | Wherever I search, I find that to use a method without an object, THE ONLY WAY IS TO MAKE IT STATIC. However,
in the following piece of code I show two examples of non static methods being called without an object FindIngredient and NumPizzas()((*) and (**)). It compiles and not even warnings are given. As you can see ... | When you call a member function from another member function, the object is implied - it's this->.
|
67,552,268 | 67,552,272 | Casting pointer to multidimensional array | How do I cast a pointer to a multidimensional array?
E.g. float* to float[][100][100]?
float* f1(); // returns allocated memory (with data), suitable for processing by f2
void f2(float in[][100][100]);
float* p = f1();
f2( ???CAST??? p);
| While it's normally dangerous to do so, you can use reinterpret_cast should you really want to:
f2( reinterpret_cast<float(*)[100][100]> (p) );
|
67,552,333 | 67,552,850 | cv::imread() in OpenCV not reading my .png | I am really new to OpenCV and I was wondering why my debug string for empty matrix is running when I check if I have a png in my directory. I can confirm that I do indeed have an image by given name in the specified directory.
relevant code:
cv::Mat imgTrainingNumbers;
imgTrainingNumbers = cv::imread("C:/Users/... | It is possible that the image you are using is of corrupted data. The imread() function will not return anything to your imgTrainingNumbers matrix if you...
a. have not specified the path correctly
b. the image is not in a proper format/is corrupted
c. some linking issue
Replace the image with something else to test th... |
67,552,685 | 67,552,780 | What is the difference between visiting a member vector in class and visit a vector created in another member function? | I was trying to solve Leetcode question 589 "N-ary Tree Preorder Traversal".
I have two implementations with same logic as below:
The first one is trying to visit and member vector in class:
class sth {
public:
vector<int> nums;
vector<int>
preorder(Node *root) {
if(!root)
return nums;
nums.push_bac... | In the first implementation every preorder call returns a vector by value. That means that for every single node you visit you're copying the vector you've built up to that point. Also, since the vector is part of the state of the sth object, calling preorder a second time will reuse the same vector that already has da... |
67,552,709 | 67,552,757 | Segfault sharing array between assembly and C++ | I am writing a program that has a shared state between assembly and C++. I declared a global array in the assembly file and accessed that array in a function within C++. When I call that function from within C++, there are no issues, but then I call that same function from within assembly and I get a segmentation fault... | Some of x86-64 calling conventions require that the stack have to be alligned to 16-byte boundary before calling functions.
After functions are called, a 8-byte return address is pushed on the stack, so another 8-byte data have to be added to the stack to satisfy this allignment requirement. Otherwise, some instruction... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.