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 |
|---|---|---|---|---|
70,219,273 | 70,219,412 | Meyers' implementation of a Singleton Attempting to reference a deleted function (paho-mqttpp3 library) (mqtt::async_client class) | OS : Windows 10 x64
Build Tool : Visual Studio 2021
Language Standard : C++20
paho-mqttpp3 : 1.2.0
Package Manager : vcpkg
I am trying to build a mqtt::async_client using paho-mqttpp3 verrsion 1.2.0
I am using Meyers' implementation of a Singleton for my MQTT Client. Reference :
https://stackoverflow.com/a/17713799... | From the documentation it appears, that mqtt:async_client is not default-constructible, meaning that you would have to provide an initializer in MqttClient's constructor or a default member initializer. Not doing so results in the default constructor being deleted, despite your attempt to explicitely default it.
|
70,219,509 | 70,219,935 | Why is the nested macro not unfolded? | I am using nested macro under gcc-9.3.1.
Here is the code.
#define A(_name) _name, _name, _name
#define P(_1, _2, _name, ...) _name
#define B(...) P(__VA_ARGS__, A(something))(__VA_ARGS__)
B(k)
I expected the B(k) converted to P(k, something, something, something)(k) at first and then converted into something(k).
H... | B(k) expands to P(k, A(something))(k) which then undergoes recursive expansion. The first thing it finds there is P, which doesn't have enough arguments.
If you want this to work the way I think you do, you need to arrange for A to expand before P. You can do that by adding explicit indirect EXPAND macros:
#define EX... |
70,219,552 | 70,219,643 | create lambda signature after template argument | I need to write a function (f) that accepts a std::function (g) with a generic callback parameter. In the function f, some additional code should be executed when the callback is called. I would therefore need to create a lambda with a signature depending on the generic callback parameter. My template skills fails me h... | I'm not sure if this is what you need, but maybe you can use it as a starting point... This requires C++14
g([handler](auto&&... args ) {
// Do the extra stuff here before calling final callback
// Call final callback with same signature as g1 (or g2) callback
handler(std::forward<decltype(args)>(args)... |
70,219,669 | 70,219,698 | Use a Unicode character in a char variable (C++) | I get some input from the command line and want to support Unicode.
This is my error:
And this is my example code:
#include <iostream>
int main() {
char test = '█';
}
// Characters wanted: █, ▓, or ▒
How can I make my program support Unicode?
| A char is usually only 1 byte, meaning it won't be able to store most Unicode characters. You should look into using wchar_t which is required to be large enough to hold any supported character codepoint. The associated char literal looks as follows: L'█'.
|
70,219,699 | 70,238,711 | How does Boost::serialization store user-defined classes in archives? | I have a user-defined object (call it Foo) which consists of some primitive variables, as well as other (external library) objects which already contain implementations of the serialize function.
I would like to know how the archive files are structured, and whether that structure is general (e.g. between text archives... |
it seems to just output the first few zeros
What do you mean? You serialized two variables with indeterminate values (you never initialized them). You should not be expecting zeroes. Nor should you be expecting any particular layout (it is determined by archive type, version, library version(s) and platform architect... |
70,219,770 | 70,227,267 | Problem with "setup.h" wxwidget - "cannot open file" | Hello i build 32 and 64 bit version wxwidget (Batch Build and select all) from source code without any problems. Then add path to the system variables as named "WXWIN" with C:\wxwidget (there is wxwidget source)
In visual studio 2019 in solution i add these path's:
C/C++ -> Additional Include Directories ->
$(WXWIN)... | Your project is not configured to use Unicode, hence it tries using non-Unicode build of wxWidgets (note the missing u in mswd/wx/setup.h) which is not available. You should ensure that the "Character Set" option in the "Advanced" section of your project properties is set to "Use Unicode Character Set".
The strange thi... |
70,219,858 | 70,220,112 | How to make an object and put it into an array using a loop, so if I want to add data all I have to do is make a new string | How to make an object and put it into an array? I want to make an array of DailyStats with the parameterized constructor. I want to use a loop to add to the array of objects.
#ifndef DAILYSTATS_H
#define DAILYSTATS_H
#include <iostream>
#include <vector>
using namespace std;
class DailyStats
{
public:
Dai... | The main problem I see is that your temperatureValues[] array is unbound at compile-time. That will not work. Since you don't know the size of the array until runtime, use std::vector instead (in fact, you already have #include <vector> in your code), eg:
#ifndef DAILYSTATS_H
#define DAILYSTATS_H
#include <vector>
#... |
70,219,925 | 70,264,803 | How to speed up character output? | I want to make this for loop run faster by optimizing the I/O:
for ( int row = 0; row < Y_AxisLen; ++row )
{
for ( int col = 0; col < X_AxisLen; ++col )
{
std::cout << characterMatrix[ row ][ col ];
}
}
std::vector< std::vector<char> > characterMatrix; is a matrix and I need to print it out. Is pri... | You can write the whole row in one go and use fmt::print for better performance:
#include <fmt/core.h>
#include <vector>
int main() {
auto X_AxisLen = 10000u;
auto Y_AxisLen = 10000u;
auto characterMatrix =
std::vector<std::vector<char>>(X_AxisLen, std::vector<char>(Y_AxisLen));
for (int i = 0; i < Y_Ax... |
70,219,989 | 70,220,030 | C++ (Atom GCC compiler) "no declaration matches 'int ClassName::FuncName(Paramaters)'" using non-numerical types / ignoring set type for default | I have been getting this Compiler/Linter Error every time I try to create a function member of a class with a return type other than int, double, and similar types. As far as I can tell, the compiler is setting the default int return type for these functions. But I can't figure out why. I have no excess header or cpp f... | std::vector<int> addSample(std::string sample); returns an std::vector<int>, so at your cpp file you have to return the same type like this:
std::vector<int> BinaryCounter::addSample(std::string sample)
{
return oneCountColumns;
}
|
70,220,130 | 70,296,697 | How can I "join" quadratic or cubic splines? | I have 2 function to either calculate a point on a spline, quadratic or cubic:
struct vec2 {float x, y;};
vec2 spline_quadratic(vec2 & a, vec2 & b, vec2 & c, float t) {
return {
(1 - t) * (1 - t) * p1.x + 2 * (1 - t) * t * p2.x + t * t * p3.x,
(1 - t) * (1 - t) * p1.y + 2 * (1 - t) * t * p2.y + t *... |
I've cleaned this answer Joining B-Spline segments in OpenGL / C++
This is not an Hermite spline, an hermite spline passes through the points, a B-spline does not.
Here is what worked and the result
float B0(float u) {
//return float(pow(u - 1, 3) / 6.0);
// (1-t)*(1-t)*(1-t)/6.f
return float(pow(1-u, 3)... |
70,220,154 | 70,220,186 | Assign another name/alias for std::vector | I am trying to give std::vector a different name like MyVector, so I did following typedef
typedef std::vector<float> MyVector<float>;
However, visual studio complains on MyVector that "MyVector is not a template"
How do I assign std::vector another name?
I have may MyVector in my code which is essentially std::vector... | What you want is an alias template, like this:
template <typename T>
using MyVector = std::vector<T>;
That will allow you to use it like this:
MyVector<float> vec = stuff;
Where vec will be a std::vector<float>.
|
70,220,263 | 70,220,312 | Getting multiple inputs from one line from a file in c++ | Basically, I'm attempting to get three things from one line of code, read from a .txt file. This will be repeated, but for now I only need to know how to get one line. The line I'm reading looks like this:
Biology $11 12
So I want to get a string, and two ints, and completely ignore the $ (note, I ca... | You can use a dummy character variable which will "pick up" $ character:
char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1]; //read into string and int array
|
70,220,397 | 70,370,535 | Android Studio Error Message: Use Of Undeclared Identifier 'accept4' | the jni folder not appear in android studio and after build only java folder get build.
as you can see the jni folder appear in explorer but not inside android studio.
EDIT:
so after i added this in my build.gradle
externalNativeBuild {
ndkBuild {
path 'src/main/jni/Android.mk'
}
}
the jni folder a... | i get pass the error "use of undeclared identifier 'accept4'" by setting these :
from compileSdkVersion 29 to compileSdkVersion 30
from buildToolsVersion "29.0.3" to buildToolsVersion "30.0.3"
from minSdkVersion 21 to minSdkVersion 22
from targetSdkVersion 29 to targetSdkVersion 30
|
70,220,404 | 70,220,836 | Question on dynamic allocation in vectors | #include <iostream>
#include <vector>
#include "malloc.h"
using namespace std;
int main() {
// Write C++ code here
vector<vector<vector<int*>>> storage;
for (int i=0; i< 13; i++)
{
storage.push_back(vector<vector<int*>>());
for (int j=0; j< 13; j++)
{
storage[i].pu... | The error message is telling you that you are trying to assign an int to an int*. Specifically, on this statement:
storage[i][j][k]=k;
storage[i][j][k] returns (a reference to) an int*, but k is an int.
Since you have 3 levels of vectors containing an int[] array, you need 4 loops to initialize the individual ints, b... |
70,220,440 | 70,220,635 | Weird syntax error in a simple code in C++ | There is a weird syntax error in this code. I don't understand it or any of the errors.
#pragma once
#include <iostream>
class Tree {
public:
Node* root;
void InputTree() {
int n, father;
int nd;
int child;
char dir;
std::cin >> n;
int** tree = new int* [n];
... | In lines like root->value = tree[headIndex][0];, you are trying to use the Node class before you have told the compiler what that class is. You can declare variables as pointers to classes before their full definition (but you need a forward declaration of the class to do so) but you can't dereference such pointers unt... |
70,220,508 | 70,220,975 | Template member function specialization of a templated class without specifying the class template parameter | What is the correct syntax to specialize a templated member function of a templated class without specifying the class template parameter?
Here is what I mean:
Example #1 (works):
#include <iostream>
struct C1
{
template <class B>
void f(void) const;
};
template <>
void C1::f<int>(void) const { std::cout<<777<<std:... | You can use a technique called tag dispatch and replace the template specialisations by function overloads.
template<typename>
struct Tag {};
template <class A>
struct C3
{
void f_impl(Tag<int>) const;
void f_impl(Tag<char>) const;
template<class B>
void f() const {
f_impl(Tag<B>{});
}
};
struct D { static ... |
70,221,058 | 70,221,082 | C++ is there way to access a std::vector element by name? | I am experimenting with a simple vertex class.
class Vertex
{
public:
std::vector<float> coords;
//other functionality here - largely irrelevant
};
And lets say we create a Vertex object as below:
Vertex v0(1.f, 5.f, 7.f);
I am wondering if there is anyway to assign a name to each element of a vector?
Let's ... |
I am wondering if there is anyway to assign a name to each element of a vector?
No, there is not. At least, not the way you want.
I suppose you could use macros, eg:
#define coords_x coords[0]
#define coords_y coords[1]
#define coords_x coords[2]
Now you can use v0.coords_x, v0.coords_y, and v0.coords_z as needed.
... |
70,221,439 | 70,221,794 | c++ ifstream to stringstream using getline() | I am making a bowling program for school that stored scores in a text file with the format:
paul 10 9 1 8 1, ...etc
jerry 8 1 8 1 10 ...etc
...etc
I want to read the file into a stringstream using getline() so I can use each endl as a marker for a new player's score (because the amount of numbers on a line can be vari... | You can't use std::getline() to read from a std::ifstream directly into a std::stringstream. You can only read into a std::string, which you can then assign to the std::stringstream, eg:
vector<int> gameScore;
vector<string> playerName;
string name, line;
int score;
while (getline(in, line)){
istringstream iss(li... |
70,221,889 | 70,221,952 | Decrypt rotating XOR with 10-byte key across packet bytes in C++ | Trying to figure out how to write something in C++ that will decrypt a rotating XOR to packet bytes that will be in varying sizes with a known 10 byte key (key can be ascii or hex, whatever is easier).
For example:
XOR 10-byte key in hex: 41 30 42 44 46 4c 58 53 52 54
XOR 10-byte key in ascii: A0BDFLXSRT
Here is "This ... | Use the % (modulus) operator!
using byte_t = unsigned char;
std::vector< byte_t > xor_key;
std::vector< byte_t > cipher_text;
std::string plain_text;
plain_text.reserve( cipher_text.size( ) );
for( std::size_t i = 0;
i < cipher_text.size( );
++i )
{
auto const cipher_byte = cipher_text[ i ];
// i %... |
70,222,595 | 70,222,686 | std::complex<float> with error C2106: '=': left operand must be l-value | I performed fast Fourier transform (fft) on my signal, turning it into signalComplex; signal is a series of real float numbers and signalComplex represents a series of complex numbers:
std::vector<std::complex<float>> signalComplex(numSamplesPerScan); // int numSamplesPerScan
fft.fwd(signalComplex, signal); /... | I want to thank all people here that were trying to help me.
Like Brian pointed out, the code in the questions is modified to
std::vector<std::complex<float>> signalComplex(numSamplesPerScan);
fft.fwd(signalComplex, signal);
for (int n = 1; n < numSamplesPerScan / 2; n++)
{
signalComplex[n] = { signalComplex[n... |
70,222,629 | 70,238,555 | Can boost spin_condition be used for process synchronization? | I see below code in interprocess_condition, I know that interprocess_condition is used for process synchronization, but I am not sure whether spin_condition can be.
private:
#if defined(BOOST_INTERPROCESS_CONDITION_USE_POSIX)
ipcdetail::posix_condition m_condition;
#elif defined(BOOST_INTERPROCESS_CONDIT... | It can. Memory is just that, memory.
If you share it between processes, it effectively makes threads from different processes behave like threads from the same process in relation to that memory location.
However, unless lock contention is very rare, a spin-lock without back-off is recipe for very inefficient power con... |
70,222,956 | 70,223,245 | Is it possible to use a dynamic number of range adaptors? | I am fairly new to ranges, and I wanted to know if there was a way to apply a dynamic number of range adaptors. I have fiddled around with some code for a while, and I have also done some searching, but to no avail.
#include <iostream>
#include <ranges>
int main() {
auto output = std::ranges::views::iota(2, 100);
... | For a fixed number like this, it would be possible to use metaprogramming to recursively build the range (although you might hit a template instantiation depth limit). You can do a truly dynamic number by type-erasing the ranges, such that the chain of filters is connected by virtual function calls. The result is slo... |
70,223,022 | 70,223,078 | C++ for loop ends after input | #include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
string hometown;
int age;
int games;
int* hours = new int [games];
};
int main(){
int players;
Student* s = new Student [players];
cout << "How many esports players are there at TTU who major in c... | You are not handling arrays correctly. You are allocating them using uninitialized variables for their sizes:
in int games; int* hours = new int [games];, games is uninitialized.
in int players; Student* s = new Student [players];, players is uninitialized.
And, even if you were allocating the arrays correctly, you ... |
70,223,348 | 70,223,379 | 'this' keyword used in class and objects is a constant pointer? | This question came in my mind due to the following error in my c++ program
#include <iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int x = 0) { this->x = x; }
void change(Test *t) { this = t; }
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj(15);
Test *ptr... | According to 9.3.2 The this pointer [class.this]
1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value
is the address of the object for which the function is called. [...]
So as the error says, the left hand side should be an lvalue but you're giving it a prvalue be... |
70,223,662 | 70,223,741 | Is there a way to delete a pointer that has not been assigned with new operator in the destructor? If so, should I delete it in the destructor? | For example,
class Test{
private:
int* foo;
public:
Test(int* foo){this->foo = foo;}
}
In this case, is there any way I can delete foo in the destructor? Will I have to delete foo in the destructor or at least set it to nullptr?
| Sure, you can. It is legal syntax. And depending on the rest of your program, it might do what you want, or it might be a double delete (delete the same pointer twice) which corrupts the heap and will lead to an eventual crash. (Debugging compilers might catch this.)
One of the reasons the C++ standard template library... |
70,224,159 | 70,224,694 | how to display text file in c++? | I want to display the text file in my c++ program but nothing appears and the program just ended. I am using struct here. I previously used this kind of method, but now I am not sure why it isn't working. I hope someone could help me. Thanks a lot.
struct Records{
int ID;
string desc;
string supplier;
d... | Here are a couple of things you should consider.
Declare the variables as you need them. Don’t declare them at the top of your function. It makes the code more readable.
Use the file’s full path to avoid confusions. For instance "c:/temp/sample inventory.txt".
if ( ! file ) is shorter.
To read data in a loop, use the ... |
70,224,226 | 70,224,317 | What is the meaning of {{strs[0}} and how does it work? | I came accross this code on leetcode, but I am not getting how {{strs[0]}} works (Line no. 6)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// Base case
if(strs.size() == 1)
return {{strs[0]}};
vector<vector<string>> ans;
u... | strs is a vector of strings, where strs[0] is the 1st string.
The function returns a vector of vectors of strings.
In the syntax {{strs[0]}}, the outer {} represents the outer vector. Inside of the {} is a comma-separated list of the vector's elements. Since the element type of the outer vector is another vector, each... |
70,224,395 | 70,226,552 | How to check if it's a silent installation from the custom action DLL? | When my installer is started with msiexec /q /i command line, is there a way to tell that it's a silent installation from my custom action C++ DLL?
PS. I'm using WiX to build my MSI.
| The UILevel property of Windows Installer will tell you whether the setup has been launched silently. Four different UI levels are possible:
INSTALLUILEVEL_NONE - 2 - switch: /qn - Completely silent installation.
INSTALLUILEVEL_BASIC - 3 - switch: /qb - Simple progress and error handling.
INSTALLUILEVEL_REDUCED - 4 - ... |
70,224,513 | 70,265,178 | How to prefill edit boxes when my custom dialog is shown from the custom action script in my MSI? | I'm using WiX to create a custom dialog/page in my installer, based on WixUI_Mondo. The custom dialog has edit controls, similar to this:
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Fragment>
<UI>
<Dialog Id="ConfigDlg" Width="370" Height="270" ... | For each property that you need read from the registry (for upgrades/repairs) just add a <RegistrySearch> element that populates those properties.
|
70,224,603 | 70,224,665 | Double declaration and initialization of vector in a class, C++? | Good night dear all
I have a question, look i working with classes and in many cases i am using vectors of vector (2D vectors), my code runs quite well. However, i am a bit confused, look in my header file i declared a vector of vectors in my protected variables, then in my cpp file in the constructors section i declar... | In your constructor:
Matrix::Matrix(int rows, int cols)
: m_nRows(rows),
m_nCols(cols)
{
std::vector <std::vector <double>> MATRIX(m_nRows, std::vector<double>(m_nCols, 0));
}
you define a brand new variable with the name MATRIX, which is totally distinct from the member variable Matrix::MATRIX.
To initial... |
70,224,680 | 70,224,804 | argument of type "WCHAR *" is incompatible with parameter of type "LPCSTR" in c++ | I know that there are lots of questions like this as it is a common error, I also know it is happening because I am using unicode. However, after reading through SO/microsoft docs and fixing the code, it still does not seem to work and I am stumped.
The code is as follows:
#include <Windows.h>
#include <Tlhelp32.h>
#in... | PROCESSENTRY32 uses wchars when you define UNICODE. The doc's are probably misleading.
Tlhelp32.h defines this:
#ifdef UNICODE
#define Process32First Process32FirstW
#define Process32Next Process32NextW
#define PROCESSENTRY32 PROCESSENTRY32W
#define PPROCESSENTRY32 PPROCESSENTRY32W
#define LPPROCESSENTRY32 LPPROCESSENT... |
70,225,008 | 70,225,062 | Generate a number based on a given number of digits | I'm trying to write a program that generates a hex number based on a given number of digits. For instance, say that the user inputs 3, I want to generate a hex number of 0x000 and store it in some variable. Another example, say the user inputs 4 the hex number to be generated will be 0x0000.
Any ideas?
Thanks in advanc... | 0x0, 0x00, 0x000 and so on, when stored in a variable, all have the same effect.
What you want to do is to store the desired number of digits in a separate variable and apply that configuration when selecting a representation of the value (be it 0 or otherwise) in output.
For doing that in C++, I recommend the formatti... |
70,225,120 | 70,225,189 | How to access correct class member? | I've been running across this snippet of code and after execution I found out that everything compiles and executes fine (the int code member of the derived class is set to 65). However I was wondering how would one be able to access the char code member of the derived class?
#include <iostream>
using namespace std;
c... | By specifying the correct scope for the base member variable using a qualified name lookup, as follows:
d.base::code = 'x'
std::cout << d.base::code << '\n';
See this section on qualified name lookups for more details.
|
70,225,218 | 70,225,375 | C++ Primer Exercise 4.25 converting binary number | I have a question regarding the exercise 4.25 in C++ Primer:
Exercise 4.25: What is the value of ~'q' << 6 on a machine with 32-bit
ints and 8 bit chars, that uses Latin-1 character set in which 'q' has the
bit pattern 01110001?
I have the solution in binary, but I don't understand how this converts to int:
int main()
... | In order to answer the question, we need to analyze what types are the partial expressions and what is the precedence of the operators in play.
For this we could refer to character constant and operator precedence.
'q' represents an int as described in the first link:
single-byte integer character constant, e.g. 'a' o... |
70,225,816 | 70,231,551 | Finding and changing repeated letters in a word | I'm trying to create logic that goes through the word and tries to find if there are letters, that are used more than once. If a letter repeats, then change it to "1", if it's not then change it to "2". Example: Radar - 11211, Amazon - 121222, karate - 212122.
Specific problem is that if I use for(), each letter comp... | You have undefined behavior in your program when wrote word[i+1]; inside the for loop. This is because you're going out of bounds for the last value of i by using i+1.
One possible way to solve this would be to use std::map as shown below. In the program given std::tolower is used because you want capital and small let... |
70,225,854 | 70,225,879 | How to use a static method as a callback in c++ | I have a comparison/ordering function that relates to a class. I can use it if I define it as a separate closure object. I would like to make it into a static method of the class it operates on so it is tidier. I guessed how to do this but I get an error that I can't interpret.
Generally I would like to know how to tre... | Couple of issues:
compare is private, make it public.
One must use & to get the address of functions.
#include <set>
class MyClass {
public:
static auto compare(int a, int b) {
return a < b;
}
};
int main() {
std::set<int, decltype(&MyClass::compare)> s(&MyClass::compare);
return 0;
}
|
70,226,047 | 70,226,452 | Make a version file of macros which run at compile time | I want to ask if I can make a file of macros that basically defined at compile time and use these macros in my c++ code which compiles specific code if the condition is true. SO what is basically the extension for that file is it a .txt file or a .h file. and how to put this file in CmakeList.txt to make it executable ... | A C++ macro is a shortcut for writing code, what happens when you compile your project is that this code:
#define SOMETHING 32
int i = SOMETHING
Is changed to before it is compiled:
int i = 32
So a macro just substitutes text wherever you place it. There is also another use of macros that maybe is what you are lookin... |
70,226,077 | 70,230,811 | Interrupt ISR not triggering when using while loop | I am using an interrupt to turn a flag to True when data is ready from an external ADC. This interrupt is being triggered, however when I add:
while(!dataReady);
to wait for the interrupt to change the flag True, the interrupt ISR function no longer triggers.
Here is my full code:
static volatile bool dataReady = f... | MCP3464::MCP3464()
{
ch = 0;
attachInterrupt(digitalPinToInterrupt(dataReadyPin), dataReadyInterrupt, RISING);
}
You are setting up the interrupt through the class constructor, for standard C++ Class, this is perfectly fine. However, for Arduino, although you didn't mention how and where you instantiate the Class... |
70,226,290 | 70,226,697 | Line spacing removal, empty line ignoring | I've got an issue with unnecessary spacing removal and empty line ignorance. So the code below -> reads a line from a file, gets all 5 values from the line (value1, ..., value5). Then the value5 is checked if it's a float, then it gets compared with a user input price and if the line's float value is less or equal to t... | If you don't want empty lines to be printed then you can use the below shown program:
#include <iostream>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream inputFile("input.txt");
std::string word1,word2,word3,word4,word5,line;
float price;//price take from user
std::cin >> price;
... |
70,226,584 | 70,226,912 | Why should I prefer a separate function over a static method for functional programming in c++? | In my other question, How to use a static method as a callback in c++, people solved my practical problem, then suggested I take a different approach in general to follow best practice. I would like a better understanding of why.
This example uses a comparator, but I would really like to understand if there is a genera... | Firstly, note that if you just want a > comparator, there are std::greater<> and std::greater<MyClass> (the former is usually superior).
Reviewing the options you listed:
(1)
struct MyComparator
{
bool operator()(MyClass a, MyClass b) const
{
return a > b;
}
};
std::set<MyClass, MyComparator)> s;
... |
70,226,784 | 70,226,975 | How to extract the size of a type from a binary without running or using special tools | I want to extract the size of certain types from an object file / library
without running the binary
without special tools
for any toolchain (GNU, MSVC, IAR)
I'd like to follow the approach presented here, but in a more generic form.
Ideally it would work like this:
// Some file.cpp
class MyClass {
// lots of me... | I think it should be possible to simply get the size of the type with a regular sizeof and then convert the number to a string as explained in this post via variadic templates.
Then you can export a string variable from your object file and grep for it on the outside.
It should work something like this:
SizeInfo.h:
nam... |
70,226,926 | 70,227,796 | Serializing and Deserializing in a client-server architecture | I'm using cereal to serialize and deserialize data in c++, and I came upon a problem. I'm sending data using a socket to the client side, so i send a stringstream with the serialized files in a JSON format.
The problem is that I can't deserialize it with simple data types, nor with complex ones, on the client side as i... | You need to null terminate the received socket data. Can you try null terminating it like buf[len] = '\0'; after this size_t len = socket.read_some(asio::buffer(buf), error); statement.
|
70,227,123 | 70,227,542 | Error Can not convert char** to const char** | I have following code:-
static char* ListOfStr[] = { "str1", "str2", "str3" };
void Foo(const char** listOfStr)
{
// do something
}
When I call Foo like;
Foo(ListOfStr);
I get Error Can not convert char** to const char** (C2664 - vc++)
I know how to solve the problem using casting or other way around like defining co... | The issue is covered in the C++ FAQ, thanks to Steve Summit: https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion
I have looked at it for 10 minutes and still don't fully understand it, but the problem is apparently that you could create non-const aliases and thus modify an originally const object if t... |
70,227,162 | 70,227,239 | Is there any equivalent to index.js in C++? | In JavaScript, I can do import "/my-folder" and it will import /my-folder/index.js".
Is there some equivalent filename in C++? (so that #include "my-folder" will include my-folder/filename.fileext)?
| No, there is not equivalent to index.js in standard C++. It would however be perfectly legal for a specific compiler to implement something like that, though I'm not aware of any compiler that does. Quoting from 19.2 [cpp.include] (N4659):
(1) A #include directive shall identify a header or source file that can be pro... |
70,227,294 | 70,228,090 | c++98 use iterator constructor only if InputIt is an iterator of type T | For a school project I have to implement std::vector but only using C++98 standard.
The problem is that the size constructor and iterator constructor are conflicting with each other when I call it with a signed integer, so I came up with this ( whith my own implementations of enable_if, is_same, and iterator_traits):
/... | As an example, the implementation of this constructor in libstdc++ is located in the header bits/stl_vector.h:
template<typename _InputIterator>
vector(_InputIterator __first, _InputIterator __last,
const allocator_type& __a = allocator_type())
: _Base(__a)
{
// Check whether it's an inte... |
70,227,334 | 70,227,681 | What is best to insert several values at the end of a std::vector? | To add elements to a std::vector<int> v is it better to do:
// Read and manipulate a, b, c triplet as ints.
// Potentially also: v.reserve(v.size() + 3); or trust vector growth policy?
v.push_back(a);
v.push_back(b);
v.push_back(c);
or
v.insert(v.end(), {a, b, c});
from a performance point of view (assuming we are al... | First of all, doing v.reserve(v.size() + 3); in a loop is generally a very bad idea since it will certainly cause a new reallocations for each iteration. For example, both Clang and GCC with the libstdc++ and libc++ actually do a linear number of reallocations (see here, here or even there). Here is a quote from cppref... |
70,227,583 | 70,238,205 | bcc32c Error integer literal is too large to be represented in any integer type | I have a large __int64 literal:
const __int64 PwTab[] = {
50036500600837093008i64,
3006206760097890820056i64
};
It is accepted nicely by bcc32 (Borland classic compiler) but not by bcc32c (clang).
The error for the clang compiler is:
integer lite... | As mentioned in the comments the problem was in bcc32 not reporting too large literal during the compile time but silently overflowing which of course created completely different array than expected during runtime.
e.g.
int64_t testVar = 0x112233445566778899aai64;
Which is of course larger than what 64-bit integer ca... |
70,227,643 | 70,227,694 | How to overload call operator() function with same type and parameters, but different return type? | I want to define a new call operator() function with the parameters and type defined for the first operator() function. The reason for doing this is that the operations I want to perform with the new operator() function needs the same parameters as the first one, but maybe named differently but the type I need should r... | Adapters:
struct Foo {
// these are your current operator() functions
int op1(int);
float op2(int);
};
struct FooAdapter1 {
Foo& foo;
auto operator()(int i) { return foo.op1(i); }
};
struct FooAdapter2 {
Foo& foo;
auto operator()(int i) { return foo.op2(i); }
};
So, instead of passing a Foo object like... |
70,227,792 | 70,227,892 | subtle usage of reinterpret cast in Pool allocator implementation | I am currently implementing my own pool allocator to store n chunks of the same size in one big block of memory. I am linking all the chunks together using a *next pointer stored in the struct chunk like this
struct Chunk{
Chunk* next;
};
so I would expect to make a linked list like this given that i have a varia... | When you add to pointers, pointer arithmetic is used. With pointer arithmetic, the memory address result depends on the size of the pointer being added to.
Let's break down this expression:
reinterpret_cast<Chunk *>(reinterpret_cast<char *>(chunk) + chunkSize);
The first part of this expression to be evaluated is
rein... |
70,228,001 | 70,228,714 | QCandlestickSeries::hovered signal is not being emitted | The QObject::connect returns true and when I manually emit the signal, the breakpoint is hit in the slot, but when I hover over a QCandlestickSet, the signal is not emitted.
I removed all other custom drawings from the chart to be sure nothing was overlaying the candlesticks, but the signal still does not fire.
'chartV... | So I found the issue. I had overridden the mouseMoveEvent to draw my crosshair and I forgot to call the parent class' mouseMoveEvent.
Old definition:
void ChartView::mouseMoveEvent(QMouseEvent *event)
{
this->drawCrosshair(event->pos());
}
New definition:
void ChartView::mouseMoveEvent(QMouseEvent *event)
{
th... |
70,228,029 | 70,228,233 | C++ - Overloading of operators needed for an iterator | I'm trying to create an iterator on a library that allows reading a specific file format.
From the docs, to read the file content you need do something like this:
CKMCFile database;
if (!database.OpenForListing(path)) {
std::cerr << "ERROR: unable to open " << path << std::endl;
}
CKMCFileInfo info;
database.Info(i... | You'll have to think about 2 major things before:
Ownership. Currently, you have to make sure your FileWrapper survives at least as long as any Iterator returned from it by calling its begin() (since your Iterators store pointers to data owned by the FileWrapper object). If you cannot guarantee that, maybe think about... |
70,228,102 | 70,265,851 | Different compilation + linking errors for static and constexpr between clang and gcc | I have the following code:
// template_header.hpp
#ifndef TEMPLATE_HEADER_HPP
#define TEMPLATE_HEADER_HPP
namespace template_header
{
template <int dim1>
/*static*/ constexpr int dim2 = 0;
template <>
/*static*/ constexpr int dim2<2> = 3;
template <>
/*static*/ constexpr int dim2<3> = 5;
}
#e... | So, without inline variables, I was able to get something achieving your goals working. The basic idea is to have a "backend" struct to hold static members and then fully specialize that struct to your options. This method has the added benefit of causing a compiler error if you attempt to access a member of the backen... |
70,228,120 | 70,229,257 | Error with initializer_list<initializer_list<T>> | I want to initialize my own class similar to this:
vector< Point3f >={{1f,2f,3f},{2f,3f,1f},{2f,2f,2f}};
but there is an error shown:
can't convert “initializer list” to “std::vector<LB::Point3f,std::allocator<LB::Point3f>>...
I want to know what the right way is to initialize my own class with lists in braces.
This... | Basically it's failing because your current implementation of `Point<T,unsigned> doesn't have a working copy constructor.
The copy constructor needs to take a const Point<T, length>& since the initializer list is const, and it will need a const version of operator[], given your current implementation of copy, because t... |
70,228,130 | 70,232,327 | cannot find -lbgi | codeblocks | I'm trying to write some program with the legendary graphics.h
I got a toy code. And downloaded all necessary files:
winbgim.h
graphics.h
libbgi.a
And then fixed all header bugs. And tried to compile with proper linking.
And the build log looks something like this:
g++.exe -c C:\tem\1.cpp -o C:\tem\1.o
g++.exe -o C... |
gcc (QP MinGW32) 4.4.5, 32 bit
I had tried different compiler, but nothing worked:
gcc (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
gcc (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
there were 4 more
But the thing that resolved this is:
gcc (QP MinGW32) 4.4.5, and this build was for 32-... |
70,228,218 | 70,229,029 | create a to_vector function that can conditionally const cast to elements of input range based on output type | I would like to create a to_vector function that works with input vieweable_ranges. I can easily get this to work if input view and output vector have exactly the same type, but cannot get it to work if the output requires a const cast on the elements of the input range. In my case, the input ranges have non-const po... | This is because your function creates a return value of type std::vector<Obj*>, which is indeed a different type to std::vector<const Obj*>; and so unless std::vector provided an overloaded constructor which accepted a non-const version of itself then this conversion is impossible. The return value is not deduced by th... |
70,228,223 | 70,228,417 | std move bug? heap error with std vector assignment of a vector reference if nesting the assignment copy within a loop that iterates more than once | I got a heap runtime error. I suspect that it is a compiler bug when it use move too excessively.
A simplified version of the code is
vector<vector<int>>result{{1,2,3}};
int size = result.size();
for(auto jdx = size-1; jdx >= 0; --jdx){
vector<int> &row = result[jdx];
// vector<int> newrow(... | Here, the comment I made initially about your code:
you keep a reference on an element of the vector, then you extend this vector, which can lead to reallocation. This reference becomes invalid
Another comment gives the link that explains this behaviour.
Below is a minimal example to illustrate explicitly the same si... |
70,228,299 | 70,228,405 | C++ if constexpr vs template specialization | Consider these 2 examples
Example 1
template<Type type>
static BaseSomething* createSomething();
template<>
BaseSomething* createSomething<Type::Something1>()
{
return Something1Creator.create();
}
template<>
BaseSomething* createSomething<Type::Something2>()
{
return Something2Creator.create();
}
.... // ... |
What do you think which pattern shall I take for my executable to be at minimal size?
In both cases, if you only instantiate createSomething<Type::Something1> you will get one function definition that is effectively one line of code.
I really do care about size of my executable in the end
Then get rid of the static... |
70,228,321 | 70,228,377 | Can std::function have a function pointer as the type? | Suppose that I have the C-style callback type like below. For C++, I could create a std::function type like callback2, and this kind of declaration is all examples I could find. But instead of typing the signature again, can I reuse callback like callback3 below?
If callback3 is possible,
how can I call the callback? ... |
Can std::function have a function pointer as the type?
No. The class template std::function is defined only for a function type template argument. The template is undefined for all other argument types, including function pointers.
I also recommend against aliasing pointer types in general (there are exceptions to th... |
70,229,195 | 70,229,384 | Generic KDTree in C++ | I would like to have a generic KDTree implementation in C++ that can hold any kind of positionable object. Such objects have a 2D position.
Unfortunately. Positionable classes could have different ways of getting the position.
Getters getX() and getY()
std::pair<double, double>
sf::Vector2f
...
What would be the prop... | Check the design rationale of boost geometry for a solution to this problem. The methodology boils down to these steps:
Declare a class template that extracts position information from a type, e.g.
template <class Geometry>
struct Position;
To make your kd Tree usable with a new type, say MyAwesome2dPoint, specializ... |
70,229,226 | 70,229,283 | How to resolve "error: ‘The’ does not name a type" when reading from txt file? | Currently trying to read from a text file using C++ I created and for it to loop to display the words. I tried used fstream and istream but for some reason I still receive this error saying
HarlemRenaissance.txt:1:1: error: ‘The’ does not name a type
1 | The Harlem Renaissance was an intellectual
Do anyone know w... | Remove the #include "HarlemRenaissance.txt" from your code. Practically include means a copy-paste. The content of the included file will be pasted in the sorce file. In this case, the content of your file is pasted into your source code. Perhaps it has some words that syntacticly incorrect. This is why you get this er... |
70,229,319 | 70,229,432 | Must I use lambda to pass a member function as std::function? | The following code works, but I feel that the line worker([this](int a, long b, int* c){receiver(a, b, c);}); is sort of redundant because it is repeating the signature of receiver. Instead of passing a lambda function that in turn calls the member function, can I somehow pass the member function directly?
using callba... | std::bind is the classical approach, that avoids the need to explicitly spell out the forwarding signature:
using namespace std::placeholders;
// ...
worker(std::bind(&Caller::receiver, this, _1, _2, _3));
C++20 also has std::bind_front; it reduces this verbiage, somewhat.
You cannot pass a pointer to a member f... |
70,229,506 | 70,230,018 | Rabin-Karp algorithm in c++ | I am trying to understand the implementation of the Rabin-Karp algorithm. d is the number of characters in the input alphabet, but if I replace 0 or any other value instead of 20, it won't affect anything. Why is this happening like this ?
// Rabin-Karp algorithm in C++
#include <string.h>
#include <iostream>
using... | I believe the short answer is that the lower d is the more hash collisions you will have, but you go about verifying the match anyway so it does not affect anything.
A bit more verbose:
First let me modify your code to be have more expressive variables:
// Rabin-Karp algorithm in C++
#include <string.h>
#include <iostr... |
70,229,531 | 70,229,710 | C++ Add string to const char* array | Hey so this is probably a dumb beginner question.
I want to write the filename of all .txt files from a folder inside a const char* array[].
So I tried to do it like this:
const char* locations[] = {"1"};
bool x = true;
int i = 0;
LPCSTR file = "C:/Folder/*.txt";
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind ... | Problem:
You can't append items to a C array -T n[]- because the length of the array is determined at compile time.
An array is a pointer(which is a scalar type), which isn't an object and doesn't have methods.
Solution:
The easiest solution is to use an std::vector which is a dynamic array:
#include <vector>
// ...
... |
70,229,619 | 70,230,027 | I need help to writing a program that prints out shape that takes number of rows from user | The shape should look like this: shape
For example, this figure has 10 lines. And the shape should continue with this pattern.
Here is my code so far:
#include <iostream>
using namespace std;
int main()
{
int rows, a, b, c, d;
cout << "Enter the number of the rows: ";
cin >> rows;
for (a = 1; a <= rows;... | Here is a solution:
#include <iostream>
#include <iomanip>
int main( )
{
std::cout << "Enter the number of the rows: ";
std::size_t rowCount { };
std::cin >> rowCount;
constexpr std::size_t initialAsteriskCount { 6 };
std::size_t asteriskCount { initialAsteriskCount };
bool isIncreasing { };
... |
70,229,622 | 70,229,915 | Process file by line in C++ where one line is string and second is array of floats | I have this file format:
Jane Doe
10 3.1 8 7.4 5 10 6 8 0.1 2
And I want to read the file line by line, storing the first line in a string and the second line is an array of floats.
string name;
double scores[10];
ifstream scoreFile;
scoreFile.open(SCORES_FILENAME);
if (scoreFile) {
while (getline (... | You can use a std::istringstream to parse the array, eg:
string name, line;
double scores[10];
...
getline(scoreFile, name);
getline(scoreFile, line);
std::istringstream iss(line);
for(int i = 0; (i < 10) && (iss >> scores[i]); ++i);
|
70,229,973 | 70,230,890 | Is there a C/C++ APIfor pkg-config? | I have a strange use case. I have a C++ program that compiles a library object and dynamically loads it at runtime. The library it compiles depends on a third party dependency, which so far I have been solving by manually hard coding the path and changing it when I switch computers.
Is there a way to call pkg-config fr... |
Is there a C/C++ APIfor pkg-config?
Yes, there is a C api. https://github.com/pkgconf/pkgconf/blob/master/libpkgconf/libpkgconf.h , which should get installed with libpkgconf.so shared library.
|
70,230,015 | 70,230,070 | Using std::bind with overloaded methods in namespace in C++ | #include <iostream>
#include <map>
#include <functional>
namespace xAOD{
namespace EgammaParameters{
enum ShowerShapeType{
var1 = 0,
var2 = 1,
var3 = 3
};
};
class Photon{
public:
// I don't want to u... | Using lambda is easier:
lookup_callback["test"] = [=] {
return photon->test(xAOD::EgammaParameters::ShowerShapeType::var1);
};
If you really want to use bind:
lookup_callback["test"] = std::bind(
static_cast<double (xAOD::Photon::*)
(xAOD::EgammaParameters::ShowerShapeType) const>(
... |
70,230,034 | 70,230,284 | C++ writing byte to file | I am trying to write one byte to a file in C++. When I save it, is is 8 byte large, instead of 1 byte. How can I save exactly one byte?
ofstream binFile("compressed.bin", ios::out | ios::binary);
bitset<8> a("10010010");
binFile << a;
Output of ls -la:
.rw-r--r-- name staff 8 B Sat Dec 4 23:26:18 2021 compressed... | operator << is designed for formatted output.
When writing strict binary, you should focus on member functions put (for one byte) or write (for a variable number of bytes).
This will write your bitset as a single byte.
binFile.put( a.to_ulong() );
|
70,230,055 | 70,230,122 | OpenGL slows for 5k points | I am writing a SLAM library and want to visualize its work with OpenGL. I need to draw some 100k points and a few hundred rectangles and I would expect that OpenGL can handle it easily. However, after the number of points reaches 5k my program slows down.
I am new to OpenGL, so I guess I am not doing things in a proper... |
We assign a GL_ARRAY_BUFFER to each point.
That's your problem. This means you are allocating an entire buffer object for all of 12 bytes of memory. Putting each point in its own buffer also means that you must render each point with a separate draw call.
None of that is a recipe for performance.
Create a single larg... |
70,231,064 | 70,231,091 | Replacing decayed array with a pointer to array resulting in segmentation fault | I was trying to loop through an array using pointers:
#include <iostream>
#include <iterator>
int main()
{
char name[]{ "Abhi" };
for (char* ptr_c{ name }; ptr_c != (ptr_c + std::size(name)); ++ptr_c) {
std::cout << *ptr_c;
}
std::cout << "\n";
}
This results in: Error: Segmentation fault ... |
ptr_c != ptr_c + std::size(name)
This condition is never false. If you add a non-zero number to a pointer, the resulting pointer will never equal the original pointer. Hence, the infinite loop overflows the array.
Shouldn't name decay to ptr_c anyway?
No. name always decays to a pointer to the first element. ptr_c... |
70,231,173 | 70,231,199 | error: void value not ignored as it ought to be in Arduino | This is a function to convert 1 digit number to 3 digit. For example convert '2' to '002'.
void loop() {
int x = convertdigit(time);
}
void convertdigit(int num){
char buffer[50];
int n;
n=sprintf (buffer, "%03d",num);
return buffer;
}
Error: void value not ignored as it ought to be
/sketch/sketch.ino: In fu... | When you write this you are telling the compiler that convertdigit does not return anything (void):
void convertdigit(int num)
When you write this, you are telling the compiler to use the return value of convertdigit and store it in x:
int x = convertdigit(num);
Those two things are in conflict: if convertdigit doesn... |
70,231,191 | 70,231,262 | Creating a 2D array with user input | I am trying to make a 2D array where user inputs the number of elements that array can take, also the elements inside the array. I think I manage to create the array, but when I try to put some elements inside it, for example 2x2 array and putting 2 as all of its elements i get this as the output. Here is the code:
#in... | It's a typo. Instead of using the "j" variable in the inner loop while taking the input, you have used the "i" variable.
|
70,231,290 | 70,240,187 | Why doesn't curl-config --cflags print libcurl's header files directory? | I'm trying to include libcurl in my c++ project, and so am trying to find where the header files are located, but running "curl-config --cflags" just prints an empty line, instead of any useful information. I do have libcurl installed, not only because curl-config is included in libcurl and doesn't throw an error when ... | I believe S.M. found the answer, which in hindsight I should have tried. Apparently, my system already had the necessary header files in its default include paths, meaning there would be no path to include, hence the blank line. I probably should have tested this by seeing if my code completion software detected it, I ... |
70,231,702 | 70,231,963 | how do I make a conditional statement to ignore std::string types when using template parameters? | I'm encountering issues when I try to use this operator++() function in a class on a string object instead of a char or numeric data type. I tried the following implementation to check if the data being iterated over is a std::string, but the function is still returning an error when this part of the code is executed:
... | Like your code this isn't complete and won't compile. But when working with code that should make choices dependent on type use compile time constructs! Use things, like "overloading", "templates", "if constexpr", "SFINAE". For example :
#include <type_traits>
#include <string>
struct foo_t
{
template<typename typ... |
70,231,757 | 70,231,792 | What should I do so that "nan" doesn't show up in console? | My teacher gave this homework. Basically I have two numbers, a and b. I have to show to console answer of this formula for every 'a' number added h=(b-a)/10 but in console I see just nan. How can I solve this error?
My code is:
#include <iostream>
#include <math.h>
using namespace std;
double s(double x){
long f = ... | You get a signed integer overflow in f=k*f; so I suggest that you make f a double:
double s(double x){
double f = 1; // double
long double anw=1;
for(int k=1;k<=100;k++){
f = k * f; // or else you get a signed integer overflow here
// f *= k; // a simpler... |
70,231,789 | 70,232,271 | Where is Node.js own dependencies (V8, libuv) located locally? | I looked at Node.js's documentation:
"Node.js includes a number of other statically linked libraries including OpenSSL. These other libraries are located in the deps/ directory in the Node.js source tree."
I installed Node.js and check out the directory Program files/nodejs, but I cannot find the deps/directory? Wher... | Node is a program where its C/C++, static libraries it uses (such as libuv) and various other resources it uses are compiled into node.exe (on Windows). So, the things you're asking about are inside of node.exe.
They are not separately available in your file system when you just install the runnable version of nodejs.... |
70,232,681 | 70,232,729 | What modifications are possible via a variable of type `const int*&`? | Can we change the value of *y in void function(const int*& x ) when y (i.e int*y= new int) is passed as an argument to function()?
If anyone could put it in words it would be great. Please refer to the following code for a better comprehension of my question:
void DoWork(const int* &n)
{
*n = *n * 2; // will this c... | No, you are not allowed to change *n since it's a const int. You need to make it non-const for it to work:
void DoWork(int*& n)
{
*n = *n * 2;
}
Also note that *a is uninitialized so reading it would make the program have undefined behavior. You need to initialize it:
int main()
{
int* a = new int{1}; // *a ... |
70,232,859 | 70,237,784 | Is it safe to take address of an out of bounds vector index? | In C++ Primer 5th edition it is mentioned that you can take the address of the non-existent element one past the last element of an array (so long as you don't de-reference it).
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int *e = &arr[10]; // 10 is 1 past the end.
For std::vector, does indexing into the vector with the [] ope... | It's undefined behaviour. The definition of vec[10] is
*(vec.begin() + 10)
which is dereferencing an past-the-end iterator. Furthermore
Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.
|
70,232,964 | 70,233,340 | How to pass functions with different signatures as parameter to other function | I'm struggling with the following problem and if this has been asked, I apologize.
I have multiple parts in my code doing a similar job - they mainly differ in a function call:
int doSomething(string* s, int i) {
...
}
int doSomethingOther(string* s, string t) {
...
}
int main() {
int num;
string s;
// do ... | You can do it like this :
#include <iostream>
#include <functional>
#include <string>
// std::function&& so it can accept temporaries
// std::function<int(void)> ensures you can only use
// functions returning an int.
int generic_function(int p, std::function<int(void)>&& fn)
{
auto value = fn();
auto result ... |
70,233,198 | 70,233,243 | Difference between operator<< and write function? | I wonder what is the difference between std::basic_ostream<CharT,Traits>::operator<< and std::basic_ostream<CharT,Traits>::write. What about performance?
#include <iostream>
#include <string>
int main()
{
std::string tempMsg;
tempMsg.reserve( 100 );
tempMsg += "This is a string";
std::cout.write( temp... | The function allows to specify the number of characters to be outputted for a character array.
For example of you have declaration
const char *s = "Hello World!";
and want to output only the word "Hello" from the string literal then you can write
std::cout.write( s, 5 );
If you will write
std::cout << s;
then the wh... |
70,234,093 | 70,234,665 | How to read into an array from a text file c++ | I am sorry if this question seems a bit dumb but i can't get it working even though i have tried many times. So my question is, i have a text file which has a numbers inside it like the following:
10 20 30
30 40 50
60 70 80
The numbers, the row size and the column size are inputs from the user. So far i have written t... | The 2d vector solution is quite good. But if you don't want to use vectors you can use 2d dynamic arrays as well.
Here is also a solution where you can use 2d dynamic arrays if you specifically want to input the rows and cols and read from the file. It would be a bit advanced concept for you as it is covered in C++ OOP... |
70,234,212 | 70,234,502 | How to recover from segmentation fault on C++? | I have some production-critical code that has to keep running.
think of the code as
while (true){
init();
do_important_things(); //segfault here
clean();
}
I can't trust the code to be bug-free, and I need to be able to log problems to investigate later.
This time, I know for a fact somewhere in the code the... | I suggest that you create a very small program that you make really safe that monitors the buggy program. If the buggy program exits in a way you don't like, restart the program.
Posix example:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <iostream>
int main(int argc, ch... |
70,234,783 | 70,234,866 | How pointer reference works in C++? | I have 3 pointers:
Node* head;
Node* temp=head;
Node* p=new Node(2);
Now I assign:
temp->next=p
Will the next of head will also be changed?
head->next=?
| Yes, if head would actually point at some allocated memory, temp would point to the same memory.
Example:
#include <iostream>
struct Node {
Node(int X) : x(X) {}
int x;
Node* next;
};
int main() {
Node* head = new Node(1);
Node* temp = head; // temp points to the same memory a... |
70,235,311 | 70,235,421 | Converting string from C++ to Swift | I am trying to use C++ functions in Swift. To do that, I use an Objective-C wrapper. I am not familiar with Objective-C and C++ so much.
My wrapper function takes Swift String as a parameter from textField. And inside of C++ I encrypt the passed string and return it.
Here is my C++ function:
string StringModifier::encr... | You need to check for the null character (\0) in C++.
Change your for-loop to this:
for(i=0; (i<100 && str[i] != '\n' && str[i] != '\0'); i++) {
str[i] = str[i] + 2;
}
Even better, loop depending on how big the string is:
string StringModifier::encryptString(string str) {
for (int i = 0; i < str.size() && str[... |
70,235,514 | 70,235,560 | Template type deduction in container initialisation | I understand that a template type parameter can be defaulted, however, this doesn't work when I attempt to construct a std::vector without supplying the template argument:
#include<vector>
template <typename Int = int>
struct integer{
Int i;
};
int main(){
integer num;
std::vector<integer> vec;
ret... | If you have a function with a default parameter:
int foo(int bar=0);
To call this function you still have to write:
int n=foo();
attempting to write int n=foo; will not work, of course. For the same reason if your template's parameters are defaulted you still have to use
integer<>
to instantiate the template ins... |
70,236,472 | 70,236,883 | Lack of type information in structured bindings | I just learned about structured bindings in C++, but one thing I don't like about
auto [x, y] = some_func();
is that auto is hiding the types of x and y. I have to look up some_func's declaration to know the types of x and y. Alternatively, I could write
T1 x;
T2 y;
std::tie(x, y) = some_func();
but this only works, ... | There is no mechanism to state the types of the "variables" in a structured binding declaration. If you want the type names to be visible, you have to forgo the convenience of structured binding declarations.
This is important because of how structured binding works. x and y aren't really variables per-se. They're stan... |
70,236,765 | 70,237,127 | Cpp create string creation without initialization | I want to read the contents of a file into a string.
string contents(size, '\0'); -> size was determined above using the file.seekg and file.tellg.
file.read((char*) contents.data(), size);
Now, I know that the contents of the string will be overwritten in file.read, so there's no need to initialize the the string to ... | You can do this:
std::string contents(std::istreambuf_iterator<char>{file},
std::istreambuf_iterator<char>{});
But it may not be faster. Either way the initialization is likely to be very fast in comparison to reading from the drive.
|
70,236,805 | 70,236,904 | What is the best (or standard) way of switching between functions? | The C++ code below is a simplified version of what I want to do, just to display the general structure.
In each case of the "primary_function()" the structure is identical:
function() + 2
The only thing that changes is the function that is used (function 1, 2, 3, or 4).
Is there a more efficient way to do this so that ... | You can use an array of function pointers as follows:
int primary_function(int x, int selection) {
using fn_ptr_t = int (*)(int);
static fn_ptr_t functions[] = {
function1,
function2,
function3,
function4
};
return functions[selection - 1](x) + 2;
}
You can also use st... |
70,236,940 | 70,237,397 | How do I build a program after cloning a repository from github? | I want to take this program: https://github.com/baskiton/Img2STL, open it in visual studio and make an executable. I realize I could get it straight from the release, but I want to learn how to edit it and build myself. When I clone it into visual studio, the folders all have blue padlocks next to them and the build fu... | This repo has a CMakeLists.txt file in its root, hence this project can be generated and built via CMake.
Generally you download and install CMake and then you have 2 options:
Use GUI.
Use your console.
For Windows you can use powershell:
git clone https://github.com/baskiton/Img2STL
cd Img2STL
mdkir build
cd build
c... |
70,237,210 | 70,237,384 | concept std::equality_comparable_with not working for user-defined equality operator | I'm trying to test at compile time whether two types are equality-comparable, and I've defined operator== for them so they should be. yet, the following code does not compile:
#include <string_view>
struct A { int n; };
bool operator==(const A& a, const std::string_view s) { return a.n == s.size(); }
static_assert(st... | Equality means more than just operator== is valid and returns true. And the standard library concepts require this.
equality_comparable defines symmetric comparison (equality comparing between the same type). In terms of syntax, this means that t1==t2 has to be a boolean. But there are also semantic requirements that t... |
70,237,930 | 70,238,571 | Directshow audio capture filter generates only 1 sample per second | I'm making an small real-time audio-video application using Directshow. I use SampleGrabber to grab samples from Audio Capture filter. The SampleGrabber's callback is called every second and each sample's size is 88200 bytes. I printed the WAVEFORMATEX:
WAVE_FORMAT_PCM: true
nChannels: 2
nSamplesPerSec: 44100
nAvgBytes... | Directshow "sample" is a term for buffer with data:
When a pin delivers media data to another pin, it does not pass a direct pointer to the memory buffer. Instead, it delivers a pointer to a COM object that manages the memory. This object, called a media sample, exposes the IMediaSample interface.
Then
... size sho... |
70,238,037 | 70,238,284 | C++: Addressing each byte | Trying to extract each byte in a short I've created.
While I can print the second (or first) byte, I can't get both.
With my current understanding, this should work. Hoping someone can make it clear to me what the error is here. I'm running this on windows x86, so ILP32 data format.
#include <iostream>
using namespace... | Here is the fix:
#include <iostream>
#include <iomanip>
int main()
{
short i = 0x1123;
short* p = &i;
char* c = reinterpret_cast<char*>( p );
char* c1 = c + 1;
std::cout << "Short: " << std::showbase << std::hex << i << '\n'
<< "p: " << p << '\n'
<< "c: " << +( *c... |
70,238,051 | 70,238,148 | Traversing a binary tree using a vector return type | I am trying to traverse a templated AVLtree with a key value pair and return a vector of all the values.
When using a cout statement, I can tell that the function is correctly traversing the tree and it will return all values in the tree. However, when I try to add this to a vector and use it in another part of my prog... | I'd try something like this. You'll avoid creating a ton of vector<s>s in the stack.
vector<s> treeTraversal(){
vector<s> result;
treeTraversal(root, result);
return result;
}
void treeTraversal(AVLNode<t, s> *node, vector<s>& visited ){
if(node != nullptr){
treeTraversal(node -> left, visit... |
70,238,430 | 70,238,654 | Choose C++ template at runtime | Is there any way to achieve the functionality of below code without creating the mapping between strings and classes manually?
template<class base, typename T>
base* f(const std::string &type, T &c) {
if(type == "ClassA") return new ClassA(c);
else if(type == "ClassB") return new ClassB(c);
// many more el... | A possible macro:
#include <memory>
#include <string>
class BaseClass {};
class ClassA : public BaseClass {
public:
std::string label = "ClassA";
explicit ClassA(int /*unused*/) {}
};
class ClassB : public BaseClass {
public:
std::string label = "ClassB";
explicit ClassB(int /*unused*/) {}
};
templ... |
70,238,437 | 70,239,135 | Mysql json binary encoding | Does MySQL use bson for its json-encoding? Or does it have a custom binary encoding? For example:
Optimized storage format. JSON documents stored in JSON columns are converted to an internal format that permits quick read access to document elements. When the server later must read a JSON value stored in this binary f... | The internal encoding for JSON in MySQL is not literally BSON.
https://elephantdolphin.blogspot.com/2019/01/mysql-shell-8014-now-with-bson.html says:
The import utility can process documents that use JSON extensions to represent BSON data types, convert them to an identical or compatible MySQL representation, and impo... |
70,238,518 | 70,247,130 | Empty line at the end of the output | So I have a "db.csv" data file. Code reads each value from the file separated by a comma (value1, ...). Unnecessary spacings from the lines are deleted, then the finished line is printed out as desired (one space between values). The problem is that I have to pass the tests on a site called repl.it. And I fail every te... | The fix for this is adding
line.erase(remove(line.begin(), line.end(), '\r'), line.end());
to the code. But just to be sure (it probably is an overkill) I added this as I did with the spacing removal - this line for every value (value1, ..., value5). This fixed the issue right away. From what I understood from google,... |
70,239,191 | 70,239,261 | "&" and ">>" number operator in C++? | I am trying to make a raycaster game in Javascript, and to do so, I am following this tutorial, which is written in C++.
My problem stems from trying to convert the following two lines to javascript:
int tx = (int)(texWidth * (floorX - cellX)) & (texWidth - 1);
color = (color >> 1) & 8355711; // make a bit darker
I do... | The code directly translates to JS with the removal of the (int) typecast and the replacement of int with let/var/const.
let tx = (texWidth * (floorX - cellX)) & (texWidth - 1);
color = (color >> 1) & 8355711; // make a bit darker
& is the bitwise and, >> is the bitshift right, explained well here.
|
70,239,523 | 70,239,550 | Function that takes templated length parameter | I have a custom array class
template <typename T, unsigned L>
class Array
{
T m_buff[L];
};
My goal is to declare a function that would take a copy of the Array class and use its values to return a sum of all elements.
The problem is that the code compiles only for a function defined as int sum(Array<int, 3> a) an... |
not for a function defined as int sum(Array a).
That's because Array<int> is not a valid type. Your Array template requires two parameters, not one.
What you are looking for, simply, is just another template function:
template<unsigned size> int sum(const Array<int, size> &a)
{
// Function code here:
}
As far how... |
70,239,556 | 70,241,268 | For mouse click ray casting a line, why aren't my starting rays updating to my camera position after I move my camera? | When camera is moved around, why are my starting rays are still stuck at origin 0, 0, 0 even though the camera position has been updated?
It works fine if I start the program and my camera position is at default 0, 0, 0. But once I move my camera for instance pan to the right and click some more, the lines are still co... | Its hard to tell where in the code the problem lies. But, I use this function for ray casting that is adapted from code from scratch-a-pixel and learnopengl:
vec3 rayCast(double xpos, double ypos, mat4 projection, mat4 view) {
// converts a position from the 2d xpos, ypos to a normalized 3d direction
float x = ... |
70,239,646 | 70,239,989 | Why can I pass a reference to an uninitialized element in c++? | Why does the following code compile?
class Demo
{
public:
Demo() : a(this->a){}
int& a;
};
int main()
{
Demo d;
}
In this case, a is a reference to an integer. However, when I initialize Demo, I pass a reference to a reference of an integer which has not yet been initialized. Why does this compile?
Th... |
Why does this compile?
Because it is syntactically valid.
C++ is not a safe programming language. There are several features that make it easy to do the right thing, but preventing someone from doing the wrong thing is not a priority. If you are determined to do something foolish, nothing will stop you. As long as yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.