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 |
|---|---|---|---|---|
73,906,884 | 73,908,736 | Code::Blocks build and run is not working on Chromebook | Whenever I try to build and run any C++ code (I didn’t try it with other programming languages) in Code::Blocks, a prompt pops up saying this:
it seems that the project has not been built yet. Do you want to build it now?"
with three options of No, Cancel, and Yes.
When I click Yes, the prompt closes, and it says th... | You must install g++ to compile C++ code. According to this question, you can use these commands to install it:
sudo apt update
sudo apt upgrade
sudo apt install build-essential
sudo apt install software-properties-common
sudo apt install gcc g++
|
73,907,342 | 73,907,534 | Sequence point, function call and undefined behaviour | main.cpp
const int& f(int& i ) { return (++i);}
int main(){
int i = 10;
int a = i++ + i++; //undefined behavior
int b = f(i) + f(i); //but this is not
}
compile
$ g++ main.cpp -Wsequence-point
statement int a = i++ + i++; is undefined behaviour.
statement int b = f(i) + f(i); is not undefined .
why?
|
statement int b = f(i) + f(i); is not undefined . why?
No, the second statement will result in unspecified behavior. You can confirm this here. As you'll see in the above linked demo, gcc gives the output as 23 while msvc gives 24 for the same program.
|
73,907,424 | 73,932,914 | Visual Studio Remote Makefile project - How to set the remote target program? | I have a visual studio c++ makefile project which I would like to run and debug from the IDE, however I am unsure how to set the remote debug target.
When I attempt a remote debug, the remote target be set to root build folder and I get the message
GDB Failed with message /home/myuser/myprojects/mytestprog is a directo... | The remote target program can be defined by setting the program property in the debug settings.
e.g.
$(RemoteOutDir)mytestprog
|
73,908,186 | 73,908,270 | Why is the declaration of std::unique_ptr valid with an abstract class | for example:
// Example program
#include <iostream>
#include <string>
class abstract_class
{
public:
abstract_class() = default;
~abstract_class() = default;
virtual void read() = 0;
};
int main()
{
std::unique_ptr<abstract_class> x;
std::cout << "Hello, " << "!\n";
}
I thought an Abstract Class ... | First things first, the argument types that you've mentioned in your question is for function call arguments and not for template arguments.
why isnt this an error.
Because you're creating a unique pointer to the abstract class object and not an object of the abstract class itself. That is, creating a pointer(whethe... |
73,908,494 | 73,908,495 | QMYSQL driver not loaded on Mac OS for Mac M1/M2 users | When I run following code:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("SecureChat");
db.setUserName("root");
db.setPassword("zTmUHsbEKZZlWhfofM");
bool ok = db.open();
qDebug() << db.lastError();
I receive error:
QT/C++ QSqlDataba... | The original solution I have found here thanks to the original author of the question and answer - chriam.
I will describe in this post some key points that are not mentioned in the original solution.
You have to install MySQL from Oracle cloud
Use QT maintenanceTool and choose the option Add or remove components. F... |
73,909,003 | 73,909,050 | C++ question about iterating over std::vector | My question ("why it doesn't work?") concerns the small sample below.
When I run this (after g++ testThis.cc -o testThis) I get:
printing 101
printing 102
printing 103
printing 100
printing 100
printing -1021296524
It sh... |
My question ("why it doesn't work?")
Because myHolder.getSV().begin() and myHolder.getSV().end() work on different vectors since you're calling the member function stdHolder::getSV() twice and for each invocation there will a different vector returned(as you're returning a vector by value).
That is, the iterator it i... |
73,909,767 | 73,910,304 | Why does g++ 11 trigger "maybe uninitialized" warning in connection with this pointer casting | After a compiler update from g++ v7.5 (Ubuntu 18.04) to v11.2 (Ubuntu 22.04), the following code triggers the maybe-uninitialized warning:
#include <cstdint>
void f(std::uint16_t v)
{
(void) v;
}
int main()
{
unsigned int pixel = 0;
std::uint16_t *f16p = reinterpret_cast<std::uint16_t*>(&pixel);
f(*f16p... | You don't initialize an object of type std::uint16_t, so it is used uninitialized.
This error is suppressed by -fno-strict-aliasing, allowing pixel to be accessed through a uint16_t lvalue.
Note that -fstrict-aliasing is the default at -O2 or higher.
It could also be fixed with a may_alias pointer:
using aliasing_uint1... |
73,910,138 | 73,910,709 | C++ terminate a thread without having acces to the function executed in the thread | I'm making a script handlers in C++14. I get function body in a lua script, that is suppose to be given by a client ( I use interpreter Sol/lua ), and exectute it in a thread.
So my problems is if the client put a infinite loop (while true) in his script, I should be able to stop/kill the thread after 3 seconds.
I try... | Nicol Bolas said, "C++ has no mechanism to kill threads." That's because there is no safe way to kill a thread in any language or in any OS. You can never be sure that, at the moment when the thread is killed, it hasn't left something in a bad state—e.g., left a mutex locked, left a data structure in an invalid state—t... |
73,910,618 | 73,913,945 | How to Handle Collision in 3D Grid based Game | How do games like 3D Games Minecraft with a grid handle collisions
their are thousands of block divided into chunks each with its own bounding box
how is collision detected calculated and processed
i tried AABB but it didnt work well with each block having its own collider
is their a way to check collision with a WHOLE... | Minecraft first calculates the player's AABB, then rounds it bigger to a whole number of blocks on each side, then checks whether the player's AABB (not rounded) collides with the AABB of any of the blocks in the rounded AABB.
One extra block is added on the bottom, because fence blocks have AABBs that go up into the n... |
73,911,182 | 73,911,225 | box2d falling while moving | Hey my player isn't falling while I'm pressing any of movement inputs while I'm falling. Just stands still and moves right or left.
Just watch the video; Video
My movement code;
if (right == true) {
p_pBody.body->SetLinearVelocity(b2Vec2(5, 0));
}
else
{
p_pBody.rect.setPosition(p_xPos * s_METPX, p_yPos * s_MET... | You're setting the vertical velocity to 0 when you're pressing right or left. That's the second coordinate of b2Vec2. If you want to have gravity, replace that zero with the vertical velocity the block has when the buttons are not being pressed.
|
73,911,444 | 73,920,036 | How to use CHILDID_SELF? | I found this article and tried to follow it to find the position of the caret in any Windows application:
How to get caret position in ANY application from C#?
However, I have a problem with following it.
This is the C# code I was following:
var guid = typeof(IAccessible).GUID;
object accessibleObject = null;
var retVa... | Your first code snippet is the correct way to pass CHILDID_SELF in a VARIANT parameter, per the documentation:
How Child IDs Are Used in Parameters
When initializing a VARIANT parameter, be sure to specify VT_I4 in the vt member in addition to specifying the child ID value (or CHILDID_SELF) in the lVal member.
So, th... |
73,911,466 | 73,911,730 | How come Gdiplus SolidBrush's RGB is different from regular RGB? | I'm trying to paint a simple header on top of my Window with Gdiplus' SolidBrush, but whenever I set the RGB color it's different from what it's suppose to be.
How come this is happening? And is there a way to fix that?
Thanks!
Gdiplus' SolidBrush RGB:
Regular RGB:
| You are using the Color constructor taking four arguments, a, r, g, and b, in this order. (255, 255, 0, 0) thus means: Fully opaque (first value), red channel at full intensity (second value), and no contribution from other color channels.
In other words: You're creating a fully opaque red brush as illustrated in the a... |
73,911,521 | 73,911,594 | Nan behaves differently in #pragma cpp | I am learning about the NaN datatype, so, I ran a code to understand it and it goes well, the code worked as expected, but when I add a line #pragma GCC optimize("Ofast") in my code then, it behaves unexpected. I am curious why??
#pragma GCC optimize("Ofast")
// C++ code to check for NaN exception
// using "==" operato... | -Ofast turns on -ffast-math, which turns on -ffinite-math-only, which does the following (from the gcc documentation here: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)
-ffinite-math-only
Allow optimizations for floating-point arithmetic that assume that
arguments and results are not NaNs or +-Infs.
This o... |
73,911,952 | 73,911,975 | Copying values from base class to derived class | Didnt want to put a really long title, continuing - without modifying the base class and without copying one by one.
Lets say the base is CClient, but I dont want to add or remove anything:
class CClient
{
public:
void (*Connect)();
void (*Disconnect)();
bool m_bIsConnected;
};
And say this is derived CCl... | Given
CClient a;
CClientHook b;
There are at least two options:
static_cast<CClient &>(b) = a;
b.CClient::operator=(a);
|
73,912,729 | 73,912,730 | What's the name of all the angle brackets? | In C++ we have angle brackets in different places and I think it's sometimes important to distinguish them when talking to other developers, e.g. during mob programming when navigating someone (e.g. "go to the arrow operator in line 36" or "now write the spaceship operator"). While I can of course call them "angle brac... | In many cases, the angle brackets do not have a name themselves, because they are part of another construct.
is called relational operator [source: C++ 20 standard, chapter 7.6.9, [expr.rel], page 140], also comparison operator or just less-than operator and greater-than operator
is called shift operator [source: C++... |
73,912,844 | 73,913,417 | .txt File passed into ifstream turns contained data into garbage characters? | I'm trying to make a simple program for a comp sci class that goes through a list of data in a text file, and assigns it to two different arrays using pointer notation, but I'm running into an issue where the file I'm reading will be corrupted after running the program, but even when the program is terminated and resta... | It seems like it wasn't an issue with the code at all, but an issue with how windows notepad would first read the file in UTF-8, and after running the program, would switch over to UTF-16 LE as Avi alluded to in the comments.
|
73,913,006 | 73,913,076 | Why is GCC giving me a use of uninitialized value warning? | I've been working on a large C++ program and I forgot to add my usual list of compiler flags/warnings when working on a C project. After enabling the -fanalyzer flag, I began to get a lot of "warning: use of uninitialized value '<unknown>'" messages from GCC 12.2 throughout my code. Here is an isolated example I was ab... | It is clearly a false positive. The analyzer complains about any function returning a std::string (and other standard library types), e.g.
#include <string>
std::string f() {
return {};
}
as well. (https://godbolt.org/z/oKrfrbn5o)
Surprisingly I could not find any previous bug report on this seemingly obvious iss... |
73,913,232 | 73,924,933 | Defining the size of an array on a custom templated Array class | I am making a project to write from scratch several datastructures, procedures, probably a mini-testing framework... things already well known and coded, but just with the purpose of learn and to adquire a much more deeper knowledge of the fundamentals of programming, but in a modern way, or, at least, using the modern... | Your are looking for the std::size_t, which can be found on some system headers. Extracted from cppreference:
Defined in header cstddef
Defined in header cstdio
Defined in header cstdlib
Defined in header cstring
Defined in header ctime
Defined in header cuchar
Defined in header cwchar (since C++17)
Basically, you sh... |
73,914,306 | 73,915,038 | PrintDlgEx invalid argument, while PrintDlg works | Problem: I need to get PrintDlgEx working for my project, but no combination of options or arguments works for me. It gives E_INVALIDARG for any combinations of options, as the ones I copied from Microsoft samples or other online samples.
Replacing PRINTDLGEX with PRINTDLG and PrintDlgEx with PrintDlg (and eliminating ... | I can make your example work if I remove PD_NONETWORKBUTTON flag.
Please note that while it is documented for PRINTDLGA struct, it is NOT listed in PRINTDLGEXA
NOTE: I did get the same error with that flag.
|
73,914,315 | 73,914,362 | Can you "swap" slices of C++ std vectors? | If I have two C++ vectors:
vector<int> a(5) {1,2,3,4,5};
vector<int> b(5) {6,7,8,9,10};
is there a one-line way to use the swap method to swap slices of a and b? Something like
swap(a[something ... something], b[something ... something]);
giving, for instance
a equal to {1,9,10,4,5} and b equal to {6,7,8,2,3}?
| std::swap_ranges.
std::swap_ranges(a.begin()+1, a.begin()+3, b.begin()+3);
Demo
|
73,914,499 | 73,914,628 | How to delete a specific node in a linked list? | I have the next linked list code:
#include <iostream>
#include <string>
using namespace std;
#define null 0
class Node
{
public:
string name;
int age;
Node *next;
Node(string name, int age)
{
this->age = age;
this->name = name;
this->next = null;
}
};
class LinkedList
{... | your problem is so simple, it's in that line:
while (temp != null && temp->name == name)
it should be:
while (temp != null && temp->name != name)
as the condition of looping, you are looping until you either didn't reach the end (temp != null) or the name isn't found in this iteration (temp->name != name).
also, ther... |
73,914,687 | 73,914,701 | Deleting a dynamic array of vectors | I believe this should be pretty simple and straightforward. Why am I getting an error?
Here is the code:
std::vector<double> *myVectorArr;
myVectorArr = new std::vector<double>[10];
delete myVectorArr;
The error I get is:
munmap_chunk(): invalid pointer
Aborted (core dumped)
Why would I be getting this error?
Thanks... | You need to use the operator delete [] instead of the operator delete
delete [] myVectorArr;
|
73,915,429 | 73,915,726 | Why does my program terminate when it should continue? | #include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
cout << "What question would you like to ask the Magic 8 ball?: \n";
cout << "\n";
cin >> question;
answer = rand () % 8 + 1;
if (answer ==... | you did most of the work you just have to make a loob like so
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
while(play!="no"&&play!="n")
{
play = "";
cout << "What question would you like to as... |
73,915,510 | 73,915,698 | use std::string to call a function in C++11 | I want to use string value to call a function. Is this possible? Can someone please show some implementation. I would appreciate it.
class obj {
int num1;
int num2;
}
int func1(obj o) {
return o.num1 + o.num2;
}
// This is an example data set. This map would be populated with values in the map below with s... | One solution is to create a mapping from function name to function itself. We know that a function is a pointer in C/C++, so we can easily do this after confirming the type of the function pointer. In your case, the target function type is int (*)(obj).
Code snippet:
#include <iostream>
#include <map>
#include <string>... |
73,915,646 | 73,915,710 | How to create a click effect on a QLabel? | How i could create a click effect similar to push buttons on a QLabel?
QPixmap pixmap;
pixmap.load(":/files/hotkeys.png");
int w = 131;
int h = 71;
pixmap = pixmap.scaled(w, h, Qt::KeepAspectRatio);
// Label
ui.label->setGeometry(220, 220, w, h);
ui.label->setPixmap(pixmap);
// Button
QIcon icon(pixmap);
ui.toolButt... | Ideally you'd just use a QToolButton or QPushButton, but if you must use a QLabel, you could do it by subclassing QLabel with a custom paintEvent() to give the desired effect, something like this:
class MyLabel : public QLabel
{
public:
MyLabel(const QPixmap & pm) : _isMouseDown(false) {setPixmap(pm);}
virtual v... |
73,916,368 | 73,932,520 | Invalid value while PeakCAN canbus frame printing QT C++ | I'm trying to read and print the frame from canbus using the peakcan plugin with QT, but I think I'm making a mistake somewhere.
This is my code :
qDebug() << "connectCanDevice";
if (QCanBus::instance()->plugins().contains(QStringLiteral("peakcan"))) {
// plugin available
... | OK, I see you're missing some points here, this is an simple code example that do the work:
if (QCanBus::instance()->plugins().contains(QStringLiteral("socketcan")))
{
QString errorString;
QCanBusDevice *device = QCanBus::instance()->createDevice(
QStringLiteral("socketcan"), QStringLiteral("ca... |
73,916,679 | 73,922,811 | Copying variables, creating temporary variables and move semantics | I was learning about move semantics and rvalue references when I came across this web page https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n2027.html. There is a piece of code that confuses me.
Without move semantics
template <class T> swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a
a = ... | Let a' and b' be the values in a and b before the function.
template <class T> swap(T& a, T& b)
{
T tmp(a); // now we have two copies of a' (in a and tmp) and one of b' (in b)
a = b; // now we have two copies of b' (in a and b) and one of a' (in tmp)
b = tmp; // now we have two copies of a' (in b and tm... |
73,917,256 | 73,953,709 | what grpc c++ `grpc_prefork()` does? | In docs of grpc_prefork() it is written that
gRPC applications should call this before calling fork().
There should be no active gRPC function calls between calling
grpc_prefork() and grpc_postfork_parent()/grpc_postfork_child().
what this function does? why is it needed?
what are grpc function calls? If I have a se... | To start, this function is a part of gRPC Core, not gRPC C++. This is an API for developers of new language bindings for gRPC, e.g. Rust, Haskell. If you're just working with C++, then the grpc_prefork function does not apply to you and you can stop reading.
grpc_prefork is how we deal with the fact that threads and th... |
73,917,303 | 74,160,554 | Spectra is not computing any values for large sparse matrix? | In a C++ program I computed a large sparse matrix energy_mat which I know is symemtric.
I am trying to compute its condition number by getting the largest and smallest eigen values like this:
Spectra::SparseGenMatProd<double> op(energy_mat);
Spectra::GenEigsSolver<Spectra::SparseGenMatProd<double>> eigs(op, 3, ... | Increasing the number of iterations from 6 to 40 seems to have fixed the issue.
|
73,917,322 | 73,917,566 | Check number range in Preprocessor macro | To set the clock prescaler on the Atmega32u4, you have to set TCCR0B according to this table:
If you want the prescaler to be 64, you would write this:
TCCR0B |= BV(CS01) | BV(CS00);
btw, here is BV():
#define BV(x) (1<<x)
I want to do this using a macro, this is what I have so far:
#define CLK_SEL(n) ((n == 256 || ... | Tail wagging the dog; trying to convert some arbitrary bit pattern to one from a selected. limited range...
int main() {
enum { ePreScl_1 = 1, ePreScl_8, ePreScl_64, ePreScl_256, ePreScl_1024 };
printf( "%X\n", ePreScl_1 );
printf( "%X\n", ePreScl_8 );
printf( "%X\n", ePreScl_64 );
printf( "%X\n", ... |
73,917,624 | 73,917,739 | Does this cause memory leakage by not freeing the function pointer? C++ | Does this code architecture cause memory leakage by not freeing m_func?
And could this be tempered with if this code would be executed at a closed server? Like finding the address of the pointer and replacing the code of the function pointee with malicious code? If so how could I solve this?
#include <iostream>
templat... | Assuming the prototypes of all your 'hello world' functions is the same (int return value, no parameter), you don't need templates at all. Just store a function pointer.
typedef int (*Func_t)();
int hello_world() {
std::cout << "Hello World! \n";
return 0;
}
int hello_world2() {
std::cout << "Hello World 2!... |
73,917,724 | 73,917,894 | How to let gcc optimize std::bit_cast with std::move? | Consider below code:
#include <cstdint>
#include <bit>
#include <utility>
struct A { uint32_t a[100]; };
struct B { uint16_t b[200]; };
void test(const A&);
void foo() {
B tmp;
test(std::bit_cast<A>(std::move(tmp)));
}
void bar() {
B tmp;
test(reinterpret_cast<A&>(tmp));
}
For clang 15 with -O3, fo... | std::move into std::bit_cast is completely pointless and doesn't have any effect at all since std::bit_cast has a lvalue reference parameter and no rvalue reference overload.
In your test case tmp is never used in foo except to read (uninitialized!) data from it. It is therefore clearly a missed optimization by the com... |
73,918,086 | 73,918,171 | constexpr variable use const variable at initialization | Why the following example compile with no problems?
#include <iostream>
int main(){
const int var1 = 2;
constexpr int var2 = var1 * 5;
return 0;
}
According to theory:
“Variables” that are not constant expressions (their value is not known at compile time)
I used gcc compiler, can be the case that each compile... |
Why the following example compile with no problems?
The full-expression of any constexpr variable has to be a constant expression, i.e evaluable at compile-time.
Your initializer var*5 is a constant expression because var is const-qualifed integral type that is itself initialized by integral constant expression; also... |
73,918,093 | 73,918,113 | prvalue vs xvalue for class types | I've got more confused when I see this question: Is a class instantiation--class_name() a xvalue or a prvalue? I'm trying to understand what does it mean by a class prvalue and a class xvalue. Someone tell me that they're called value category. But I think it would be better if I provide an example, because I'm very co... | The expression myclass() is explicit type conversion using functional notation, per [expr.type.conv]/1:
A simple-type-specifier or typename-specifier followed by a
parenthesized optional expression-list or by a braced-init-list (the
initializer) constructs a value of the specified type given the
initializer [..]
Here... |
73,918,767 | 73,922,524 | Displaying the sizes of all objects, containers, programs etc. С++ | Let's imagine that we have a big project. In which there are many classes, objects of these classes, containers of objects, and so on.
Can I view the dimensions of all these objects? Output, for example, a table or a list of all objects, containers, with their sizes.
Of course, for a project, for example, in 20000+ lin... |
Output, for example, a table or a list of all objects, containers, with their sizes.
Of course, for a project, for example, in 20000+ lines, I will not be able to display everything by hand.
Yes, you can do that. Either by writing appropriate object-tracking code and linking it into your program, or by writing a GDB ... |
73,918,842 | 73,918,903 | Why not have all variables be a constexpr? | sorry if this sounds like a dumb question but I dont have much experience with C++ programming and im trying to learn as much as a I can about its syntax. I came across the specifier constexpr and was wondering that if it allows you to save time at runtime, why not declare all your variables with it?
| First of all not all variables can be made constexpr. For example
int x;
std::cin >> x;
Obviously x cannot be constexpr. The value it will have after it has been read from input is not a compile-time constant.
Second, constexpr is part of the contract of a variable or function. By marking it constexpr, you allow other... |
73,919,215 | 73,989,643 | Can not link yaml-cpp with my cmake project | My CMakeLists.txt
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(test_includes)
#find_package(Boost COMPONENTS system filesystem REQUIRED)
#include_directories( ${Boost_INCLUDE_DIRS} )
set(Torch_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libtorch/share/cmake/Torch")
find_package(Boost COMPONENTS system filesystem R... | it was pre C++11 ABI issue
the solution can be found at:
https://github.com/pytorch/pytorch/issues/19353#issuecomment-652314883
|
73,919,258 | 73,919,319 | reinterpret_cast<const> casts away const qualifier? | In the following case I try to cast a pointer to a struct into a pointer to another struct (which has the same memory layout behind the scenes). I try to do this in a const correct way, however the compiler is complaining.
I looked at a similar issue but I need the constness to propagate and it doesn't work like descri... | const queue_handle applies the const to the pointer type itself, not the pointed to type as you intent to.
I would suggest adding a const_queue_handle alias to const queue* if you are already using aliases for the pointers (whether or not that is a good idea is a matter of opinion) and then you can use that as template... |
73,919,400 | 73,923,976 | Unable to transfer complete data stream from Arduino Uno at high baudrate | I am trying to transfer some data at 115200 Bd to a C# form RichTextBox. Below is my Arduino code:
void serialEvent() {
if (Serial.available()) {
int command = Serial.parseInt();
Serial.println(command);
switch(command) {
case 1:
/*executes its job and writes data in the following format in... | You mentioned 'Arduino', then your 'serial line' is likely a virtual USB-serial port.
I had similar problems about a month ago. But I had only control over the code at the receiving end and at a late point in time (for the project) some insight in the code at the sending end.
Virtual USB-serial connections are a known ... |
73,919,449 | 73,919,585 | How to use a vector in a vector | I am trying to use a for statement with a vector in a vector.
std::vector<std::string> array = {
{"A", "a"},
{"B", "b"},
{"C", "c"}
};
for (std::string& a : array) {
if (letter == a[1] || letter == a[0]) {
std::cout << a[0] << ": " << a[1] << std::endl;
break;
}
}
I am new to C++ a... | I think {"A", "a"} is already a verctor, and this array varable type should be vector<vector<string>>.
|
73,920,004 | 73,921,029 | How to delete "end" node from a circular linked list using only tail in c++? | I need to write three separate functions for node deletion in a circular singly linked list (deleteFront(), deleteMiddle() and deleteEnd()). I have to use only tail (last). For some reason, my deleteEnd() function deletes second to the last node. Can anyone please help?
struct node
{
int data;
struc... | There are several issues with your deleteEnd function:
There is no way that the caller can get the new tail reference, because the tail argument is passed by value. The tail parameter should be a pass-by-reference parameter.
The statement after the loop (in the else block) does not remove the correct node. After the ... |
73,920,103 | 73,926,710 | Sending numpy array (image) to c++ library with ctypes | I'm trying to make a python program that can run Photoshop Plugins by using this DLL library from Spetric - https://github.com/spetric/Photoshop-Plugin-Host
I need to send an image loaded by opencv to the dll (while I can read c++ I cannot program in it and have never been able to get the dll to compile for edits such ... | This is a duplicate of [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer), but I'm going to detail.
When working with CTypes, the .dll must export functions using C compatible interface (extern "C"), while pspiSetImage seems to be C++ (default arguments).
Also check [SO]: How ... |
73,920,562 | 73,920,662 | How can I set User Input from Code in C++? | I am creating a test for a function which gets the user input with std::cin, and then returns it. The test just needs to check if the input from the user, is the one actually returned.
Problem is, the test should be automated so I can't manually react to the std::cin prompt. What can I do to set the input with code?
| I wouldn't bother with automation or redirection of the std::cin functionality.
From personal experience it always get much more complicated than it has to be.
A good approach would be to separate your behavior.
Bad:
void MyFunction()
{
std::string a;
std::cin >> a;
auto isValid = a.size() > 1;
}
Better:
... |
73,920,645 | 73,920,682 | Function Pointer Initialization in C/C++ | As I was going through a ESP IDF's documentation; I saw that a function pointer was initialized in a certain way that does not make sense to me.
typedef void *app_driver_handle_t;
app_driver_handle_t app_driver_light_init();
app_driver_handle_t app_driver_button_init();
Etc.
I thought that in order to initialize a fu... | Let's break down the code you're looking at.
typedef void *app_driver_handle_t;
This is not a function pointer. This is a void pointer, which means it can point to basically any values. And this is a type, not a value, so app_driver_handle_t does not actually contain any pointers at all; it's merely a name that's syno... |
73,921,009 | 73,922,711 | Kaprekar Number between given range | I'm trying to print all Kaprekar Numbers between Given Range
As input the range is between --> 1 to 99999 <--
The Expected Output :
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121 99999
but I got this output :
1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22... | All the variables used in the posted snippet are of type int, which is probably1 not enough big to store the squares of all the possible input values, so that, as note by Igor Tandetnik in their comment
Your program exhibits undefined behavior by way of integer overflow.
Using a wider type, like long long2 or int64_t... |
73,922,014 | 73,930,998 | AutoCAD ObjectARX c++ What is the syntax to convert a AcString to a std::string value? | I am very new to ObjectARX and c++ and I hope you can help.
I am using AutoCAD 2023 and Visual Studio 2019.
I have successfully compiled and loaded my c++ function as ARX and called from within AutoLISP.
(myfunc "Hello World")
I have managed to get the value of Lacstring_parameter_passed_to_myfunc "Hello World"
What s... | Try this:
AcString base = _T("testżźę");
CT2CA pszConvertedAnsiString(base);
std::string strStd(pszConvertedAnsiString);
|
73,922,406 | 73,922,447 | How to pass tuple elements to callable in C++ | How do I pass the elements of a tuple as arguments to any callable in C++? std::apply works only when the callable's arguments exactly match those of the tuple's.
For instance:
struct Foo {
template<typename... Ts>
Foo(std::string s, Ts&&... ts) {}
}
int main() {
auto tup = std::make_tuple(5, 5.5f, 100000l);
... | Either you can specify template arguments, thereby choosing the overload; or, you might do a simple forwarding lambda:
Foo f = std::apply([&](auto&&... args){ return Foo("", std::forward<decltype(args)>(args)...);}, tup);
Note that here I have added the first parameter as a string; an int is not accepted by Foo there.... |
73,922,440 | 73,922,778 | return the output value of a function that asks for an output variable | Title is a bit messy, but i dont know how to simplify it. This is what i want to do:
nodeReceivedData[packetSize+1] = itoa(LoRa.packetRssi(), [output], 10);
itoa() always asks for a input variable, output variable and a size modifier. What I want to do, is to avoid having to make a ... | Since "itoa" expects the 2nd argument to be "char*" and 'nodeReceivedData' is byte (assuming it is just an "unsigned char"), you can just cast it to a char* and should work as expected:
itoa(LoRa.packetRssi(), (char*)&nodeReceivedData[packetSize+1], 10);
|
73,922,651 | 73,922,675 | Is it possible to know in a destructor that an r-value referrence is being deleted? | I was testing my own RAII pointer implementation that does some weird stuff (by design). To test it, I made a class that tracks constructors and destructors and makes sure everything is deleted and created exactly once.
But I was constantly getting an error that I'm deleting something twice. Weird, right. I found out w... | This has nothing to do with a destructor getting called for an r-value reference, or not. A destructor is a destructor. An object is getting destroyed. The End. The particular details of the object are immaterial.
ReportDelete& operator=(ReportDelete&& moveHere)
{
name = std::move(moveHere.name);
re... |
73,922,781 | 73,922,833 | How to import a C++ class head and cpp file in a new cpp file | Here is an example C++ code.
header.h
class example {
int a;
int b;
public:
int sum(int i,int j);
};
cpp.cpp
#include<iostream>
#include"header.h"
int example::sum(int i,int j){
a=i;
b=j;
return a+b;
}
int main(){
example e1;
int b=e1.sum(32,34);
std::cout<<b<<std::endl;
return 0;
}
main... | You should compile with the command g++ cpp.cpp main.cpp, and comment out the main function in cpp.cpp.
|
73,922,876 | 73,923,134 | Drawing a simple rectangle in OpenGL 4 | According to this wikibook it used to be possible to draw a simple rectangle as easily as this (after creating and initializing the window):
glColor3f(0.0f, 0.0f, 0.0f);
glRectf(-0.75f,0.75f, 0.75f, -0.75f);
This is has been removed however in OpenGL 3.2 and later versions.
Is there some other simple, quick and dirty,... |
Is there some ... way ... to draw a rectangle ... without using shaders ...?
Yes. In fact, AFAIK, it is supported on all OpenGL versions in existence: you can draw a solid rectangle by enabling scissor test and clearing the framebuffer:
glEnable(GL_SCISSOR_TEST);
glScissor(x, y, width, height);
glClearColor(0.0f, 0.0... |
73,922,896 | 73,923,000 | Why does == work and = does not in an if statement? | for (unsigned int i = 0; i < list.size(); i++) {
if (list.at(i) = n) {
cout << "True";
return 0;
}}
I was wondering why this would not work I understand that tou should use list.at(i) == n.
However i thought that a single = means assigning, and a double == means equal to. I understand it is d... | It would not necessarily be correct. When you use an assignment expression as a boolean for integers, it will return true if the integer is not zero, and it will return false if the integer is zero.
Suppose our list looks like this: 1, 2, 0, 5. Now, suppose we have this if-statement:
if (list.at(0) = 1) {
cout << "... |
73,922,977 | 73,923,155 | Embedding an SVG as std::string in C++ source code | ALL,
I finally moved away from the bitmaps and trying to use SVG in my C++ code.
I made an SVG using an InkScape and saved it as Compressed.
Then I edited the resulting file by adding the
static const char data[] =
in front of the XML and place every single line of XML inside double quotes.
The resulting file then is ... | You may want raw string literal introduced in C++ 11.
static const char data[] = R"xxx(<?xml version="1.0"...)xxx";
This is equivalent to
static const char data[] = "<?xml version=\"1.0\"...";
|
73,922,989 | 73,923,025 | How to write string to .txt file in C++ using FILE | I have string str = "6.5.1"
I want to write str to file .txt, but the result is ��j
Here my code
FILE *outfile = fopen("solution.txt", "w");
string test = "6.5.1";
fprintf(outfile, "%s\n", test);
I use string, FILE because I want to pass FILE as an argument, and convert string from another file to method.
How can I fi... | You clarified that you needed a c++ solution and required to use FILE *:
#include <cstdio>
#include <string>
int main(void) {
FILE *outfile = std::fopen("solution.txt", "w");
std::string test = "6.5.1";
std::fprintf(outfile, "%s\n", test.c_str());
std::fclose(outfile);
}
|
73,923,076 | 73,923,580 | Flash "CurveTo" and "LineTo" in Shapes | I'm working in trying to display some old SWF files with Direct2D.
I found swfmill which, for a simple SWF (found here) that displays a "W"
produces XML code, part of which is this one:
<ShapeSetup x="-214" y="470" fillStyle1="1"/>
<LineTo x="-20" y="0"/>
<CurveTo x1="-35" y1="-74" x2="-4... | Probably, coordinates are all relative. So you need to calculate positions incrementally.
For example,
<ShapeSetup x="-214" y="470" fillStyle1="1"/>
<LineTo x="-20" y="0"/>
<CurveTo x1="-35" y1="-74" x2="-45" y2="-109"/>
:
are to be translated to
pSink->BeginFigure(D2D1::Point2F(-214, 470), D2D1_FIGURE_BEGIN_FILLED);
... |
73,923,145 | 73,923,278 | How do you include your own custom class in C++ | I'm trying to learn how to properly create separate classes in my c++.
Every tutorial on classes have the custom class in the same file like this.
I found this question on combining different files but it doesn't deal with classes.
I've created 3 simple files to learn creating classes in different files.
car.h
#ifndef ... | If you really want the bodies separate, your Car.cpp should look like this:
#include "car.h"
Car::Car(){
wieght = 10.0;
}
Car::Car(double wieght){
this->wieght = wieght;
}
double Car::get_wieght(){
return wieght;
}
void Car::set_wieght(double wieght){
this->wieght = wieght;
}
~Car::... |
73,923,148 | 73,923,186 | Why does the output always show 0 as LCM? | ERROR: type should be string, got "\nhttps://github.com/mehedihasrifat\n\nPlease correct my mistake**\n\nHow can I solve this issue?\n\nDid I do something wrong here?**\n\n\nI have been trying to debug this code but ultimately I can't. Please help me, I'm totally new to this platform.\nThis picture shows the following code\n/*\nWritten by Mehedi Hasan Rifat\nWritten on October 2, 2022\n*/\n\n#include <stdio.h>\n\nint main()\n{\n int a, b, t, gcd, lcm;\n\n printf(\"Enter two numbers: \");\n scanf(\"%d %d\", &a, &b);\n\n if (a == 0)\n gcd = b;\n else if (b == 0)\n gcd = a;\n else\n {\n while (b != 0)\n {\n t = b;\n b = a % b;\n a = t;\n }\n\n gcd = a;\n }\n\n lcm = (a * b) / gcd;\n\n printf(\"LCM: %d\\n\", lcm);\n\n return 0;\n}\n\n" | As jasonharper says in the comment, when you finished the gcd calculation, b will be always zero.
One quick fix is to add
int original_a = a;
int original_b = b;
and calculate lcm using:
lcm = (original_a * original_b) / gcd;
Or just use the __gcd() function in the <algorithm> library.
#include <algorithm>
int main(... |
73,923,154 | 73,923,314 | How can I check, straight away, if a set of pairs have a commom number? | Suppose we have 4 pairs, e.g.:
pair<int, int> P1(1, 2);
pair<int, int> P2(3, 1);
pair<int, int> P3(2, 1);
pair<int, int> P4(1, 5);
How can I compare those 4 pairs straight away and conclude that they all have the number 1 in common? I can only think of comparing two by two, but that is a lot of work for a lot of pairs... | In the sample code you've given, you need to check each pair (P1, P2, etc) separately (e.g. if (P1.first == 1 || P1.second == 1 || P2.first == 1 || <etc> )).
If you insist on having P1, ... P4 as distinct variables, there are no shortcuts on that, since you've defined P1, P2, ... P4 in a way that imposes no logical or... |
73,923,232 | 73,931,330 | How to simplify variable parameter template functions? | Recently, I came up with an idea when learning to call function pointers. I used template variable parameters to construct template functions so that I can call function pointers
#include<functional>
#include<Windows.h>
template<class T, class ...Args>
decltype(auto) ExecuteFunc(LPVOID f, Args&& ...args) {
if (f !=... | Thank you to all our friends for your support and comments.
Your enthusiastic comments have provided me with constructive help
At the moment I have accepted a more simple answer, which meets my needs very well.
The code and examples are as follows
template<class T,class F, class ...Args>
inline decltype(auto) ExecuteFu... |
73,923,530 | 73,923,827 | How to distinguish between pr-values and x-values | In the following code,
#include <utility>
struct literal_type
{
// ...
};
class my_type
{
public:
my_type(literal_type const& literal); // (1)
my_type(literal_type && literal); // (2)
// ...
};
void foo()
{
literal_type literal_var { /* ... */ };
my_type var1 (literal_var); ... | You can't. You can distinguish xvalue and prvalues at the call site, but once you've passed them to a function that accepts them, you've lost the information of which of the two it was.
The reason is that the value category is a property of an expression, and inside of the constructors literal has always the lvalue val... |
73,923,608 | 73,923,732 | Why are these 2 sectors different? | i tried to read ntfs partition.
main function:
int main(int argc, char** argv)
{
BYTE sector[512];
ReadSector(L"\\\\.\\E:", 0, sector);
PrintBPB(ReadBPB(sector));
BYTE sector2[512];
ReadSector(L"\\\\.\\E:", 0, sector2);
PrintBPB(ReadBPB(sector2));
return 0;
}
ReadSector function:
int ... | The bug is in the code we cannot see: PrintBPB. Apparently it switches to hexadecimal output (for the "Volume serial number") and then fails to switch back to decimal until later.
When the code calls PrintBPB a second time the output mode is still in hexadecimal format, and printing "Bytes per Sector" now displays 200 ... |
73,923,683 | 73,923,722 | what does while(pointer) and if(pointer) mean? | I don't know why 'currentNode'pointer is in () beside 'while' and 'if'.
Node* currentNode = head;
while (currentNode) {
Node* toBeDeleted = currentNode;
currentNode = currentNode->next;
delete toBeDeleted;
......}
Node* successor = currentNode->next;
Node* predecessor = currentNode->previous;
... | A pointer variable is compatible with boolean in C. C considers every not-null pointer variable as True, and every variable pointing to NULL is considered as False.
|
73,924,259 | 73,930,415 | Is there a way to put as a parameter only one row of a 2d array? | I'm trying to call the getAverage function in the last cout on printResults, but when I call it, it just give me the same average for all the cases. For example, if I put that first students grades are 50 50 and 50, the average would come 50 for the second and third even if they have different scores. I tried a loop wi... | In the comments section of your question, you stated that the line
int getAverage(int scores[][EXAMS], const int students)
was written by you and not provided by the assignment.
However, according to the code comments above the function definition (which I assume were provided by the assignment and not written by you)... |
73,924,294 | 73,924,314 | cannot access member data via ' *this ' | Say if I have a class named cube which refers to a 3D cube, and it has a private member data called _height. Within the class I tried to use
this->_height
and it works. (I know '_height' along is enough. I just want to try more about 'this' pointer).
However when I use
*this._height
inside the class. It reports error... | Due to the precedence of the . over the * you need to put brackets around to make sure you get what you want:
(*this)._height
|
73,924,477 | 73,924,571 | Passing an array to a function declared in two different ways | So, I have declared an array using the <array> header in C++, and now I want to pass this array to a function that doesn't return any value but displays each element in a new line on the terminal. Following is the code for that.
// to pass an array to a function
#include <iostream>
#include <array>
using namespace std;... | The problem is that your function expects an int* but you're passing a array <int, 5> but since there is no implicit conversion from array <int, 5> to int*, we get the mentioned error.
You can also use std::array::data as myFunction(arr.data()); to make this work.
The reason your second case works when you create arra... |
73,924,910 | 73,924,958 | How to ignore parameter pack arguments | With the expression
(void)var; we can effectively disable unused variable warnings.
However, how does that work with arguments in a parameter pack?
template<bool Debug = DebugMode, typename... Arg>
void log_debug(const Arg&... args) {
if constexpr(Debug) {
(std::clog << ... << args) << std::endl;
} else... | I suggest using maybe_unused:
template<bool Debug = DebugMode, typename... Arg>
void log_debug([[maybe_unused]] Arg&&... args) {
If you for some reason don't want that, you could make a fold expression over the comma operator in your else:
} else {
(..., (void)args);
}
|
73,925,410 | 73,925,476 | static check an out of bounds | I have this method, that just gets an element of a member, which is a c-style array.
constexpr T get(const int&& idx) const {
static_assert(idx >= sizeof(array) / sizeof(T));
return array[idx];
}
I would like to statically check for a value on the parameter that will try to recover an element on the member tha... | idx is not a compile-time constant, so you cannot assert this at compile-time (which is what static_assert is for). You don't know at compile-time what values the function will be called with.
You can use a runtime assert from <cassert> instead, however that is typically meant for debug builds only (defining the macro ... |
73,925,567 | 73,927,090 | Char sort plus print with rows and columns | Hello i really need help, should make from two chars to camper first with second and if some symbol is include, should print them in row and column, also in same position where they are same; if my inputs are gold and xxlz should look like this.
x
x
gold
z
if they they dont had same symbol should pr... | You solved already the comparison of each character of both words.
Now, after having found a match, you need to show the crossword. For that, we imagine a 2-dimensional grid of rows and columns. Like the below
column
row 01234
0 x
1 x
2 gold
3 l
4
We need to print row by row. If the row is equal... |
73,925,683 | 73,925,716 | Iterating over an std::vector two elements at a time plus last and first elements too | I am trying to iterate over a vector say {1,3,4,2} and collecting pairs basically (1,3), (3,4), (4,2), (2,1). Collecting the first three pairs is easy but doing the last one is a bit difficult.
This is what I have:
#include <vector>
#include <iostream>
int main()
{
auto v = std::vector<int>{1,3,4,2};
auto vecO... | It is simpler if you use plain subscripting. You can then add 1 and take the remainder with % v.size():
for(size_t i = 0; i < v.size(); ++i) {
vecOfPairs.emplace_back(v[i], v[(i + 1) % v.size()]);
}
|
73,926,356 | 73,927,946 | How to examine bytes in gdb without printing labels? | GDB is trying to be helpful by labeling what I believe are global variables, but in this case each global is more than 0x10 bytes and so the second part of the variable is printed on the next line, but with an offset added to its label, which throws off the alignment of the whole printout (generated by executing x/50wx... |
Is there a command to disable these labels while examining bytes?
I don't believe there is.
One might expect that set print symbol off would do it, but it doesn't.
The closest I can suggest is this answer.
|
73,927,045 | 73,927,109 | Is there a way to give a specification about the allowed values of a non-type template parameter? | For example, is there a way of saying "n must be larger than 2" in this code?
template<int n>
class MyClass
{
...
}
| Use requires from C++20:
template <int n> requires(n > 2) // The parentheses are often optional, but not with this condition.
class MyClass
{
// ...
};
Alternatively you can use a static_assert:
template <int n>
class MyClass
{
static_assert(n > 2, "N must be less or equal to 2."); // The description is option... |
73,927,213 | 73,927,301 | std::regex_search return multiple matches | In regex engines that I'm familiar with, it's possible to return every instance of a matching substring. E.g. the following Perl code gives the output shown:
my $data = "one two three four";
my @result = ($data =~ /(\w+)/g);
say "@result";
output:
one two three four
So all four matches are returned, when the "g" mod... | You use std::sregex_iterator:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string const s{"one two three four"};
std::regex const r{"(\\w+)"};
for (std::sregex_iterator it{s.begin(), s.end(), r}, end{}; it != end;
++it) {
std::cout << it->str() << '\n';
}
}... |
73,927,332 | 73,927,472 | copy 2d vector without first row and column | Just like in topic. I would like to copy one vector to another without first row and column.
'''
std::vector<std::vector<int>> v2(v1.size()-1,std::vector<int>(v1.size()-1));
std::copy((v1.begin()+1)->begin()+1,v1.end()->end(),v2.begin()->begin());
return v2;
'''
| Using C++ and views it is easy to drop items while enumerating.
So you can avoid using raw or iterator loops.
Live demo here : https://godbolt.org/z/8xz91Y8cK
#include <ranges>
#include <iostream>
#include <vector>
auto reduce_copy(const std::vector<std::vector<int>> values)
{
std::vector<std::vector<int>> retval{... |
73,927,457 | 74,222,492 | Item views: setSelectionModel and support for row editing | In my Qt (6.3.1) application, for a model I developed, I noticed the submit() method being called all the time.
After some debugging, I noticed, in void QTableView::setSelectionModel/QTreeView::setSelectionModel, this:
if (d->selectionModel) {
// support row editing
connect(d->selectionModel, SIGNAL... | Answering my own question after 4 weeks without another answer nor any comment.
Despite having found a solution that seems to work in every case (see below), I still think this very design choice made by Qt as well as other special case they implemented are bad choices, would be interested to read other opinions in the... |
73,927,884 | 73,928,252 | Does C++ standard guarantee such kinds of indirect access well defined? | Below has 3 different styles for indirect accessing. I am trying to understand if they all have well-defined behavior, and can be safely used for cross-platform code.
#include <cstdint>
#include <iostream>
#include <any>
using namespace std;
#if 1
#define INLINE [[gnu::always_inline]] inline
#else
#define INLINE [[gn... | Technically the behavior of neither of these is specified by the standard, because you are using implementation-defined attributes which could have any effect. However practically speaking these attributes are irrelevant to the behavior here.
That aside:
test1 is correct and specified to work as expected. Casting an ob... |
73,927,889 | 73,941,622 | How to call c++ methods from rust? | I would like to call the c++ methods from rust. I heard I need to create vtables(VMTs), but how can I do that? How is that different from what I did?
C++:
struct numbers {
int addnums(int a, int b) {
return a + b;
}
};
struct v_numbers {
virtual int v_addnums(int a, int b) {
return a + b;
... |
To the people who commented:
The example I gave to you, was a simplified version of what I was trying to do. I was thinking this example is so simple, that people would recognize that it is a simplified version of something. I am sorry for assuming something like that. You know, not all C++ libraries have "classic C-s... |
73,927,930 | 73,928,144 | How can I have a dynamic array without using a vector? C++ | The program question is as follows:
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. That list is followed by two more integers representing lower and upper bounds of a range. Your program should output all integers from the l... | Because C++ does not support variable length arrays (outside of compiler-specific extensions), you want to use a dynamically allocated array based on the input sample size. Such an array can be created with new, and then deallocated with delete[].
#include <iostream>
int main() {
int sample, lower_bound, upper_bound... |
73,928,772 | 73,928,797 | What are header only version in Boost C++ Libraries? | I am working on my assignment in which I think I can use boost.serialization library. But we are asked to use only header only version of boost. So I want to know wheather boost.serialization fall under header only version or not?
| No, it requires linking with the boost_serialization or boost_wserialization library.
Failing to link with the library will for the most basic demo on the boost site produce a long list of undefined references:
undefined reference to...
`boost::archive::archive_exception::~archive_exception()'
`boost::archive::archive_... |
73,929,080 | 73,929,624 | Error with Clang 15 and C++20 `std::views::filter` | I'm wondering why this code doesn't compile with clang 15, even though the ranges library is marked as fully supported in clang 15 on the compiler support page? It does compile with g++12, even if the support is marked only as partial, and it compiles with clang trunk.
#include <ranges>
#include <vector>
int main() {
... | The code is fine.
However Clang's implementation of concepts is broken in a way that libstdc++'s views don't work. This has been a known issue for a while, but apparently has been resolved a few days ago. The code now works on Clang trunk with libstdc++. See similar question and relevant bug reports 1 and 2.
Libc++'s i... |
73,929,123 | 73,929,204 | String functions from Windows Visual Studio seem to not work when compiled through g++ on Ubuntu(Linux Mint) | I was working on a project for my class through visual studio(windows) because I like the compiler a bit more, but when I copy/pasted the code to ubuntu linux(linux mint cinnamon) and ran both a g++ compiler and a cmake build on it, the string functions did not seem to be defined correctly and I received the following ... | The problem is simple. You need to include the header <algorithm>
#include <algorithm>
Otherwise the compiler finds the C function remove
int remove(const char *filename);
declared in the header <cstdio> because (the C++ 14 Standard, 27.4 Standard iostream objects)
1 The header declares objects that associate objec... |
73,929,668 | 73,929,742 | Makefile not doing what I want - Compiling same thing twice | CXX := g++
CXX_FLAGS := -std=c++17
SRC_DIR := ./src
LIB_DIR := $(SRC_DIR)/lib
OBJ_DIR := $(SRC_DIR)/obj
BIN_DIR := $(SRC_DIR)/bin
BIN_DEBUG := $(BIN_DIR)/Test-debug
BIN_RELEASE := $(BIN_DIR)/Test
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
LIB_FILES := $(wildcard $(LIB_DIR)/*.cpp)
OBJ_F... | This is wrong:
$(OBJ_FILES): $(SRC_FILES) $(LIB_FILES)
$(CXX) $(CXX_FLAGS) -c -o $@ $<
Say you have src/foo.cpp and src/bar.cpp in SRC_FILES. Now OBJ_FILES is src/obj/foo.o and src/obj/bar.o. Now the above rule expands like this:
src/obj/foo.o src/obj/bar.o: src/foo.cpp src/bar.cpp
$(CXX) $(CXX_FLAGS... |
73,930,461 | 73,930,520 | How to do a template specialization with multiple arguments (when the type of one of them is known) | Here's the template for a class
template <typename T, unsigned int size>
class Foo {
T myarray[size];
//other code (doesn't matter for the example)
}
and I want to do a template specialization for it. For example, I have defined class Bar. So I want to make a specialization for class Bar, but I want ... | This is called partial template specialization:
template<unsigned int size>
class Foo<Bar, size> {
Bar myarray[size];
};
|
73,931,285 | 73,931,592 | Is it possible to pass a struct pointer to an int argument of a function? | I am working on the Nachos Operating System as part of my coursework. While modifying the codebase of the OS, I encountered the following comment for a member function that allows you to run a function inside a newly forked thread (in this OS, processes are called threads - don't ask me why - refer to the official docu... |
I want to understand what the authors of this codebase are trying to say.”
They are saying, if you want to pass more data than an int, put it into a structure of your own design, say some struct foo x, and pass (int) &x to Thread::Fork. Implicit in the fact they are instructing you to do this is that the Nachos opera... |
73,931,712 | 73,931,734 | what is for (; e > 0; e >>= 1)? | Can anyone explain to me what's happening in line number 4, and how to understand these types of loops in future.
I was solving this problem. I have used basic approaches like pow(2,n) and (1<<n), but it overflows. Then I got this solution, but I'm unable to understand that fourth line. I know how to use for() loops in... | The for loop has 3 components:
for (a; b; c) {
}
a runs at the start. The loop will break when b is no longer true, and after each iteration c is executed.
|
73,931,831 | 74,024,993 | How to get the default, max, min value of Video Proc Amp/Camera Control parameters from UVC camera? | I want to get the default, max, and min values of control parameters from UVC camera like the picture.
I try to get the default value with the below function. However, it only gets the current value of XU control and I cannot get the default values of XU control or any value of Video Proc Amp/Camera Control like the a... | I found the solution to my question. I use IAMVideoProcAmp and IAMVideoProcAmp to realize this function.
HRESULT hr;
IAMVideoProcAmp* procAmp = NULL;
IAMCameraControl* control = NULL;
...
hr = pVideoSource->QueryInterface(IID_PPV_ARGS(&procAmp));
if (SUCCEEDED(hr))
{
hr = procAmp->GetRange(prop, &min, &max, &step... |
73,932,381 | 73,957,603 | " /bin/sh: 1: Syntax error: "(" unexpected " error while building code for raspberry pi pico | I am on Ubuntu.
I am trying to build a simple project that I know worked! (I already made it work) I don't think I changed something to it but it has been three days and I cannot find a way to make it build again.
I use a library named pico-DMX, whenever I don't add it to my project with "include" in cmake, than the ma... | As mentioned in the comments, the cause is the name of your directory. In order to accurately explain why it happens, I reproduced your situation myself. I created a dummy project under "/tmp/test checkout (copy)" and built using CMake:
cd "/tmp/test checkout (copy)/build/pico-sdk/src/rp2_common/boot_stage2" && \
arm-n... |
73,932,857 | 73,932,892 | C++ Exception codes vs classes | I am developing a header-only C++20 library, and now I need to add exception classes.
And I have two choices:
One base class and many subclasses
class library_error : public std::exception {
// ... other work
};
class parse_error : public library_error {
// ...
};
class playing_error : public library_error... | Likely, an exception is not only thrown blank, but there are arguments to it. E.g. the file missing, the device on which the playing error occurred. You'd likely expect the exception handler to be able to process these. Therefore, I'd strongly suggest not to go around the type system and have an exception type hierarch... |
73,933,905 | 73,933,979 | C++ template defining number of parameters of function | Lets say i have a class looking like this
template<int n>
class A{
array<size_t, n> sizes;
//...
public:
template <int k>
A<k> reshape(array<size_t, k> new_sizes){
return A<k>(new_sizes):
}
};
it works but the parameter new_sizes is syntatically suboptimal, since i have to call it like that:
foo.r... |
OR (even better) a way to define the size of a variadic parameter, so i could write something like
foo.reshape(1,2,3);
You could take the sizeof... a parameter pack:
template <size_t N>
class A {
std::array<size_t, N> sizes;
public:
A() = default;
template <class... Args>
A(Args&&... ss) : sizes{sta... |
73,934,455 | 73,934,635 | friend function is not a friend of all template instances? | In the following example I try to access the private member function subscribe() from a templated class type from within its friend function. However it appears that the friend function is only befriended in one instantiation of the class and not the other, hence yielding a "private within this context"-error. Check ou... | Yes, this is correct.
my_class<int> and my_class<bool> are separate classes, and everything inside them will get defined separately for each instantiation of the template. Normally this is fine, because the stuff inside the classes is class members, so i.e. my_class<int>::subscribe and my_class<bool>::subscribe are di... |
73,934,596 | 73,934,825 | Idiomatic template parameter pack wrapper for template parameter pack deduction disambiguation | My initial goal is to disambiguate the following:
template<typename... T, typename... U>
void foo(){}
In that case, foo< <a_sequence_of_types> >() always results in T = <a_sequence_of_types> and U = <empty_parameter_pack>.
A classic solution is to pack T... and U... in std::tuple<T...> and std::tuple<U...> respectivel... |
Problems arise if any of the involved template parameters is not default constructible as it is becomes impossible to bind the dummy parameters of foo in that case.
You can pass std::type_identity<T> instead of T to tuple to pass type:
foo(std::tuple<std::type_identity<int&>,
std::type_identity<const f... |
73,935,448 | 73,948,866 | Installing and Linking to Apache Arrow inside Cmake | I'm trying to build and link-to apache-arrow v9.0.0 inside my cmake project using the following section in my CMakeLists.txt file.
ExternalProject_Add(arrow
URL "https://www.apache.org/dist/arrow/arrow-9.0.0/apache-arrow-9.0.0.tar.gz"
SOURCE_SUBDIR cpp)
message(STATUS "arrow source dir: ${arrow_SOURCE_D... | Building arrow from sources in cmake took quite some doing. It's heavily influenced by this link.
cmake/arrow.cmake
# Build the Arrow C++ libraries.
function(build_arrow)
set(one_value_args)
set(multi_value_args)
cmake_parse_arguments(ARG
"${options}"
"${one_value_args}"
... |
73,935,536 | 73,936,155 | Syntax for std::bit_cast to an array | #include <bit>
#include <array>
struct A {
int a[100];
};
struct B {
short b[200];
};
void test(const A &in) {
const auto x = std::bit_cast<short[200]>(in); // error: no matching function for call to 'bit_cast<short int [200]>(const A&)
const auto y = std::bit_cast<B>(in); // OK
const auto z = std... | Not even std::bit_cast can return an array, so wrapping in a class (perhaps std::array) is the best you can do.
|
73,935,618 | 73,936,608 | Change background color with OpenGL | The Qt OpenGL Window Example shows a colored triangle. The colors, RGB corners, are set with:
static const GLfloat colors[] = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
How do I change the black background to another color?
| You set the clear color with use of glClearColor function:
C Specification
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
Parameters
red, green, blue, alpha
Specify the red, green, blue, and alpha values used when the color buffers are cleared. The initial values are all 0.
Description
gl... |
73,935,704 | 73,935,990 | How to declare a <vector> object and use push_back inside a class? | I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definit... | The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array.
for(int j=0;j<x_max;j++) {
for (int k=0;k<y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
However, there are also some ... |
73,935,778 | 73,935,901 | C++ bitset strange value | #include <bitset>
#include <assert.h>
#include <stdio.h>
using namespace std;
int main()
{
bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
assert(bs[12]==1);
printf("bs[11]=%d\n", bs[11]);
printf("bs[12]=%d\n", bs[12]);
return 0;
}
console output:
Why can't I simply get 0 or 1 as output ?
| printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference.
You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console):
#include <bitset>
#include <assert.h>
#include <iostream>
int main()
{
std::bitset<128> bs(42);
bs[11]... |
73,935,913 | 73,936,630 | nested vector with polymorphic_allocator cannot be constructed via emplace_back | The following code:
std::pmr::vector<std::pmr::vector<int>> outer_vec(std::pmr::get_default_resource());
outer_vec.emplace_back(std::pmr::get_default_resource());
fails with quite inconceivable error message ending with
static assertion failed: construction with an allocator must be possible if uses_allocator is true... | std::pmr::polymorphic_allocator uses uses-allocator construction if supported by the constructed type. std::vector does support uses-allocator construction and the allocator type of the inner std::vector is compatible with that of the outer one.
In consequence uses-allocator construction will be used by the outer vecto... |
73,936,188 | 73,936,418 | how are integers stored in stack | main.cpp
#include <iostream>
int main(){
int x = 1, j = 2;
int *p = &j;
// std::cout << &x << std::endl;
std::cout << *(p-1) << std::endl;
}
I get different output with the line std::cout << &x << std::endl; commented out and uncommented. Are integers stored in consecutive locations in stack?
values:
c... | You didn't use x, so the compiler didn't store it anywhere.
Remember, when you write C++ you aren't writing a program. You're describing the behavior of the program you want your compiler to write for you. The compiler can write any program as long as its behavior matches the behavior you described. If you declare a... |
73,937,606 | 73,937,670 | How do I convert a String into a char in C++ | I want to convert a string that is inside a vector of strings (vector) into a char.
The vector would look something like the following: lons = ["41", "23", "N", "2", "11" ,"E"]. I would like to extract the "N" and the "E" to convert them into a char.
I have done the following:
char lon_dir;
lon_dir = (char)lons[lons.si... | You cannot directly cast a c string (char* or const char*) to a char as it is a pointer. More precisely a pointer to an array of chars!
So once you retrieve the right char* (or const char*) from your array lons it suffices to dereference said pointer, this will return the first character of that string
char* str = "abc... |
73,937,814 | 73,938,007 | How to make a class static variable which depends on the complete class type a constexpr? | I have a class MyClass which has a static variable instance. The value of instance is a compile-time constant, but it depends on the complete type MyClass. Is there any way to make instance a constexpr?
// memchunk.hpp
#ifndef MEMCHUNK_HPP
#define MEMCHUNK_HPP
#include <new>
#include <utility>
enum class DestroyOpti... | Use a function instead:
class MyClass {
static constexpr MyClass* instance();
};
MemChunk<MyClass> obj;
constexpr MyClass* MyClass::instance() {
return obj.get();
}
However, this is pointless because obj.get() cannot be used in a constexpr context (because of the reinterpret_cast, as mentioned in the comment... |
73,937,862 | 73,937,940 | How to increment the C++list's Iterator inside a for loop to iterate over specific pattern say for example each second element? | Usually in C++ one can iterate over each second element by doing so:
for (int i = 0; i < 10; i = i + 2 ){
//do Somthing
}
and for a C++ list (from library list) one can iterate over each element like so:
std::list<int> dY = {5,4,5,8,9,7,10,4};
std::list<int>::iterator iterdY;
for (iterdY = dY.begin(); iterdY ... | std::advance(iterdY, 2)
But you can no longer use the comparison iterdY != dY.end() because if the list has an odd number of elements you will skip over the end iterator, and into the territory of undefined behavior.
You must make sure that the list have an even number of elements first, if using iterators, or use some... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.