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 |
|---|---|---|---|---|
69,336,635 | 69,336,896 | MFC CPP A problem with putting picture in picture control on load | I got MFC app and I wanted to upload a picture using those 3 lines:
cbitmap_.LoadBitmap(IDB_BITMAP1);
picture_control_.SetBitmap((HBITMAP)cbitmap_.Detach());
UpdateData(FALSE);
When I did it on the main Dialog it worked. I tried to use it on a second Dialog that I open and it doesnt work on load. If I use it with a bu... | Final initialization of controls in a dialog is commonly done in response to the WM_INITDIALOG message. It is sent by the system after all controls have been created, but before the dialog is displayed. The CDialog class provides the virtual OnInitDialog member you can override in a derived implementation.
The call to ... |
69,336,769 | 69,337,085 | static CArray C++ MFC | I simply cannot seem to be able to make a static CArray and work with it.
Here's my code:
class WhiteBoard
{
public:
static CArray<WhiteBoard, WhiteBoard> test;
void tester()
{
test.Add(*this);
}
};
And upon calling the tester method, I get an unresolved external symbol.
Full error code is:
S... | Static class members need to be defined. As posted, the WhiteBoard class merely declares the identifier test. That makes the compiler happy, but the linker fails, because it cannot find the referenced symbol when it is used.
To fix this you need to add the following to a compilation unit:
CArray<WhiteBoard, WhiteBoard>... |
69,337,035 | 69,442,414 | Comparison between 2 different ways of writing Merge Sort | I have learned Merge Sort algorithm in C++ recently and have come across 2 different ways by which it is implemented in tutorials.
1st way:
void merge(int arr[], int low, int mid, int high) {
const int n1 = (mid - low + 1);
const int n2 = (high - mid);
int *a = new int[n1], *b = new int[n2];//dynamically al... | The second implementation allocates ancillary memory just once and passes the pointer recursively whereas the first calls the allocator and deallocator once per merge call. For large arrays, the second code is likely faster than the first.
Note however that both codes have problems:
they use int for the index variable... |
69,337,060 | 69,371,702 | Understand the sorting of a vector of pair (int and pointer to object) | I have a vector of pair defined as follows:
vector<pair<int, myClass *>> myVector;
The vector is sorted using the following:
sort(myVector.begin(), myVector.end());
This code is not mine and everything is working fine.
The only thing I don't get and I would like to understand is:
When I have two elements of my vector... | As I said in the comment to my question, tt's indeed the numeric value of the pointer which is use as second sorting argument. This behavior doesn't make any sense in the program itself (once again, not my program) but also it won't be reproducible in Matlab. Anyway, thanks all for your help.
|
69,337,091 | 69,349,419 | STM8 as SPI slave can't send back data | I have build a prototype board with a STM8L, and I want it to be used and configured as a SPI slave. I am testing it with a raspberry pi as master.
I use the lib provided by ST called "STM8 Standard Peripherals Library" for this, but the documentation is very poor and doesn't expain how to do this...
I can send data fr... | I finaly found where were my mistakes.
First, I forgot to configure a pullup resistor on the MISO pin:
// Set the MOSI and SCK at high level
GPIO_ExternalPullUpConfig(GPIOB, GPIO_Pin_6 | GPIO_Pin_5 | GPIO_Pin_7, ENABLE);
Next, the SPI config were wrong. The Rpi was in MSB and the STM8 in LSB, and phase was on th... |
69,337,471 | 69,337,604 | How to make a simple loop more generic | The below method will concatenate all warnings into one string. It works but obviously need to create almost the same method again for info and error.
struct MyItem
{
std::vector<std::string> errors;
std::vector<std::string> warnings;
std::vector<std::string> infos;
};
std::vector<MyItem> items;
std::string Get... | You can use a pointer to member to extract a specific field from an object:
auto concatenate(
const std::vector<MyItem>& items,
const std::vector<std::string> MyItem::* member
) {
std::string str;
for (const auto& item : items) {
for (const auto& element : item.*member) {
str... |
69,337,753 | 69,337,824 | create std::tuple using compile-time types and a run-time function | I'm trying to build (at runtime) a tuple whose types are known at compile-time.
I've gotten it pretty close I think:
#include <tuple>
// This is defined elsewhere
template<typename T>
T* create_obj();
template<typename ...Ts>
auto create_tuple()
{
std::tuple_cat(
(std::make_tuple( create_obj<std::tuple_el... | I am not sure if I correctly understand the question, because I dont understand why you want to iterate Idx, why use tuple_element or tuple_cat. I think you just want to call make_tuple to return a tuple whose elements are created via create_obj:
#include <tuple>
template<typename T>
T* create_obj() { return new T{};}... |
69,338,118 | 69,338,186 | Passing arrays to tesselation evaluation shader | I have this tesselation evaluation shader:
\\ vertex
#version 410 core
#define SIZE 6
layout (location = 0) in vec2 x;
layout (location = 1) in vec2 h;
layout (location = 2) in float f[SIZE];
out TC_DATA
{
vec2 x;
vec2 h;
float f[SIZE];
} tc_out;
void main()
{
tc_out.x = x;
tc_out.h = h;
tc_ou... | The size argument of glVertexAttribPointer must be 1, 2, 3 or 4. Passing 6 to the size argument generates a GL_INVALID_VALUE error.
If the type of the vertex shader attribute is an array, each element of the array has a separate attribute index. The attribute layout (location = 2) in float f[SIZE]; has the attribute in... |
69,338,391 | 69,338,499 | c++ function returns two different types | I'm creating a queue template class using C++.
The queue class has multiple function members. One of the functions is called front() to retrieve the first value of queue. Basically, the front() function will first check if the queue is empty or not (using another bool function is_empty()).
If it is empty, the function ... | One option is to use std::optional:
template <class T>
std::optional<T> MyQueue<T>::front() {
// You should remove the object from the queue here too:
if (!is_empty()) return my_queue[0];
return {};
}
You can then use it like so:
if(auto opt = queue_instance.front(); opt) {
auto value = std::mo... |
69,338,457 | 69,369,809 | What is the fastest way to power real numbers? | Of course i know that there is a good pow() function in cmath(math.h), but not touching the background of the pow() what is the fastest way to power numbers with my own hands?
| You are asking two different questions:
What is the fastest way to power real numbers?
What is the fastest way to power numbers with my own hands?
These have different answers.
pow is fast. Standard library implementations are generally written by very smart people, reviewed by other smart people, and then refactored... |
69,338,461 | 69,338,677 | How can I print the result from this code with four places after the decimal point? | How can I print the result with four places after the decimal point?
#include <iostream>
#include <math.h>
using namespace std;
int main() {
double A;
double R;
cin >> R;
A = 3.14159 * R * R;
cout << "A=" << A << "\n";
return 0;
}
| #include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main() {
double A;
double R;
cin >> R;
A = 3.14159*R*R;
cout << "A="<< fixed << setprecision(4) << A<< "\n";
return 0;
}
Add the library iomanip. fixed and setprecision are utilized in this case to achieve your... |
69,338,624 | 69,338,717 | Trying to pass a function as a parameter using functional library in c++ but it is not working | // I will define all the functions that are involved.
//First is the sort function that i am trying to pass.
void bubbleSort(vector<int> &vector);
//Second is the function that calls the function that is supposed to take a function as a parameter.
int testSorts(vector<int> &vector, ofstream& outfile, string data)
{
... | Don't do using namespace std; and specify the namespace and it should work:
void displaySort(std::vector<int>& vector, std::ofstream& outfile,
std::string data, std::function<void(std::vector<int>&)> func)
{
func(vector);
}
If you for some reason want to stick with using namespace std;, add :: be... |
69,338,639 | 69,338,655 | drawing program with glut/openGL not working | This program is able to create a window and locate my mouse when it is on the window, however the display function does seem to work. What am I missing here?
float pointSize = 10.0f;
bool leftBottState;
float xvalue;
float yvalue;
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void dots()
{
glBegin(GL_POI... | You're using a double buffered window (see glutInitDisplayMode).
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
Therefore you must call glutSwapBuffers to swaps the buffers after rendering the scene:
void dots()
{
glBegin(GL_POINTS);
glVertex3f(xvalue, yvalue, 0.0);
glEnd();
}
void display(void)
{
gl... |
69,338,726 | 69,338,944 | Why is a function taking a pointer preferred over a function taking an array reference? | Consider the following program:
#include <iostream>
#include <cstring>
using namespace std;
void print(const char *pa) {
cout << "Print - using pointer" << endl;
}
void print(const char (&arr)[]) {
cout << "Print - using reference" << endl;
}
int main() {
char ca[] = {'B', 'A', 'D', 'C', '\... | Binding a reference directly to an argument expression is considered as an identity conversion.
For the function with a parameter of a pointer type there is required the implicit conversion from an array type to the pointer type.
So the function with the referenced type of its parameter is more viable.
From the C++ 17 ... |
69,338,737 | 69,338,809 | Passing References to Member Functions | I've been working with a doubly-threaded BST in C++, and I thought it would be cool to separate my visitor functions from my various traversals. However I can't figure out how to properly pass references to member functions into my traversal functions. Here is a massively simplified version of my problem:
class foo {
p... | void (*visitor)(int)
In C++ this means: a pointer to a function that takes an int parameter and returns a void.
&print
The type of this expression is not "a pointer to a function that takes an int parameter and returns a void". It is "a pointer to a method of class foo that takes an int parameter and returns a void".... |
69,338,932 | 69,864,086 | C++ Unit tests failing when using SFML objects | I have a C++ project I am working on and I have to write Unit tests for it. It's a video game-like project so I am using SFML as my base. I tried using the Native Unit Test framework and the Google Test framework, but I always get stuck at the same point. Whenever I try to create an object that uses anything from the S... | I fixed this by adding the bin directory (C:\SFML-2.5.1\bin) of the SFML library in the Path environment variable
|
69,339,881 | 69,340,021 | Do C++ compilers align small functions to optimize cache-line fetches? | I may be misunderstanding how cache fetches work, but I'm curious if there are any compiler optimizations for aligning small functions that are not inlined.
If the cache-line-size is 64 bytes on a given machine, would it make sense to have function pointers to functions that are smaller than 64 bytes be aligned within ... | No, mainstream compilers like gcc and clang don't leave extra unused space to start a small function at the start of a cache line, to avoid having its end cross a boundary. Nor do they choose an order within the text section that optimizes for this without reducing overall code density for I-cache and iTLB.
AFAIK, GCC... |
69,340,012 | 69,340,022 | C++: Initialize template variable in struct | UPDATE: The issue was stemming from the fact that the Passenger class does not have a default constructor. I don't understand why that breaks the list implementation though. If someone could leave a comment explaining this to me, I'd appreciate it a lot!
OG Post:
Hello fellow stackoverflowers. I'm working on a simple u... | It appears that you call:
Node *newNode = new Node;
Which is equivalent to
Passenger *newNode = new Passenger;
Which appears to be invalid because Passenger does not have a no argument constructor. I suspect you could fix this by doing:
Node *newNode = new Node(data, nullptr);
|
69,340,062 | 69,342,881 | How to disable anti-aliasing in QMovie(or QLabel)? | I want to use QMovie in QLabel to show a pixel animation but anti-aliasing seems to be enabled by default. This makes the pixel painting not look like a pixel painting.
QMovie* movie = new QMovie(":/gif/exp.gif");
movie->setScaledSize(QSize(200,200));
label->setMovie(movie);
| QMovie just play your gif inside label, It didn't change anti-aliasing, If you didn't see that gif with the high quality you should change that gif.
The QMovie class is a convenience class for playing movies with
QImageReader.
this means that it didn't use paint.
one thing that makes you see that gif in low quality i... |
69,340,407 | 69,340,554 | How do you write a program that tests if a user's inputs are integers and returns a message if they enter characters? | The homework is that you need to write a program that takes 4 integers between 0-100 inclusive from the user, computes their average, and displays the four integers as well as the average on the output screen, like in the following format:
Your grades were: 70 80 60 90
Your average grade is 75
You also have to make sur... | The function std::isdigit expects an int with the value of a character code. However, you are not passing it a character code. If you want to pass a character code, you must read the input as a string or as individual characters, not as a number. Otherwise, you will have no character codes to pass to std::isdigit.
Howe... |
69,340,510 | 69,349,572 | cout with pointers c++ | I can not understand why cout does not work in this code:
#include<iostream>
using namespace std;
int main() {
int v = 65;
int* q = &v;
char** o = (char**)&q;
cout << o << endl; // output: 012FFCAC
cout << *o << endl; // output: A
cout << **o << endl; // output: A
printf("%c",*o); //... | Because an int is (usually) 4 bytes 65 will fit quite neatly into just the first byte and the rest of the memory allocated for the int will be 0 this byte pattern happens to match up very closely to how strings are stored in memory.
So when the memory is accessed through a char* it will print A most of the time even th... |
69,340,715 | 69,387,938 | Reading file from .csv in c++ | I am writing a program that takes input from the .csv file. The program run but the problem is it only returns the last line of the .csv file and skips all the other 9 lines.
It also does not display the average and the grade. Please help me figure out what I am doing wrong.
The professor is very specific about using w... | An answer has been given already and accepted.
To be complete, I will show a refactored and working version your code.
I uses no arrays. Just loops and functions.
#include <iostream>
#include <fstream>
#include <iomanip>
double getAvg(int testScore1, int testScore2, int testScore3, int testScore4, int testScore5){
... |
69,340,745 | 69,341,098 | Compiles error:Undefined reference, which is caused mainly by dependency with libraries? | I met a c++ compile error that almost drives me mad these days. The output info is
(/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: undefined reference to symbol '__libc_start_main@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libc.so.6: error adding symbols: DSO missing from command line
it's not... | Your libc.so conflicts with the one installed by glibc. You would need to change to use another name
|
69,341,174 | 69,341,348 | Cannot use C++ QQuickPaintedItem Singleton in QML | I have to create a C++ singleton class, but it doesn't work in qml.
#include "myimage.h"
MyImage::MyImage(QQuickPaintedItem *parent)
{
}
MyImage* MyImage::myImage = new MyImage;
MyImage *MyImage::instance()
{
return myImage;
}
void MyImage::paint(QPainter *painter)
{
QRectF target(10.0, 20.0, 80.0, 60.0);
... | A singleton is already created for QML so you get that error message since by using "{}" you are trying to create the object.
In this case it is enough to set a parent and the size:
import QtQuick 2.15
import QtQuick.Window 2.15
import s0.image 1.0
Window {
id: root
width: 640
height: 480
visible: tru... |
69,341,307 | 69,341,980 | Difference between using << operator with stringsteam and write member function | I have observed that when a uint8_t type buffer (not guaranteed to be null terminated) is read into a stringstream with the << operator using ss << buff.data, and the contained std::string is returned to Python, Python throws an error:
UnicodeDecodeError: 'utf-8' codec can't decode byte
But, if I use ss.write(buff.da... | uint8_t is an alias for unsigned char. When operator<< is given an unsigned char* pointer, it is treated as a null-terminated string, same as a char* pointer. So, if your data is not actually a null-terminated character string, writing it to the stream using operator<< is undefined behavior. The code may crash. It may ... |
69,341,853 | 69,342,028 | Can pointers on std::type_info be compared for equality in constant expressions? | One can define a constexpr pointer on std::type_info object of any class T. Does the language allows one to compare such pointers for equality in compile-time?
For example:
#include <typeinfo>
template <typename T>
inline constexpr auto * pType = &typeid(T);
int main() {
static_assert( pType<int> == pType<int> );... | This is a GCC bug: 85428
By the way, pType<int> == pType<int> is not always guaranteed.
|
69,342,158 | 69,342,570 | Is it possible to extend the life of an rvalue passed into a function? | I am trying to make a system for lazy evaluation, however it seems my system wont work with rvalues/temporary variable. for example
class Number;
class LazyAddition
{
public:
Number& lhs;
Number& rhs;
LazyAddition(Number& lhs, Number& rhs)
: lhs(lhs), rhs(rhs)
{
}
LazyAddition(Number&... | Because the rvalues are bound to the parameters of the constructor firstly, and bounding them to the class members later does not further extend their lifetime.
You can define your LazyAddition class as an aggregate to avoid binding the rvalues to parameters of constructor:
struct LazyAddition
{
const Number& lhs;
... |
69,342,182 | 69,342,585 | How can I give two compatible names to a C++ class template with deduction guides? | If I have a widely-used class template called Foo that I want to rename to Bar without having to update all of its users atomically, then up until C++17 I could simply use a type alias:
template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explicit Bar(T value);
};
// An older name for this cl... | Your problem is exactly what P1814R0: Wording for Class Template Argument Deduction for Alias Templates
wants to solve, that is to say, in C++20, you only need to add deduction guides for Bar to make the following program well-formed:
template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explic... |
69,343,060 | 69,343,139 | C++: Cannot convert string to char*? | I'm trying to print the first item (top item) of a Deque in C++ with the following piece of code:
#include <queue>
#include <deque>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
deque<string> commandHistory;
for (int i = 0; i < 2; i++) {
commandHistory.push_back("asdf");
... | Eventhough your question is marked both C and C++, I'd remove the C tag since your code is more C++ than C.
The documentation for printf is here: https://en.cppreference.com/w/cpp/io/c/fprintf
The gist of that function is that it takes at least 1 param: the so called format string, which as the signature says, is a con... |
69,343,108 | 69,343,737 | Q1 : priority_queue "come before means output last", Q2 : custom compare with sort and priority_queue | Q1
https://en.cppreference.com/w/cpp/container/priority_queue
i'm looking this webpage and in template parameters section Compare says like this.
But because the priority queue outputs largest elements first, the
elements that "come before" are actually output last.
i learned that heap realization like this.
parent n... | Q1 is mostly a terminology clash; the ordering relation a < b usually says "a is ordered before b", but in a priority_queue, a < b means "a has a lower priority than b".
So b is before a in the priority order. (That is, the priority order is the opposite of the ordering relation's order.)
Here is one suggestion regardi... |
69,343,160 | 69,376,745 | Given an array 'a' and an integer 'x', arrange the elements of the (in place) such that all the elements <x come before all the elements >='x' | Also, preserve the original relative order of elements in both the groups (i.e elements smaller than 'x' form one group and elements equal to or greater than 'x' form another group. The relative order should be maintained in both the groups.)
Example 1:-
a={2,6,3,5,1,7}
x=5
Output : 2 3 1 6 5 7
All the elements small... | When working with linked lists, the concept of swapping is not really useful for linked lists. Instead you would move nodes.
Here is a possible implementation:
#include <iostream>
class Node {
public:
int value;
Node * next;
Node(int value, Node * next) {
this->value = value;
this-... |
69,343,172 | 69,344,066 | Throwing data member's destructor | I have a class that holds an object which destructor's can throw (it is actually a tbb::task_group, but I named it MyObject for simplicity here).
The code is like this:
#include <stdexcept>
class MyObject {
public:
MyObject() {}
~MyObject() noexcept(false) {}
};
class A {
public:
A() {}
virtual ~A() {... | Based on a suggestion from @463035818_is_not_a_number, it is possible to wrap the throwing class into a custom one that does not throw.
In my case, for tbb::task_group, it could be like this:
class TaskGroup {
public:
TaskGroup() {
_task = new tbb::task_group();
}
// This destructor will not throw.... |
69,343,832 | 69,388,472 | Why g++ tries to link against the wrong libstdc++.so library? | I am trying to write a very simple test application that uses Matlab C++ interface. My machine is running CentOs7 that comes with the default gcc 4.8.5. But for my application, I need gcc 7+, so I have installed gcc 7.3.1 as well. For compiling this mini-app, I use this command:
g++ -o matlab_test matlab_test.cpp -I/... |
/opt/rh/devtoolset-7
devtoolset-7 :
/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/libstdc++.so
...... is a 210B text file :
/* GNU ld script
Use the shared library, but some functions are only in
the static library, so try that secondarily. */
OUTPUT_FORMAT(elf64-x86-64)
INPUT ( /usr/lib64/libstd... |
69,345,094 | 69,345,564 | How do I convert my point light into an oval/ellipse? | I am looking to turn my current circular light into an ellipse by having a vec2 radius which can have different x and y values. Is there any way to do this based on my current code in the fragment shader?
uniform struct Light
{
vec4 colour;
vec3 position;
vec2 radius;
float intensity;
} allLights[MAX_LIGHTS];
vec4 cal... | Divide the vector to the light source with the semi-axis of the ellipse and check whether the length of the vector is greater than 1.0:
if (length(lightDir / light.radius) >= 1.0)
return vec4(0, 0, 0, 1); //outside of radius make it black
return light.intensity * (1 - length(lightDir / light.radius)) * light.colour... |
69,345,625 | 69,345,711 | Constructor delegation with std::array<> | I have a class which receives a std::array in the constructor. For the life of me I can't write a correct and simple delegation from std::initializer_list - only the awkward lambda which I have commented out. Can someone show me a clean and sensible way without ad-hoc code?
#include <array>
class foo
{
std::array<in... | std::array has no (any) explicitly declared constructors and so, it has no constructor from initializer list, so you cant just forward initializer list to array.
As a workaround, you can use variadic template constructor
template <typename ... Args>
foo(Args && ... args) : foo(std::array<int, 5>({args ...}))
|
69,346,153 | 69,511,030 | Disable CPU package idle states in Windows from C++ code | I am successfully disabling CPU core C-states using this code (I’m working on Win10 and use Qt):
#include <QCoreApplication>
#include <QDebug>
#include "Windows.h"
extern "C" {
#include "powrprof.h"
}
#pragma comment(lib, "powrprof.lib")
int main()
{
const DWORD DISABLED = 1;
const DWORD ENABLED = 0;
GUID ... | The system is shutting down the USB device to save power.
This link provides the solution USB system power issue.
Open the Device manager as administrator.
Find the camera.
On the "Power Management" tab, deselect "Allow the computer to turn off this device to save power".
This can be done programmatically if the device... |
69,346,522 | 69,348,572 | How can I set the initial index for Shift + click selection in Qt QTableView? | My issue is that after Ctrl + click deselect of an item. It became the initial index of the following Shift + click select.
What I would like to happen is set the initial index of the Shift selection to index 0.
For example:
#include <QApplication>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplicat... | You should subclass QTableView for this purpose. Here is small example tested for Qt4. For Qt5 it should be pretty similar.
Header:
#ifndef CUSTOMTABLEWIDGET_H
#define CUSTOMTABLEWIDGET_H
#include <QTableView>
class CustomTableWidget : public QTableView
{
Q_OBJECT
public:
explicit CustomTableWidget(QWidget *p... |
69,346,632 | 69,347,341 | define constants in a struct | I'm trying to create a struct with some constants in it like this:
#include <CoreAudio/CoreAudio.h>
...
struct properties {
//Volume control
const AudioObjectPropertyAddress volume = {
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
... |
struct properties {
//Volume control
const AudioObjectPropertyAddress volume = {
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
};
is valid, but volume is not a static member, so usage requires an instance:
s... |
69,346,803 | 69,368,861 | How to configure and export function that should return char array? | I'm trying to create a function that can be called from e.g. Python through a .dll.
I'm working on byte arrays.
This is the original function I'm trying to wrap:
QByteArray getKeys(const QByteArray data, const QByteArray info);
What should the C style interface and implementation look like? Do I have to pass char* arr... | Listing [Python.Docs]: ctypes - A foreign function library for Python.
@Jarod42's suggestion wasn't to use std::pair, but to emulate it via a C (compatible) struct. Here's an example (my dummy getKeys implementation is to simply return the concatenation the 2 QByteArray arguments):
dll00.cpp:
#include <QtCore/QByteArra... |
69,346,955 | 69,347,033 | C++ uniform declaration is not working in class | I am trying to have a member array in a class with its length specified by the const static int variable for future needs.
My compiler throws an error with it, and I am not sure this is an error about a uniform initialization or array initialization, or both.
Here is the header file:
#ifndef SOUECE_H
#define SOURCE_H
... | Since array_length is static const you have to initialize it like this:
source.h
#ifndef SOUECE_H
#define SOURCE_H
class Test
{
public:
Test();
static const int array_length = 2;
//static const int array_length{2}; this will also work just note that we cannot use constructor initializer list to initialize ... |
69,346,969 | 69,347,050 | using an initializer list where the values contain unique_ptr member variables | I have a class that contains a unique_ptr. I want to place instances of this class inside a container (specifically std::map). This works using std::move and .emplace however, I would like to perform all this initialization within the container's initializer list. Is this possible?
I suspect Foo gets initialized in the... | It's fault of std::initializer_list, if you look at it's begin/end member functions, they return const T*, which means it will force std::map to try use the copy constructor of your Foo, which is deleted as std::unique_ptr can not be copied.
This issue is not unique to std::map, any container which allows you to initia... |
69,347,069 | 69,347,591 | Json::Value as private class member | I'm writing a C++ class for Reading/Writing strings from/to a json file using the jsoncpp lib.
My question is if it's possible to create a Json::Value private member for my class and use this every time I need to read/write instead of creating a new Json::Value inside every function?
If so, how can I initialize it in t... | You don't need any special initialization for the Json::Value. You can make it a private member variable and use it like any other member variable.
Here's an example where I've added support for streaming from/to istream/ostream objects and a few member functions to demonstrate access to specific fields:
#include "json... |
69,347,072 | 69,347,590 | The input is a three-digit number. Print the arithmetic mean of its digits | I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (... | The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
s... |
69,347,666 | 69,360,909 | Setting type of an outer variable using auto lambda parameters | I am using a C++ web framework that heavily uses callback lambda functions. As you may guess, parameters to lambdas are usually specified as auto due to the must to declare very long declarations.
Now I use decltype() operator to find the right type deduced by auto so that I can declare a vector of the same type. When ... | You have to manually look at the type that you are initialising.
A generic lambda creates an object with a template operator(). There's not much stopping there from being multiple instantiations of that template.
If that's the case then there isn't a type that is the type of auto parameter.
You are relatively lucky her... |
69,348,036 | 69,348,499 | How to std::forward class template parameter | I'm getting compiler error when using std::forward on a class template parameter, but not on a function template parameter. I'd like to know how to std::forward a class template parameter. This is my code:
#include <iostream>
#include <vector>
template<typename T>
class Data_List {
std::vector<T> data_list;
p... | In here:
void add_to_list(T&& data) {
std::cout << "\nbefore inside add_to_list: " << data.size() << std::endl;
data_list.push_back(std::forward<T>(data));
std::cout << "after inside add_to_list: " << data.size() << std::endl;
}
data isn't a forwarding reference, it's an rvalue reference, so you can't do s... |
69,348,217 | 69,348,339 | How can I std::bind a user-provided function to a member variable of type std::function? | I have a class with a member variable std::function customCallback, and I need to let the user customize its behavior. customCallback should take as input a const std::array<int, N>& and a int, and return a std::array<int, N> (where N is a template parameter).
I am currently using std::bind to achieve this, but I can't... | Well, for starters, the first error you are getting is an error on std::array<int> in Derived::SetCustomBehavior():
error: wrong number of template arguments (1, should be 2)
You also have an error on std::ref(std::placeholders::_1), it should be just std::placeholders::_1.
Fixing those two mistakes, the code then co... |
69,348,731 | 69,359,676 | Parallel vs Sequential naïve quick sort | I am trying to implement quicksort which runs partition sorting in parallel as given below:
// Returns patition points as pair
template<typename ExPo, std::random_access_iterator I, std::sentinel_for<I> S,
class Comp = std::ranges::less, class Proj = std::identity >
requires std::sortable<I, Comp, Proj>
std... | First, you cannot use godbolt to demonstrate speedup (or slowdown) due to parallelism. Last time I checked, the service was giving each program one hardware thread.
Second, by default gcc does not do any parallelisation. There are two parallelism backends there, and the one that is used by default is called, surprising... |
69,348,894 | 69,349,704 | Remove Pair from TJsonObject | {
"Test":{
"A":{
"ins":{
"type":"pac",
"id":{
"values":{
"test_number":"156764589",
"val":"abcde",
"val_2":"gggg",
"val_3":"jjjj"
},
"verif":{
},
"bool":"INSTR"
}
}
},
"res... | First, your path is wrong. type is not in the path down to test_number. The correct one would have been:
obj->RemovePair("Test.A.ins.id.values.test_number");
But as far as I know, that can't be parsed by RemovePair. You'll have to use FindValue:
// Cast helper:
TJSONObject* ToTJSONObject(TJSONValue* v) {
auto obj ... |
69,348,948 | 69,350,424 | Absolute Value of the DFT with OpenCV in C++ | I am trying to compute the DFT in C++ with OpenCV. I want the absolute value of the DFT. To compute it I do:
vector<float> areas, X_mag;
cv::Mat X;
...
cv::dft(areas, X, cv::DFT_COMPLEX_OUTPUT);
areas is a 50x1 vector, and I want to store the absolute value of the DFT of areas in X_mag
The problem, is that I think ... | As @Christoph Rackwitz said, we can use split and magnitude.
vector<float> areas, X_abs;
Mat X;
Mat X_mag[2];
...
cv::dft(areas, X, cv::DFT_COMPLEX_OUTPUT);
cv::split(X, X_mag);
cv::magnitude(X_mag[0], X_mag[1], X_abs);
And we will have the absolute value vector in X_abs.
|
69,350,094 | 69,350,136 | The type returned by 'operator|' does not always match the type you passed it | Some code called a templated function, but it did not call the specialisation I expected. Turned out the culprit was this: I or-ed some uint16_t constants and passed them as an argument like this: foo(uint16_bar | uint16_baz);. My expectation was it would call the foo<uint16_t>, but it did not. I can easily evade the p... | The usual arithmetic conversions are applied to operands of the bitwise operator |. That means that integer objects of types with rank less than the rank of the type int are converted either to int or unsigned int due to the integral promotions that are a part of the usual arithmetic conversions..
From the C++ 14 Stand... |
69,350,142 | 69,351,942 | Using unique_ptr with an interface requiring pointer-pointer, to an abstract class | I'm using RocksDB which requires a pointer to a pointer to open:
rocksdb::DB* db{nullptr};
const rocksdb::Status status = rocksdb::DB::Open(options, path, &db);
As expected, I'd like to use a unique_ptr. However, unfortunately if I do this:
std::unique_ptr<rocksdb::DB> db;
const rocksdb::Status status = rocksdb::DB::O... | Using a raw pointer to accept the value from Open() is the correct solution, since that is what the function is expecting.
However, the way you are creating the unique_ptr afterwards is not correct.
Use this instead:
std::unique_ptr<rocksdb::DB> _db; // Class member
...
rocksdb::DB* db;
const rocksdb::Status status = r... |
69,350,818 | 69,367,814 | How to add noexcept specifier to already defined function type? | For example I have type:
typedef DWORD WINAPI HANDLER_FUNCTION_EX (DWORD);
And I want:
static as_noexcept<HANDLER_FUNCTION_EX>::type my_func; // forward declaration
static_assert(noexcept(my_func(0)));
I got something like:
template<typename>
struct noexcept_trait;
// specialization to infer signature
template<typen... | Add
template<typename Result, typename... Args>
struct noexcept_trait<Result __stdcall(Args...)>
{
using as_noexcept = Result __stdcall(Args...) noexcept;
using as_throwing = Result __stdcall(Args...);
};
and similar elsewhere. But you should only do this if !is_same_v< void(*)(), void(__stdcall *)() >. If _... |
69,350,834 | 69,350,935 | C++ Templates - The Complete Guide: Understanding footnote comment about decltype and return type | The 2nd edition of C++ Templates - The Complete Guide features the following code at page 435
#include <string>
#include <type_traits>
template<typename T, typename = void>
struct HasBeginT : std::false_type {};
template<typename T>
struct HasBeginT<T, std::void_t<decltype(std::declval<T>().begin())>>
: std::true... | Your demo uses void begin() const; to test the following
... instead does add the requirement that the return type of the call is complete ...
But a void return type is not the same as an incomplete return type. For that you could try
struct X;
struct A {
X begin() const;
};
Here, X is indeed incomplete, and no... |
69,351,000 | 69,353,899 | C++ I don't want to ignore white spaces in folder paths (MAC) how can I do that? | I am currently working on a project which runs pretty well, and I get a file path from the user, if the path has no white spaces it works pretty well! but if it includes white spaces the system ignores and doesn't continue reading the path. For Ex; if the path says Desktop/School Projects/C++
System reads only the Desk... | Use getline(cin, directory); instead of cin >> directory; in order to store more than one words in a string, and don't forget to use cin.ignore(); before getline.
|
69,351,083 | 69,351,665 | Understanding User-Defined Conversions for Unrelated Types | I have a class, UDataChunk, which is a wrapper class for all my data types (actor info like location, stats, etc).UDataChunk holds a Value() method which is hidden by derived classes in order to return the type they hold (as the data types they hold can vary, I believe that means I shouldn't use a template on UDataChun... | In the first case, you are trying to assign a TObjectPtr<USenseComponentChunk> object to a TObjectPtr<USenseComponent> object. Your conversion operator for that purpose is implemented in USenseComponentChunk, not in TObjectPtr. So, unless TObjectPtr<T> uses CRTP to derive from T, the compiler is correct to fail the c... |
69,351,180 | 69,351,260 | "/usr/bin/ld: cannot find -llibopencv_calib3d" when compiling an opencv project in Ubuntu 20.04 | I have installed opencv in Ubuntu 20.04 following the instructions in OpenCV Installation in Linux. As per the instructions, sudo make install copies all the .so files to /usr/local/lib.
However, when compiling a program, using the command g++ --std c++17 -g opencv/Basic.cpp -o output -I/usr/local/include/opencv4 -L/us... |
-llibopencv_calib3d
make it
-lopencv_calib3d
etc. the lib part in front of it is simply wrong
|
69,351,364 | 69,351,900 | How to get validate result Qt? | For quick skip the gui code, and go straight to method validate, i dont know, next step to get validate result when login button click. full code in here https://pastecode.io/s/ut3cuq3p
class MainWindow: public QWidget
{
Q_OBJECT
public:
MainWindow(){ ... }
public slots:
void validate(QLine... | When using a validator on a QLineEdit, you want to look at the value of pUserInput->hasAcceptableInput() but you can set it up better. You only need to assign the validator to your QLineEdit when it is created (unless your validation regex is changing every time), then you can use the signals QLineEdit::editingFinishe... |
69,351,650 | 69,352,997 | C++ erasing section of vector with a size_t as start point | I want to erase a section of a std::vector e.g ith element through end. Where i is a std::size_t that is calculated beforehand.
auto i = vec.size();
for (auto pos = vec.size(); pos > 0; --pos) {
auto& elem = vec.at(pos - 1);
if (*magic_condition*) {
--i;
}
}
vec.erase(vec.begin() + i, vec.end());
I get a ... | The code shown is perfectly fine, AFAICS. The warning implies that the vector's implementation is in the wrong, not you. A vector::iterator can be incremented by an index, and your index variable is the same type that vector uses for its indexes. So there should be no conversion. But there is, because the differenc... |
69,351,795 | 69,470,453 | DLL's dependency cannot be found when DLL moved to another location | I'm on Windows 10, Visual Studio 2017, x64 build . . .
I have a DLL that I'm using in an exe project. We'll call it, myLibrary.dll. It comes with a .lib companion file as well. The myLibrary.dll has some other DLL dependencies that it is using. We'll call that one theDependency.dll.
I've linked the companion myLibr... | Adding the path of the dll to the PATH environment variable worked for me.
|
69,352,240 | 69,352,477 | What should I send after STARTLS? | I am using smtp.gmail.com and port 587. After a successful connection, I send EHLO and receive the following:
250-smtp.gmail.com at your service, [62.16.4.123]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF
I choose STARTTLS and after that, I don't know what... | After you send an (unencrypted) STARTTLS command, if the server returns any reply other than 220, handle it has a failure and move on with other SMTP commands as needed (though, at this point, the only one that really makes sense is QUIT).
If the server returns 220 to STARTTLS, you then need to perform the actual TLS h... |
69,352,249 | 69,352,327 | To remove the Duplicates from the given string (without sorting it) | The question is asking to remove duplicates from the string, I came up with a solution to remove duplicates but for that, I sorted the string.
So I wanted to know is there a way of removing duplicates from a string without sorting the string.
Test Cases :
"allcbcd" -> "alcbd"
My Code (the one in which string has to ... | Here is one way to do it without sorting (or using a recursive loop):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
string::size_type index = 0;
string::iterator end = s.end();
while (index < s.size()) {
end = remove(s.begin()+index+1, en... |
69,352,573 | 69,353,345 | cpp-httplib https server not working on Linux | I am trying to create a HTTPS Server running on linux with cpp-httplib in C++. (https://github.com/yhirose/cpp-httplib)
Everything worked when I used Windows. But on linux only the HTTP Server works.
It seems like the HTTPS Server does not open a port which I do not understand...
When typing: sudo netstat -tuplen in ... | Ok as mentioned in the comments the problem was that the certs could not be found. I have given the absolute path for now and it works fine.
Thanks!
PS: As I said: "probably a silly mistake"..
|
69,353,433 | 69,353,527 | How do I multiply vector integers | so basically I want to multiply a vector by 60 from seconds to minutes and hours 3 times using a for loop. I also want to add 3 more values inside that vector that should store a value 60 times greater than the last integer before it.
This is what I have come up so far but it only prints out 2 times so what am I doing ... | This for loop iterates exactly once.
std::vector <int> seconds = { 1 };
for (int i = 0; i <= 3; i++) {
i = seconds.at(i) * 60;
seconds.push_back(i);
}
i is set to 60, and the loop condition i <= 3 then fails.
Use a different variable to hold this value.
std::vector <int> seconds = { 1 };
for (int i = 0; i <=... |
69,353,505 | 69,353,758 | Doubly linked list not taking input after calling a delete function | Greetings stack overflow. My program is supposed to take a user inputted line of characters and append them to a list. The program is also supposed to delete the most recent character appended if a hashtag is read in the input.
My program mostly works, but I run into errors when I try to break it by adding too many has... | You should also set the pointer last to nullptr in the constructor
doubleList() { first = nullptr; last = nullptr; }
The function append is incorrect because it does not set the data member prev of the first node appended to the list. It should be written like
void doubleList::append(char entry)
{
Node* temp = new... |
69,353,507 | 69,359,725 | choose a constexpr based on a runtime value and use it inside a hot loop | I need to traverse a vector, read each element, and map to the modulo division value. Modulo division is fast for divisors of power2. So, I need to choose between a mod and mod_power2 during the runtime. Following is a rough outline. Please assume that I am using templates to visit the vector.
Bit manipulation tricks w... | "Issue" with cond ? mod_power2 : mod is that it is a function pointer, which is harder to inline.
Different lambdas have no common type. Using type-erasure such as std::function has overhead, and devirtualization is even harder to optimize.
So, only option I see is to be able to write run1 in a "nicer" way:
Factorize t... |
69,353,512 | 69,353,817 | How can I dynamically pick a member from two similar C++ structures while avoiding code duplication? | Having the following structures:
class XY
{
private:
int test;
};
class XYZ
{
private:
short extra;
int test;
};
I want to use XY::test and XYZ::test depending on a runtime variable. Like:
if (x == 1)
{
reinterpret_cast<XY*>(object)->test = 1;
}
else if (x == 2)
{
reinterpret_cast<XYZ*>(object)->te... | #define FlexibleOffset(class1, class2, member) (x == 1 ? offsetof(class1, member) : offsetof(class2, member))
#define FlexibleMember(object, member) *reinterpret_cast<decltype(XY::member)*>(reinterpret_cast<uintptr_t>(object) + FlexibleOffset(XY, XYZ, member))
FlexibleMember(object, test) = 1;
void* addressTo = &Flexi... |
69,353,615 | 69,456,756 | Perfect forwaring of auto&& in generic lambda | The next generic lambda is used to protect any operation which shares resource between threads:
auto mutexed = [mtx(std::mutex{})](auto &&fn, auto &&...args) mutable {
std::unique_lock lo(mtx);
return fn(args...);
//return std::forward<decltype(fn)>(fn)(std::forward<decltype(args)>(args)...)... | In C++20 and later
auto lambda20 = []<class F, class...Ts>(F &&fn, Ts &&...args) {
return std::forward<F>(fn)(std::forward<Ts>(args)...);
};
In C++pre20 : C++11,14,17
auto lambda14 = [](auto &&fn, auto &&...args) {
return std::forward<
std::conditional_t<
std::is_rvalue_referenc... |
69,354,120 | 69,354,161 | Trying to iterate through an array using pointers but I get float pointer error / it won't compile | I am learning how pointers work in C++, and am trying to iterate through an array using pointers and that confusing pointer arithmetic stuff.
#include <iostream>
int main()
{
float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
float *ptr1 = arr;
for (int i = 0; i < 5; *ptr1 + 1)
{
std::cout << *ptr1 <<... | In your loop, after each iteration, *ptr1 + 1 is dereferencing ptr1 to read the float it is currently pointing at, adding 1 to that value, and then discarding the result. You are not incrementing ptr1 itself by 1 to move to the next float in the array. You likely meant to use ptr1 += 1 instead of *ptr1 + 1.
More impo... |
69,354,129 | 69,354,250 | Real Applications of internal linkage in C++ | This sounds like a duplicate version of What is the point of internal linkage in C++ and probably is. There was only one post with some code that didn't look like a practical example. C++ISO draft says:
When a name has internal linkage, the entity it denotes can be
referred to by names from other scopes in the same tr... | Internal linkage is a practical way to comply with the One Definition Rule.
One might find the need to define functions or objects with plain names, like sum, or total, or collection, or any one of other common terms, more than once. In different translation units they might serve different purposes, specific purposes ... |
69,354,267 | 69,355,853 | What is the best method for compiling a project with multiple directories in vscode? | The problem is simple. Say you have 3 files in a project and I want to compile them all.
src/proj-runner/main.cpp
#include <iostream>
using namespace std;
int main () {
string line;
Greeting *hello = new Greeting();
cout << hello->hello() << endl;
return 0;
}
src/proj-class/class.cpp
#include "class.h"
Gree... | You can create a vscode build task to run the command for you. To do that, create a .vscode directory in your workspace root and in that directory create a file called tasks.json. Add the following to that file:
{
"version": "2.0.0",
"tasks": [
{
"label": "build_main_and_class",
... |
69,354,553 | 69,354,783 | Dialog window procedure as a member function of a class | Based on this post, I'm trying to create a simple Win32 application, in which the window procedure/callback function of a dialog window is a member function of a class. My code looks like this:
H file:
class MyClass
{
public:
HINSTANCE hInstance;
HWND hWnd;
int APIENTRY WinMainProc(HINSTANCE hInstance,... | Lets start with the error message. You are trying to use a non-static class method, WinProc(), as your CreateDialog() callback. That will not work. You went to the trouble of implementing a static class method, WinProcWraper(), which calls WinProc(), but you are not actually using it. You need to use WinProcWraper(... |
69,354,607 | 69,418,832 | Is there a difference between SVML vs. normal intrinsic square root functions? | Is there any sort of difference in precision or performance between normal sqrtps/pd or the SVML version:
__m128d _mm_sqrt_pd (__m128d a) [SSE2]
__m128d _mm_svml_sqrt_pd (__m128d a) [SSE?]
__m128 _mm_sqrt_ps (__m128 a) [SSE]
__m128 _mm_svml_sqrt_ps (__m128 a) [SSE?]
I know that SVML Intrinsics lik... | I've inspected the code gen in MSVC.
_mm_svml_sqrt_pd compiles into a function call; the called function consists of a single sqrtpd followed by ret
_mm_svml_sqrt_ps compiles into a function call; the called function consists of a single sqrtps followed by ret
_mm_sqrt_pd and _mm_sqrt_ps intrinsics compile to inlined ... |
69,355,139 | 69,370,764 | Make can't find .hpp file in Boost | I'm using an Ubuntu virtual machine and am encountering the following error message when running the 'make' command:
Scanning dependencies of target AIToolboxMDP
[ 1%] Building CXX object src/CMakeFiles/AIToolboxMDP.dir/Impl/Seeder.cpp.o
[ 1%] Building CXX object src/CMakeFiles/AIToolboxMDP.dir/Impl/CassandraParser.c... | I ended up solving it by deleting my Boost folder and reinstalling it using the command sudo apt-get install libboost-all-dev; I just reran cmake and took out all the options I had been using except for the lpsolve one, and then when I ran make afterward I encountered no issues.
|
69,355,295 | 69,355,344 | How to remove preceding '0' from numbers 10 and above? | How can I remove the preceding '0' from number 10 above? Only numbers 1-9 should have preceding '0'.
SAMPLE INPUT:
40
SAMPLE OUTPUT:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
21.22.23.24.25.26.27.28.29.30
31.32.33.34.35.36.37.38.39.40
MY CODE'S OUTPUT:
01.02.03.04.05.06.07.08.09.010
011.012.013.014.01... | std::cout <<"." << std::setfill('0') << std::setw(2) << a;
|
69,357,059 | 69,357,617 | C++: Backspace characters not showing in stdout? | I am implementing a shell that has command history. When the user presses the up or down arrow, the text in the current line is replaced with the previous or next command.
The algorithm I'm planning on implementing is fairly simple. If the current command has k characters, I output k '\b' characters to delete the k cha... | You need ANSI escape codes. Try:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
cout << "asdf";
cout<<"\b\b\b\b\033[J";
return 0;
}
\033 stands for ESC and [J is a parameter to the code. ESC[J clears the screen from the cursor to the end of the screen. For mo... |
69,357,332 | 69,357,851 | Why does string shuffle stop working after 10 characters in the string? | #include <iostream>
#include <string>
using namespace std;
string cardsShuffle(string orig_seq){
string choice;
int random = 0;
string shuffled_seq;
int orig_len = orig_seq.length();
while(orig_len > shuffled_seq.length()){
random = rand() % orig_seq.length();
while(ran... | I don't get a normal exit, I get "Floating point exception(core dumped)".
The erase function does not have the parameters you think it does - like substr, the second is the length, not the "one past the end" index.
(std::string has a peculiar interface, as it was created long before the standard collections were added.... |
69,358,284 | 69,358,404 | STL generic algorithms - implicit conversion of the ranges element type to the predicates parameter type | Say I want to remove all punctuation characters within a std::string using the erase-remove idiom.
However, let str be of type std::string, this call won't compile
str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );
Now I guess, strictly speaking the std::ispunct callables parameter type is i... | Consider the following code:
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
bool foo(int i) { return true; }
int main() {
string str = string("");
str.erase( std::remove_if(str.begin(), str.end(), foo), str.end() );
str.erase( std::remove_if(str.be... |
69,358,555 | 69,358,596 | How to get const_iterator when the T is 'const std::map',? | I have the following struct:
template<typename T>
struct Foo
{
typename T::iterator iter;
};
The expected type:
iter is a std::map<K, V>::iterator when T is deduced as std::map<K, V>.
iter is a std::map<K, V>::const_iterator when T is deduced as const std::map<K, V>
But my code always get a std::map<K, V>::iter... | You can provide a std::conditional type:
#include <type_traits> // std::conditional_t
template<typename T>
struct Foo {
using iter = std::conditional_t<std::is_const_v<T>
, typename T::const_iterator
, typename T::iterator>;
};
|
69,358,675 | 69,372,321 | How to use collate_fn in LibTorch | I'm trying to implement an image based regression using a CNN in libtorch. The problem is, that my images got different sizes, which will cause an Exception batching the images.
First things first, I create my dataset:
auto set = MyDataSet(pathToData).map(torch::data::transforms::Stack<>());
Then I create the dataLoad... | I've got a solution now. In summary, I'm split my CNN in Conv- and Denselayers and use the output of a torch::nn::AdaptiveMaxPool2d in the batch construction.
In order to do so, I have to modify my Dataset, Net and train/val/test-methods. In my Net I added two additional forward-functions. The first one passes data thr... |
69,358,695 | 69,836,645 | Eclipse CDT Indexer not including header from same project | After a recent upgrade (only SSD capacity change), Eclipse CDT Indexer has been giving me a tough time. My project folder structure is as shown below.
LinEmLibrary
└─ test
├─ TestNumParam.cpp
├─ TestNumParam.h
├─ TestPMS.cpp
├─ TestPMS.h
├─ TestSerial.cpp
├─ TestSerial.h
├─ TestWindow.cpp
└─ Tes... | After a month of struggle I have finally broght things back to normal.
The issue appears to be the preferences I would import after creating a new workspace. I have exported preferences once after setting up the environment for code style, editor font / color etc. I don't remember exactly but I might have created it wh... |
69,358,836 | 69,360,677 | Conan packages migration from official repo to local private repo | I would like to know if it is possible to upload a package from official "conan-center" repo and all its dependencies into a local private repository (who does not have internet access)
Example:
In "conan-center" repo there is a package A.
Package A has some dependencies: B and C.
I wanto to upload A (and automatically... | The best to do it is using the Artifactory feature Remote Repository, where Artifactory will download it for you when a package is not available in your Local Remote.
However, if you don't have internet connection, it will be more complicated, you will need to download which packages do you need and upload them manuall... |
69,360,721 | 69,405,074 | Can't compile with extern library | I've installed the jsoncpp library via vcpkg into my project directory. Since the compiler looks for header files mostly in predefined include directories how can I add the library to those directories so that the compiler can recognize it?
Error:
fatal error: 'json.h' file not found
| I found the issue: The package wasn't installed properly due to a homebrew error. I had a shallowed version of homebrew. I had to unshallow and upgrade it and then download the package again, now it works.
|
69,360,822 | 69,361,078 | How to modernize memalign in a C++ codebase? | I am modernizing/updating some old code that was originally written in C but is now used in a C++ codebase (no need to be backwards compatible). A bunch of this code is memory optimized with memalign with which I am very inexperienced with so my question is how one would update this code (or just leave it like it is) a... | If std::array is an option for you, it's easy to align (same applies to bare arrays):
alignas(32) std::array<TALBLE_SIZE, float> table;
The standard function for dynamically allocating over-aligned memory inherited from C is std::aligned_alloc. It's nearly identical to the non-standard memalign; only difference is tha... |
69,362,208 | 69,362,246 | Remove '0' from numbers less than and equal 9 | How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17... | As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.
|
69,362,554 | 69,362,614 | Why can't I deduce the function signature for a mutable lambda? | I have the following code which implements a memoize function.
note The question is not about how to write a memoize function specifically but rather about the compile error I get with this implementation and the smallest change to get it to work.
The implementation.
#include <functional>
#include <map>
#include <funct... | You are lacking a specialisation.
Adding this makes it work
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...)>
{
using type = std::function<Ret(Args...)>;
};
The operator() of the closure-type of a lambda is const qualified iff the lambda is not declared mutable
|
69,362,579 | 69,369,586 | C++: How to cross-compile from Windows to Linux? | I have a C++ module on windows which I want to compile such that I get a dynamic library for linux *.so.
Does a cross-compiler exist that can help me out?
| Several comments mentioned using Windows Subsystem for Linux. I would personally recommend this as it is far easier than trying to use a cross-compiler. It also comes with the added benefit that you can test your code in the same environment in which you compile it.
https://learn.microsoft.com/en-us/windows/wsl/about i... |
69,363,104 | 69,363,218 | Error reporting in C++ programming in VS code | I have no problem compiling files with G++, but VS code reports an error to the C++ 11 standard syntax. I want to know how to make VS code detect the syntax normally.
a space is required between consecutive right angle brackets (use '> >')
non-aggregate type 'vector<vector >' cannot be initialized with an initializer... | Add "C_Cpp.default.cppStandard": "c++11" to settings.json. (F1 -> Open Settings (JSON) or Open Workspace Settings (JSON))
|
69,363,344 | 69,370,263 | Cppyy cmake build unable to find LibClang | I've been trying to use cppyy to build some python bindings for a C++ library. At the moment I am using the cookiecutter recipe from here: https://github.com/camillescott/cookiecutter-cppyy-cmake
But the package is having trouble finding LibClang_LIBRARY and LibClang_PYTHON_EXECUTABLE. This is the same case if I instal... | The cmake fragments in the cookie cutter example seem to be older than the ones in cppyy-cling: https://github.com/wlav/cppyy-backend/tree/master/cling/python/cppyy_backend/cmake
(These are the ones installed under cppyy_backend/cmake in the Python site-packages directory.)
The newer version protects the searches with ... |
69,363,387 | 69,363,657 | string stream vs direct string | I'm attempting to send a STOMP frame to a server. I first tried to create the message directly using std::string, but the server kept complaining I am doing it wrong. But, when I created the message using stringstream, it works. Anyone can spot my mistake? The code is as shown. It complains it can't find the terminatin... | Creating an std::string from const char * will ignore the terminating NULL character. You could use the char[] constructor but I think it won't fit your use case.
Example:
// Example program
#include <iostream>
#include <string>
int main()
{
std::string message1 {"STOMP\naccept-version:1.2\nhost:transportforlondon... |
69,363,581 | 69,364,271 | Is it valid to move away an object managed by a std::shared_ptr | Context
I am trying to forward ownership of a std::unique_ptr through a lambda. But because std::functions must always be copyable, capturing a std::unique_ptr is not possible. I am trying to use a workaround described here: https://stackoverflow.com/a/29410239/6938024
Example
Here is my example which uses the describe... | We have our unique ptr to an interface I:
up[I]
where [] is ascii-art for the "box" we put the "I" in. We then put this in a box:
sp[up[I]]
the data is "double boxed".
We then pass this double box around. When we need to get at the unique ptr, we crack it with a std::move(*sp.get()). This leaves us with both of:
s... |
69,364,273 | 69,369,034 | ncurses WINDOW* disappears after console resize | So, let's say we have a
WINDOW *main_win=newwin(50, 80, 1, 0); // 50 rows, 80 columns
WINDOW *status_win=newwin(3, 100, 51, 0); // Status bar
WINDOW *interaction_bar=newwin(1, 200, 0, 0);
I have a function that prints strings onto it (mvwaddstr) and it works as planned. But after resizing the terminal to particularly ... | Regarding the disappearing window (likely reduced to 1x1, which is not "magically disappears"). ncurses will attempt to keep a window which has the same width (or height) as stdscr preserve that relationship when resizing, as mentioned in the manual page:
When resizing windows, resize_term recursively adjusts su... |
69,364,614 | 69,364,657 | Variable passed-by-reference is changed in function scope but not in main scope | I'm trying to alter a given grid of vectors into a heightmap, which I do by passing a vector of vertices by reference to a function which should calculate the height for each vertex and change it. However, when printing the height of the new vertices in the main scope, all are 0, whereas if I print the height of the ve... | The problem is not in pass-by-reference into the function, but in the for loop. It should use a reference to the vector elements:
for (glm::vec3& vertex : base)
|
69,365,044 | 69,365,426 | Recreating swapchain vs using dynamic state on resize | I have a vulkan application that uses GLFW as its window manager.
Upon the window resize event, vulkan needs to update its drawable area. I have seen 2 ways that this is possible. One is to recreate the swapchain alongside all of the other objects that are tied to it and the other is to use dynamic state for the viewpo... | If the window is resized to a smaller size, the display engine may not force you to change your swapchain image sizes. It may inform you of this through the VK_SUBOPTIMAL_KHR error code (though it may not give you even that if performance of presenting is not affected). However, if the window is resized to be larger, t... |
69,365,230 | 69,365,526 | How to set value in c++ unordered_map and return reference? | So this is silly:
Nodes[pos] = node;
return &Nodes[pos];
because I insert and then do a lookup. I tried like this:
return &Nodes.emplace(pos, node).first->second;
but it doesn't return the reference.
| You can use insert/emplace like this:
int& f1(std::unordered_map<int, int>& m) {
auto [iterator, was_inserted] = m.insert({10, 100});
return iterator->second;
}
operator[] can also create the key if it doesn't exist, so you can also do:
int& f2(std::unordered_map<int, int>& m) {
auto& node = m[10];
node = 10... |
69,365,580 | 69,365,756 | My Visual Studio can't find files and so can't do basic operations. What's wrong with it? | Using C++, if I launch an 'empty project', create a new C++ file, and try to run it, I just get this error message:
Unable to run program 'C:\Users\User\source\repos\Project2\Debug\Project2.exe' The system cannot find the file specified
I go to the file it's referencing and the file IS there -- what??
Using a 'Consol... | From the result you described, I suspect you used File -> New file to add that cpp file, right? This does NOT add that file to a project.
Instead, you should right-click the Project file in the Solution explorer, select Add new item (or Project -> Add new item menu), and choose the C++ file type.
This works!
|
69,365,601 | 69,367,870 | CMake: check for standard library file using CheckIncludeFileCXX | I am trying to figure out if the current compiler supports std::format, however the following code is populating the variable CXX_FORMAT_SUPPORT with nothing. I assume I may need to add an include path, but I'm not sure how to get that for the compiler if that is the case.
# check std::format support
include(CheckInclu... | The documentation is less than clear but check_include_file_cxx sets the output variable to 1 if the header is found and doesn't set the variable if it is not found.
|
69,365,927 | 69,366,788 | add a new button in a QWidget in Qt5 | I am trying to add a new QPushButton to a QWidget, but it doesn't seem to have an addWiget method.
I am using the following code:
QWidget *wdg = new QWidget;
QPushButton *btn=new QPushButton(this);
btn->setText("text");
wdg->addWidget(btn)
wdg->show();
hide();
the 6th line is giving an error
| You can pass QWidget as parent to QPushButton.
QWidget *wdg = new QWidget;
QPushButton *btn=new QPushButton(wdg);
|
69,366,623 | 69,367,527 | std::scoped_lock - vector of mutexes? | How can I apply a std::scoped_lock on a std::vector<std::mutex>? I've tried:
std::vector<std::mutex> mutexes;
std::scoped_lock lock{ mutexes }; // doesn't work
std::scoped_lock lock{ ...mutexes }; // doesn't work
| A global mutex shared between the output function and sources was the best solution.
|
69,367,313 | 69,367,355 | How to check international filepath symbols on correctness? | In my c++ linux application I load a file with file list.
Every single line is a full path to some file (utf32) and can have international symbols.
Is there a way check these lines for character correctness? Maybe some library?
Need to avoid emoji or symbols like that.
These files are outside, so I cannot check each of... | I would say in general "yes", but your question is very vague. If international characters are allowed, that opens up thousands of character (code points, in Unicode parliance) for use.
Filtering out some set is of course possible, but it's going to be tricky to define that set in a way that works for everyone.
I would... |
69,368,754 | 69,385,491 | how to use strip in conjunction with split-dwarf? | I am currently trying to use the --gsplit-dwarf gcc flag in order to automatically create and separate debug symbols from build libraries/executables. More info on DWARF Obj files. However, what I have observed is that split-dwarf still leaves a lot of unnecessary information in the remaining .o file. What I would like... |
If I strip the executable, the table is removed and the size is reduced, but it also strips away the debug_info that references the dwo file.
Correct.
The right way is to keep the unstripped copy of the executable and the .dwp file, while distributing the stripped copy to end-users.
I thought that was the whole poin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.