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
|
|---|---|---|---|---|
74,507,174
| 74,507,654
|
Loop through a sequence of characters and swap them in assembly
|
My assignment for school is to loop through a sequence of characters in a string and swap them such that the end result is the original string in reverse.
I have written 3 assembly functions and one cpp function but on the function below I am getting a few errors when I try to run the program and I'm not sure how to fix it. I will post both the cpp code and assembly code below with the errors pointed out, if anyone could point out what my mistake is I would appreciate it a lot!
My c++ code is below
#include<iostream>
#include <string>
using namespace std;
extern"C"
char reverse(char*, int);
int main()
{
char str[64] = {NULL};
int lenght;
cout << " Please Enter the text you want to reverse:";
cin >> str;
lenght = strlen(str);
reverse(str, lenght);
cout << " the reversed of the input is: " << str << endl;
}
Below is my assembly code
.model flat
.code
_reverse PROC ;named _test because C automatically prepends an underscode, it is needed to interoperate
push ebp
mov ebp,esp ;stack pointer to ebp
mov ebx,[ebp+8] ; address of first array element
mov ecx,[ebp+12] ; the number of elemets in array
mov eax,ebx
mov ebp,0 ;move 0 to base pointer
mov edx,0 ; set data register to 0
mov edi,0
Setup:
mov esi , ecx
shr ecx,1
add ecx,edx
dec esi
reverse:
cmp ebp , ecx
je allDone
mov edx, eax
add eax , edi
add edx , esi
LoopMe:
mov bl, [edx]
mov bh, [eax]
mov [edx],bh
mov [eax],bl
inc edi
dec esi
cmp edi, esi
je allDone
inc ebp
jmp reverse
allDone:
pop ebp ; pop ebp out of stack
ret ; retunr the value of eax
_reverse ENDP
END
On the line close to the beginning where it reads push ebp I'm getting an error that says
invalid instruction operands
and towards the end where it reads pop ebp I'm getting an error where it says the same thing.
Not sure if this is big but I'm also getting a syntax error on the very first line of code that reads .model flat.
|
Based on reproducing the symptoms, I diagnose the problem as: this is 32-bit x86 assembly (clearly), but it was treated as x64 assembly, and that didn't work.
the .model directive is not valid for x64, so there is a syntax error there.
pushing and popping 32-bit registers is not encodeable in x64, so there are invalid operand errors there.
If this is in a project in Visual Studio, set the "platform" for either the whole solution or this individual project to x86/win32 (it has different names in different places, but set it to 32-bit).
|
74,507,255
| 74,509,046
|
What is MATLAB's algorithm to calculate histogram with hist function?
|
I'm working on translation of some old MATLAB code to C++. I have noticed, that my custom function to calculate histogram that supposed to be equivalent to MATLAB [counts,centers]= hist(___) gives different results. I could not find a bug in my implementation, so I used MATLAB Coder to generate C++ function from MATLAB code and compare it to my C++ code. Here is a simple MATLAB function I used to generate C++ code:
function [counts, centers] = my_hist(values, bins)
[counts, centers] = hist(values, bins);
disp(centers);
disp(counts);
end
And a script to call it, so MATLAB can define inputs:
values = rand(1,1000);
bins = linspace(0.05, 0.95, 10);
[counts, centers] = my_hist(values, bins);
Based on the above, the Coder generates the function:
//
// File: my_hist.cpp
//
// MATLAB Coder version : 5.3
// C/C++ source code generated on : 17-Nov-2022 15:46:17
//
// Include Files
#include "my_hist.h"
#include "rt_nonfinite.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <math.h>
// Function Definitions
//
// MY_HIST Summary of this function goes here
// Detailed explanation goes here
//
// Arguments : const double values[1000]
// const double bins[10]
// double counts[10]
// double centers[10]
// Return Type : void
//
void my_hist(const double values[1000], const double bins[10],
double counts[10], double centers[10])
{
double edges[11];
double nn[11];
double absx;
int k;
int low_i;
std::copy(&bins[0], &bins[10], ¢ers[0]);
for (k = 0; k < 9; k++) {
absx = bins[k];
edges[k + 1] = absx + (bins[k + 1] - absx) / 2.0;
}
edges[0] = rtMinusInf;
edges[10] = rtInf;
for (k = 0; k < 9; k++) {
double absx_tmp;
absx_tmp = edges[k + 1];
absx = std::abs(absx_tmp);
if ((!std::isinf(absx)) && (!std::isnan(absx))) {
if (absx <= 2.2250738585072014E-308) {
absx = 4.94065645841247E-324;
} else {
frexp(absx, &low_i);
absx = std::ldexp(1.0, low_i - 53);
}
} else {
absx = rtNaN;
}
edges[k + 1] = absx_tmp + absx;
}
std::memset(&nn[0], 0, 11U * sizeof(double));
low_i = 1;
int exitg1;
do {
exitg1 = 0;
if (low_i + 1 < 12) {
if (!(edges[low_i] >= edges[low_i - 1])) {
for (low_i = 0; low_i < 11; low_i++) {
nn[low_i] = rtNaN;
}
exitg1 = 1;
} else {
low_i++;
}
} else {
for (k = 0; k < 1000; k++) {
low_i = 0;
absx = values[k];
if (!std::isnan(absx)) {
if ((absx >= edges[0]) && (absx < edges[10])) {
int high_i;
int low_ip1;
low_i = 1;
low_ip1 = 2;
high_i = 11;
while (high_i > low_ip1) {
int mid_i;
mid_i = (low_i + high_i) >> 1;
if (values[k] >= edges[mid_i - 1]) {
low_i = mid_i;
low_ip1 = mid_i + 1;
} else {
high_i = mid_i;
}
}
}
if (values[k] == edges[10]) {
low_i = 11;
}
}
if (low_i > 0) {
nn[low_i - 1]++;
}
}
exitg1 = 1;
}
} while (exitg1 == 0);
std::copy(&nn[0], &nn[10], &counts[0]);
counts[9] += nn[10];
}
//
// File trailer for my_hist.cpp
//
// [EOF]
//
I don't understande what happens in this chunk of code and why it is done:
for (k = 0; k < 9; k++) {
double absx_tmp;
absx_tmp = edges[k + 1];
absx = std::abs(absx_tmp);
if ((!std::isinf(absx)) && (!std::isnan(absx))) {
if (absx <= 2.2250738585072014E-308) {
absx = 4.94065645841247E-324;
} else {
frexp(absx, &low_i);
absx = std::ldexp(1.0, low_i - 53);
}
} else {
absx = rtNaN;
}
edges[k + 1] = absx_tmp + absx;
}
The function shift the edges of bins, but how and why? I will be grateful for help and explanation!
|
That bit of code adds eps to each bin edge except the first and last.
It is hard to know why hist does this, they must be working around some edge case they discovered (presumably related to floating-point rounding errors), and figured this was the best or the easiest solution.
|
74,507,509
| 74,507,694
|
Resolve ambiguity in assignment constructor c++
|
Description
I have code that is ambiguous when a certain constructor is present. But, when I comment said constructor out, then the compiler complains that a necessary constructor is missing.
Minimum Working Example
struct X;
struct E{
E(const double& r){ /* important protocol stuff */ }
E(const X&);
};
struct X{
X(){ /* important init stuff */ }
~X(){ /* important delete stuff */ }
//X(const double& r){ *this=E(r); } // POSITION 1
X(const X& x){ /* important init stuff */ *this=x; }
X(const E& e){ /* important init stuff */ *this=e; }
const X& operator=(const X& x){ return *this=E(x); }
const X& operator=(const E& e){ /* important stuff */ return *this; }
};
E::E(const X& x){ /* important protocol stuff */ }
E operator+(const E& x, const E& y){ /* important protocol stuff */ return E(1); }
E operator*(const E& x, const E& y){ /* important protocol stuff */ return E(2); }
int main(){
X x,y;
x = 3.0;
X u = 4.0; // POSITION 2
y = x + u * 5.0;
X z = 6.0 + 7.0 * y;
}
With position 1 commented out, position 2 throws an error.
With position 1 included, there is an ambiguity error.
Basically, I want to remove position 1 and with that double->X be cast via double->E->X.
Questions
What is the name of the problem?
How do I fix it?
Things I tried:
explicit keywords in front of various constructors. For E, this results in errors after position 2. For X, this results in the same error as with position 1 commented out.
removing constructors/operators from the definitions from X,E. This however is no solution, because I need to be able to include some important stuff.
trying different compilers (g++ 8.3.0 and 9.2.0, clang++ 12.0.0). This did not change the issue.
|
The ambiguity occurs because (in the x = 3.0; line) the compiler can't decide which of the two assignment operators to use: the one with the X& argument or the one with the E&, as both parameter types are convertible from the given double (because both E and X have constructors that take a const double& parameter).
You can resolve this error by providing a third assignment operator, which takes a const double& argument, like so:
struct X {
X() { /* important init stuff */ }
~X() { /* important delete stuff */ }
X(const double& r){ *this=E(r); } // Now uncommented (required)
X(const X& x) { /* important init stuff */ *this = x; }
X(const E& e) { /* important init stuff */ *this = e; }
const X& operator=(const double& x) { return *this = E(x); } // Add this!
const X& operator=(const X& x) { return *this = E(x); }
const X& operator=(const E& e) { /* important stuff */ return *this; }
};
|
74,508,049
| 74,508,349
|
How to perfectly forward multiple struct members
|
I'm looking to get some clarity on the correct way to forward multiple members from the same forwarding reference to a struct.
Example
Here's an example of forwarding two fields (one_field and another_field) to a class constructor (widget) from a forwarding reference argument info. This is how I previously thought we should do it:
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(
std::forward<Bundle>(info).one_field,
std::forward<Bundle>(info).another_field);
}
However, based on a discussion on reddit's C++ thread, I am worried that this is not the best practice, or worse that this is not safe. According to this thread, it's obviously OK to use this idiom to forward individual member fields, but this statement makes me worried it's not safe to forward multiple fields by calling forward for than once.
FWD(t).field: forward t.field, and invalidates t and all its members
(My emphasis)
What concerns me is that my example therefore is incorrect if all of the fields of info are invalidated by the initial std::forward<Bundle>(info)!
How should we be passing on multiple struct fields in a way which is theoretically and practically safe? I'm very much hoping it's not required to write a variant of std::forward which moves its argument depending on the semantics of the parent struct type.
References
Reddit discussion on single field members: https://www.reddit.com/r/cpp/comments/q4mchr/overview_of_different_ways_of_passing_struct/
Comment on multiple forwards: https://www.reddit.com/r/cpp/comments/q4mchr/comment/hfzsidd/
Found this post suggesting this is OK "in practice" but given the subtlety of C++ bugs, I'm keen to know this is OK "in theory" as well! I'm hoping that since under the hood std::forward is a static_cast to an rvalue type the invalidation doesn't happen to the other fields as would happen if a move constructor was actually called.
Similar SO question (for a single member field): How to perfectly forward a struct member?
Thanks all.
|
the forward you have already does the correct thing (i.e. forward the member as Bundle) and access a field is not like to invalidate the parent object.
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(
std::forward<Bundle>(info).one_field,
std::forward<Bundle>(info).another_field
);
}
if you want, you can also use something like std::forward_like in c++23
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(
std::forward_like<Bundle>(info.one_field),
std::forward_like<Bundle>(info.another_field)
);
}
|
74,508,173
| 74,508,262
|
static member definition outside class template template
|
I'm getting:
error: default argument for template parameter for class enclosing 'ticker<T, E, A>::garbage_element'
51 | E ticker<T,E,A> ::garbage_element;
| ^~~~~~~~~~~~~~~
l know if I use the keyword "inline" like this:
inline static E garbage_element;
inside the "ticker" template, it compiles fine,
but how in the world it suppose to look like outside the template.
#include <iostream>
#include <vector>
template< template<class, class> class T, class E, class A = std::allocator<E> >
class ticker
{
T<E,A>* container;
int current_index;
bool mode;
static E garbage_element;
public:
// constructors and members fn
};
template< template<class, class> class T, class E, class A = std::allocator<E> >
E ticker<T,E,A> ::garbage_element;
|
When defining the static data member of a class template which has a default argument for one of its template parameter, the default argument should not be repeated. It is needed only once when the class template is first declared/defined.
This means you don't need to specify the default argument for parameter A when defining the member garbage_element outside the class as shown below:
//-------------------------------------------------------v-->no default argument here
template<template<class, class> class T, class E, class A>
E ticker<T,E,A>::garbage_element;
Working demo
|
74,508,184
| 74,508,360
|
Emscripten and C++ 20
|
It looks like emscripten does not support C++ 20
I try to compile this:
#include <stdio.h>
#include <span>
using std::span;
int main() {
int a[2] = {1, 3};
printf("hello, world!\n");
return 0;
}
command:
~/emsdk/upstream/emscripten/em++ ~/Documents/helloWord.cpp
I get this:
error: no member named 'span' in namespace 'std'
using std::span;
~~~~~^
1 error generated.
em++: error: '/Users/user/emsdk/upstream/bin/clang++ -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -DEMSCRIPTEN -I/Users/user/emsdk/upstream/emscripten/cache/sysroot/include/SDL --sysroot=/Users/user/emsdk/upstream/emscripten/cache/sysroot -Xclang -iwithsysroot/include/compat /Users/user/Documents/helloWordl.cpp -c -o /var/folders/v4/krr003h50x3_bfpnlpytbdjr0000gn/T/emscripten_temp_n8xk089h/helloWordl_0.o' failed (returned 1)
Is there any way I can use C++ 20 features (particularly std::span) with emscripten.
Here are version details:
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.26 (8eaf19f1c6a9a1b0cd0f9a91657366829e34ae5c)
clang version 16.0.0 (https://github.com/llvm/llvm-project f81f0cb75a2808a67d2662f044ad07628fc9d900)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /Users/user/emsdk/upstream/bin
|
adding the flag -std=c++20 worked
Credit: @Someprogrammerdude @MarcGlisse
|
74,508,332
| 74,511,659
|
Boost::program_options how to parse multiple multi_tokens
|
is it possible to parse multiple mulit-token parameters with the same name?
Like: program.exe --param a b c --param foo bar ?
I only could get it to work like this:
program.exe --param "a b c" --param "foo bar" but then I have to split the parameter myself.
[...]
options.add_options()("param", po::value<vector<string>>()->multitoken()
, "description")
[...]
thanks for any hints
|
I think you want a combination of composing and multi-token:
Live On Coliru
#include <boost/program_options.hpp>
#include <fmt/ranges.h>
namespace po = boost::program_options;
using strings = std::vector<std::string>;
int main(int argc, char** argv) {
po::options_description opts;
opts.add_options()("param",
po::value<strings>()
->multitoken()
->composing()
->default_value({}, "")
->implicit_value({}, ""),
"you know the drill");
po::variables_map vm;
store(parse_command_line(argc, argv, opts), vm);
if (vm.contains("param")) {
fmt::print("Params: {}\n", vm["param"].as<strings>());
}
}
Which prints e.g.:
+ ./a.out
Params: []
+ ./a.out --param
Params: []
+ ./a.out --param a b
Params: ["a", "b"]
+ ./a.out --param a b --param c d
Params: ["a", "b", "c", "d"]
Note, if you don't want to allow --param without a value, remove the implicit_value: Live On Coliru
UPDATE
To the comment:
You can always use the parser section of the library, inspecting the parsed_options instance:
// using parsed-options to see "source" material:
auto parsed = parse_command_line(argc, argv, opts);
for (auto& po : parsed.options) {
auto key = po.position_key == -1 //
? po.string_key
: '#' + std::to_string(po.position_key);
fmt::print("Option {}: {}\n", key, po.value);
}
// original logic:
store(parsed, vm);
if (vm.contains("param")) {
fmt::print("Effective combined params: {}\n", vm["param"].as<strings>());
}
See it Live On Coliru, printing:
+ ./a.out
Effective combined params: []
+ ./a.out --param
Option param: []
Effective combined params: []
+ ./a.out --param a b
Option param: ["a", "b"]
Effective combined params: ["a", "b"]
+ ./a.out --param a b --param c d
Option param: ["a", "b"]
Option param: ["c", "d"]
Effective combined params: ["a", "b", "c", "d"]
|
74,508,448
| 74,508,489
|
How to pass the first element of an object to a function in C++?
|
I am trying to send the first element of an object to a function and modify its attributes and return back.
I have already created a Ray object with 20000 rays. Each single ray has its own properties.
How can I pass the first ray to a function to modify one of its property since I dont want to pass all rays because of computation time.
I tried to create a function that recevies a ray;
std::vector<Ray> hi(std::vector<Ray> bb)
{
bb.bounces++;
return bb;
}
and I tried to pass the first ray as:
hi(rays[0]);
but I receive 'no suitable used-defined conversion from "Ray" to "std::vector<Ray, std::allocator" exists.
Thank you for your help.
|
If you want to pass a single Ray, simply do so. If you want to modify it, pass it as reference (non-const), optionally returing reference to original:
Ray &hi(Ray &bb)
{
bb.bounces++; // modify the original, passed as reference
return bb; // return reference to original, for convenience
}
Or, if you don't want to modify original, but return a new, modified Ray, simply don't make it a reference:
Ray hi(Ray bb)
{
bb.bounces++; // argument is value, meaning copy, modify it
return bb; // return the copy
}
Or, another way to do the same, by passing const reference:
Ray hi(const Ray &bb)
{
auto result = bb; // get a copy
result.bounces++; // modify copy
return result; // return copy
}
If you use this option (either of above 2), you then need to modify the original by assignment:
rays[0] = hi(rays[0]);
|
74,508,689
| 74,550,835
|
C++ quicksort with const unsigned** input pointers
|
I am currently struggling with Pointers in C++, especially with the input of following function:
/*
... there is an immutable array a of unsigned integers that we are not allowed to change
In order to sort this array, a second array b containing pointers to the individual
elements in a is created. We then sort the poiners in b based on the values of the pointed-to elements in a.
(d) implement the quicksort function which sorts an array of pointers as outlined above.
Note that the parameters to this function are two pointers, one to the first element in b and
one to the first element past the end of b.
*/
// Sort the range of pointers [begin; end)
void quicksort(const unsigned** begin, const unsigned** end)
{
//TODO
}
However, the Function is given const values, so is there any way to change the position of the input pointers?
A common Quicksort algorithm relies on the swap function, I tried calling
void swap (const unsigned** a, const unsigned** b){
const unsigned** temp = **a;
**a = **b;
**b = temp;
}
with
swap(begin, (end-1));
in the Quicksort Function. But that does not not work as the value for **a cannot be changed (Here, with the value **b), due to it being const.
So how would I even be able to sort the input pointers if I cannot change their order?
|
First of all, I know this stuff is really tricky when starting out with c/c++ and I had my fair share of confusion when I did. Therefore I will try to explain it the best way I can:
What you are trying to do in your swap function is changing the actual value of the integers behind the pointers by dereferencing two times and reassigning. You got an array of pointers which is basically a pointer to the first pointer and if you dereference that two times you end up at the actual integers, however you don't want that because this integer is constant.
Instead you want to end up at the pointers to the actual integers and swap those around. You can achieve that by dereferencing only once. If you try to reasign the pointer to change what it's pointing to, you can change the order of the array of pointers without ever touching the actual integers.
your swap function should look like this:
void swap(const unsigned int** a,const unsigned int** b) {
const unsigned int* temp = *a;
*a = *b;
*b = temp;
}
and the code where you call it could look something like this:
const unsigned int sort_without_touching[] = { 1 , 2 };
const unsigned int* ptr_array[] = {&sort_without_touching[0],
&sort_without_touching[1]};
//1 2
std::cout << *ptr_array[0] << " " << *ptr_array[1] << std::endl;
swap((ptr_array+ 0), (ptr_array+ 1));
//2 1
std::cout << *ptr_array[0] << " " << *ptr_array[1] << std::endl;
|
74,508,962
| 74,508,974
|
C++ new and delete with structs
|
I have a customer node and an item node structure and I'm trying to test them. I make a customer node and add some items to its basket. However, when I'm deleting the nodes, the program mostly crashes. I'm trying to first delete the basket and then delete the customer node. The code sometimes runs fine but sometimes crashes. Why do you think it crashes? Your help is appreciated.
My code is as follows:
#include <iostream>
#include <string>
struct itemNode
{
int id;
char *itemName;
int amount;
itemNode *next;
itemNode(const int id, const char *name, const int amount, itemNode *const next = nullptr)
: id(id), amount(amount), next(next)
{
this->itemName = new char[strlen(name)];
strcpy(this->itemName, name);
std::cout << "Item " << this->itemName << " constructed." << std::endl;
};
~itemNode()
{
std::cout << "Deleting " << itemName << std::endl;
delete[] this->itemName;
if (this->next != nullptr)
{
delete this->next;
}
}
};
struct customerNode
{
int id;
char *fullName;
itemNode *basket;
customerNode *next;
customerNode *previous;
customerNode(const int id, const char *name, customerNode *const previous, customerNode *const next)
: id(id), previous(previous), next(next)
{
this->fullName = new char[strlen(name)];
strcpy(this->fullName, name);
std::cout << "Customer " << this->fullName << " constructed." << std::endl;
this->basket = nullptr;
this->next = next;
this->previous = previous;
};
~customerNode()
{
std::cout << "Deleting " << fullName << std::endl;
delete[] this->fullName;
if (this->basket != nullptr)
{
delete this->basket;
}
}
};
int main()
{
customerNode *customer1 = new customerNode(14235, "Georges Politzer", nullptr, nullptr);
itemNode *item3 = new itemNode(5355, "Pen", 2, nullptr);
itemNode *item2 = new itemNode(1351, "Folder Case", 1, item3);
itemNode *item1 = new itemNode(4412, "Paper Clips", 20, item2);
customer1->basket = item1;
delete customer1->basket;
customer1->basket = nullptr;
delete customer1;
return 0;
}
|
Error here
this->itemName = new char[strlen(name)];
strcpy(this->itemName, name);
should be
this->itemName = new char[strlen(name) + 1];
strcpy(this->itemName, name);
The + 1 is required for the nul terminator that C strings have. Without it you are corrupting the heap. Classic symptom of a corrupt heap is a crash when you free memory. Of course the better solution would be to use std::string. std::string is both simpler and more robust. There is no good reason not to use it.
Additionally in professional code your linked lists would probably be replaced by std::vector. But I guess you have no choice over that.
You should also have a close read of this link. Your current code isn't just breaking the rule of three, it's murdered it and buried the corpse in a shallow grave.
|
74,509,182
| 74,509,250
|
How can I pass a function that must be treated as a member function of template type
|
I have created the following simplified working example - where a class Manager takes a template argument and must invoke a member function get_timestamp against the template argument.
class Ex1 {
public:
int timestamp;
int get_timestamp() {return timestamp;};
};
template<typename T>
class Manager {
public:
void process_data(T& type) {
type.get_timestamp(); //
}
};
int main()
{
Manager<Ex1>();
return 0;
}
I am looking for a solution where I can replace this type.get_timestamp(); to something like type.FUNC(args); where the FUNC is passed into the class separately. Something similar to passing a lambda or std::function but the difference here is I must instruct the class to treat this "lambda"-like function as a member function of the template argument. Is that possible in C++. I am using c++20
|
You can pass a member function pointer as a template argument:
template<typename T, int(T::*FUNC)()>
class Manager {
public:
void process_data(T& type) {
(type.*FUNC)();
}
};
Manager<Ex1, &Ex1::get_timestamp> mgr;
Of course you can also pass it as a runtime argument to process_data(), or to the Manager constructor to store as a member variable.
|
74,509,244
| 74,509,285
|
Is referencing a member during Initialization valid?
|
I have a struct that contains multiple members.
these members should be constructed using another member.
Is accessing this other member for the initialization of the members valid, or am I invoking UB this way?
struct Data {
int b;
};
struct Bar {
Bar(Data& d): a(d.b){
}
int a;
};
struct Foo {
Data data;
Bar b;
};
int main() {
Foo f {.data = Data(), .b = Bar(f.data)}; // b is constructed using f.data!
}
https://godbolt.org/z/fajPjo6oa
|
Members are initialized in the order they are declared in the struct/class and you can validly reference other members during initialization, as long as they have already been initialized at that point.
This holds regardless of how initialization is performed.
|
74,509,349
| 74,510,153
|
How to fix error invalid conversion from 'char' to 'const char*' [-fpermissive]?
|
Hi i am a beginner and i have to make a simple phonebook programme in C++ using library . I would definitely use but im not allowed to as it is for an assignment. Below is my code until now and i have 3 errors which i don't know how to solve. I know conversion from char to const char* is not allowed but i really need to compare these two type c arrays and i can't figure it out how to. I am using strcmp and i am using '\0' as a char which seem correct.
#include <iostream>
#include <cstring>
using namespace std;
struct contact {
char name[30];
char surname[30];
char phone_number[30];
};
int main() {
for (int i = 0; i < 30; i++)
{
if (strcmp(person.name[i],person.surname[i]) != '\0') <--- //ERROR HERE
cout << person.name[i] << person.surname[i] << person.phone_number[i];
check++;
}
char temp;
char temp1;
cout << "Insert the name of the contact to delete: \n";
cin >> temp;
cout << "Insert the surname of the contact to delete: \n";
cin >> temp1;
int check = 0;
for (int i = 0; i < 30; i++)
{
if (strcmp(temp,person.name[i]) == 0 && strcmp(temp1, person.surname[i]) == 0)
{ ^-- // 2 ERRORS HERE CONVERSION FROM 'CHAR' TO 'CONST CHAR*'
cout << "Contact deleted!\n";
person.name[i] = '\0';
person.surname[i] = '\0';
person.phone_number[i] = '\0';
check++;
}
if (check == 0)
{
cout << "This person is not in your contact list\n ";
return 0;
}
|
maybe you don't understand struct well, here is a sample I have revised, you can take it for reference
#include <iostream>
#include <stdio.h>
using namespace std;
struct person{
char name[30];
char surname[30];
char phone_number[30];
};
int main()
{
person Persons[] = { // structure initialization
{"Bob","Thug Bob","01230123"},
{"Marry","Gangster Marry","9999999"},
{"Somebody","Mr Somebody","777777"}
};
int Size = sizeof(Persons)/sizeof(Persons[0]); // return size of Persons array
for(int i=0;i<Size;i++){
cout << Persons[i].name << "\t"<< Persons[i].surname << "\t"<< Persons[i].phone_number <<endl;
}
return 0;
}
|
74,509,409
| 74,509,487
|
Segmentation fault whrn trying to sort the array by quick sort
|
I'm making a program of quick sort which prints the sorted elements of the arry but when I run the code I get segmentation fault
#include <iostream>
using namespace std;
int partition(int arr[],int left,int right,int pivot) {
while(left <= right) {
while(arr[left] < pivot) {
left++;
}
while(arr[right] > pivot) {
right--;
}
if(left <= right) {
swap(arr[left],arr[right]);
left++;
right--;
}
}
return left;
}
void quick_sort(int arr[],int left,int right) {
int pivot = arr[(left+right)/2];
int index = partition(arr,left,right,pivot);
quick_sort(arr,left,index-1);
quick_sort(arr,index,right);
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int size = sizeof(arr)/sizeof(arr[0]);
quick_sort(arr,0,size-1);
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
I was expecting a soted arrray of elements which are hardcoded.
|
Add this to top your quick_sort function
if (left >= right)
return;
|
74,509,450
| 74,509,618
|
Call a block of code once every 10ms in a while loop without stopping the loop c++
|
So I'm trying to run a block of code once every 10ms in a while loop without stopping the loop (sleeping).
I would like to achieve something like this:
while (true) {
if (should_run_the_10ms_code) {
// some code (once every 10 ms)
}
// some other code (every tick)
}
|
std::chrono::steady_clock::now gives you the current time from a monotonic clock. Here is a relatively simple way to use it:
auto timer = std::chrono::steady_clock::now();
while (true) {
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> timer_diff_ms = timer - now;
if (timer_diff_ms >= 10.0) {
// some code (once every 10 ms)
timer = now;
// or
// timer = std::chrono::steady_clock::now();
// if the "some code" takes a bit of time
}
// some other code (every tick)
}
Note that timer_diff_ms might be much greater than 10 if something lenghty happens between the now() calls (might be in the "some other code" part, might be completely unrelated to your program).
You can also use std::chrono::milliseconds instead of std::chrono::duration<double, std::milli> if you don't need a double (it will be some integer type).
|
74,509,711
| 74,511,403
|
Boost multiprecision cpp_float not working properly when not using cpp_bin_float_(50/100)
|
I need to do calculations with higher precision than doubles and am using boost::multiprecision for that. This works perfectly fine when I use boost::multiprecision::cpp_bin_float_50 or boost::multiprecision::cpp_bin_float_100. So simply doing something like
#include <boost/multiprecision/cpp_bin_float.hpp>
// ...
boost::multiprecision::cpp_bin_float_100 Test1, Test2;
Test1 = 1.0;
Test2 = 2.0;
Test1 = Test1 + Test2;
works. But I need different amounts of precision. So for example, I'd simply like to do something like
boost::multiprecision::cpp_bin_float<200> Test1, Test2;
Test1 = 1.0;
Test2 = 2.0;
Test1 = Test1 + Test2;
While the first three lines work fine, I get an error in the forth line saying "no matching operator found". Also .convert_to<double>() is not found, which I will need later. Same thing for cpp_dec_float...
I'm sure, I am missing something stupid here. Can anybody help?
Edit:
Thank you sehe - I just wanted to edit in the exact same thing. It took me ages to find that out. Funny how I couldn't find one single example of how to use arbitrary lengths other than ..._50 or ..._100...
|
The boost::multiprecision::cpp_bin_float<200> type is a backend type. You want a frontend type, which would be e.g.
number<cpp_bin_float<200> >
You can compare this with the definitions of the working types:
using cpp_bin_float_50 = number<backends::cpp_bin_float<50> > ;
using cpp_bin_float_100 = number<backends::cpp_bin_float<100> >;
Backends define the implementation, where the frontend provides the usability interfaces that you expect, like operator overloads.
Live Demo
#include <boost/multiprecision/cpp_bin_float.hpp>
namespace bmp = boost::multiprecision;
int main() {
bmp::number<bmp::cpp_bin_float<200>> v(0);
v += 2.0;
v = pow(v, 156);
std::cout << std::fixed << v;
}
Prints:
91343852333181432387730302044767688728495783936.000000
|
74,509,839
| 74,521,330
|
How to include Libraries without an IDE
|
I just downloaded the MingW Compiler and the glfw and glad libraries. i set up Notepad++ to compile with mingW and now i cant figure out how to include the above mentiond libraries. do i have to put the .h files in my folder with my main.cpp file or smth? where do i have to unzip my libraries to. I have absolutly no idea and have been searching the web for hours.
I have unzipped the libs into the same folder as the main.cpp file and then called smth like this in the main.cpp
include<librariename/include/lib.h>
|
First of all, consider MinGW-w64, it's much more up to date than MinGW and supports both Windows 32-bit and 64-bit. You can get standalone versions from https://winlibs.com/, or you can install it from MSYS2 using pacman.
To use a library you need to do several things:
Include the header file(s) in your code using #include <someheader.h>.
Tell the gcc compiler where to find the header file(s) using the -I (-Iheaderpath) compiler flag.
Tell the gcc linker where to find the library file using the -L (-Llibrarypath) linker flag.
Tell the compiler to actually use the library with the -l (-llibrary) linker flag. This will make the linker look for the library file by adding lib in front of the specified library name and .a after (or .dll.a in case of shared build).
So for example if you have the following files:
/C/Temp/bin/glfw.dll
/C/Temp/include/GL/glfw.h
/C/Temp/lib/libglfw.a
Then you shoule add #include <GL/glfw.h to your code and build like this (if your code is in main.c):
gcc -c -o main.o main.c -I/C/Temp/include
gcc -o main.exe main.o -L/C/Temp/lib -lglfw
In the above example the first line is the compiler step and the second line the linker step. You could combine both steps like this:
gcc -o main.exe main.c -I/C/Temp/include -L/C/Temp/lib -lglfw
But as your project grows it's better to keep compiler and linker steps separated.
In fact, as your project grows you may want to consider using some kine of build system (like make or cmake).
|
74,510,107
| 74,510,449
|
How to extract a particular line from an external txt file using C++ and then output the line as a string?
|
This code only works for printing the first line. What should I do to print only the second or third line?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string str;
string lineFromFile;
ifstream myfile("./file.txt");
while(getline(myfile,lineFromFile)){
str = lineFromFile;
cout << str << endl;
break;}
}
|
You can count the lines and equate your expected line number with the counter to output your line as in the below example.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int count = 1;
int line_count;
string str;
string lineFromFile;
ifstream myfile("./file.txt");
std::cin >> line_count;
while(getline(myfile,lineFromFile)){
if(line_count == count)
{
str = lineFromFile;
std::cout << str << std::endl;
break;
}
count++;
}
}
|
74,510,288
| 74,511,189
|
Implementing Square Root function in C++ not Working
|
double _sqrt(double n)
{
double sqrt = 0, c = 0, prec = 1;
for (;; sqrt += prec) //increments sqrt per precision
{
c = sqrt * sqrt;
if (c == n)
{
return sqrt;
}
if (c > n) // if square is greater then..
{
sqrt -= prec; // decrement squareroot by previous precision
prec *= 0.1; // increase precision eg. 1, 0.1, 0.01, 0.001 .....INF
}
}
}
This is the square root function that I've done. It works for some numbers but for others its just blank, doesn't return a thing. Where am I getting this wrong?
|
Your code has a few problems in it, the first one being that your code may infinitely loop as you try to have an infinite accuracy for a (possibly) irrational number. Although doubles do not have an infinite accuracy, I certainly wouldn't recommend trying to evaluate that function to that high of a degree of accuracy. The solution to this is to add some sort of 'precision' or 'epsilon' value (as mentioned in the comments below). Or even better to break out of the loop when increment becomes too small (as @Pete Becker suggested):
double _sqrt(const double& n)
{
const double precision = 0.000001;
double increment = 1.0, sqrt = 0.0;
while (true)
{
if (increment <= precision)
break;
else if (sqrt * sqrt > n)
{
sqrt -= increment;
increment *= 0.1;
}
else
sqrt += increment;
}
return sqrt;
}
You can of course do this with the standard library, using std::sqrt, but I assume you are doing this for fun.
If you are interested in other square root algorithms, there are some scary looking ones on Wikipedia here.
One that I personally like is Newton's Method, but this is for finding the root's of functions in general.
An application of this for the square root function that I copied and modified from here is:
double _sqrt(const double& n)
{
const double precision = 0.00001;
double sqrt, x = n;
while (true)
{
sqrt = 0.5 * (x + (n / x));
if (std::abs(sqrt - x) < precision)
break;
x = sqrt;
}
return sqrt;
}
|
74,510,609
| 74,521,895
|
Do dependent reads require a load-acquire?
|
Does the following program expose a data race, or any other concurrency concern?
#include <cstdio>
#include <cstdlib>
#include <atomic>
#include <thread>
class C {
public:
int i;
};
std::atomic<C *> c_ptr{};
int main(int, char **) {
std::thread t([] {
auto read_ptr = c_ptr.load(std::memory_order_relaxed);
if (read_ptr) {
// does the following dependent read race?
printf("%d\n", read_ptr->i);
}
});
c_ptr.store(new C{rand()}, std::memory_order_release);
return 0;
}
Godbolt
I am interested in whether reads through pointers need load-acquire semantics when loading the pointer, or whether the dependent-read nature of reads through pointers makes that ordering unnecessary. If it matters, assume arm64, and please describe why it matters, if possible.
I have tried searching for discussions of dependent reads and haven't found any explicit recognition of their implicit load-reordering-barriers. It looks safe to me, but I don't trust my understanding enough to know it's safe.
|
Your code is not safe, and can break in practice with real compilers for DEC Alpha AXP (which can violate causality via tricky cache bank shenanigans IIRC).
As far as the ISO C++ standard guaranteeing anything in the C++ abstract machine, no, there's no guarantee because nothing creates a happens-before relationship between the init of the int and the read in the other thread.
But in practice C++ compilers implement release the same way regardless of context and without checking the whole program for the existence of a possible reader with at least consume ordering.
In some but not all concrete implementations into asm for real machines by real compilers, this will work. (Because they choose not to look for that UB and break the code on purpose with fancy inter-thread analysis of the only possible reads and writes of that atomic variable.)
DEC Alpha could famously break this code, not guaranteeing dependency ordering in asm, so needing barriers for memory_order_consume, unlike all(?) other ISAs.
Given the current deprecated state of consume, the only way to get efficient asm on ISAs with dependency ordering (not Alpha), but which don't do acquire for free (x86) is to write code like this. The Linux kernel does this in practice for things like RCU.
That requires keeping it simple enough that compilers can't break the dependency ordering by e.g. proving that any non-NULL read_ptr would have a specific value, like the address of a static variable.
See also
What does memory_order_consume really do?
C++11: the difference between memory_order_relaxed and memory_order_consume
Memory order consume usage in C11 - more about the hardware mechanism / guarantee that consume is intended to expose to software. Out-of-order exec can only reorder independent work anyway, not start a load before the load address is known, so on most CPUs enforcing dependency ordering happens for free anyway: only a few models of DEC Alpha could violate causality and effectively load data from before it had the pointer that gave it the address.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0371r1.html - and other C++ wg21 documents linked from that about why consume is discouraged.
|
74,510,633
| 74,510,749
|
How to call EXPECT_CALL gtest macro before the object construction
|
I have a class that calls a mocked function in the initializer list.
I want to use EXPECT_CALL in order to verify that the mocked function is called only once.
The problem is that I can't use the macro before the constructor because it's the first function that runs, neither after it because the mocked function is called in the constructor.
For example:
ui.cpp
class UI {
public:
UI() = default;
~UI() = default;
virtual std::string get_name() {
std::string name;
std::cin >> name;
return name;
}
};
foo.cpp
class Foo {
public:
Foo(UI& ui) : m_name(ui.get_name()) {}
~Foo() = default;
};
mock_ui.hpp
class MockUI : public UI {
MockUI() : UI() = default;
~MockUI() = default;
MOCK_METHOD(std::string, get_name, (), (override));
};
The problem occurs here:
foo_test.cpp
class FooTest : ::testing::Test {
public:
// I want to call EXPECT_CALL(m_ui, get_name()) before this line executes.
FooTest() : m_foo(MockUI()) {}
~FooTest() = default;
protected:
void SetUp() override {}
void TearDown() override {}
Foo m_foo;
MockUI m_ui;
};
I tried initializing the Foo object in the SetUp() function, but Foo doesn't have default constructor so it has to be initialized in the FooTest constructor.
The Solution?
The only idea I have is to call EXPECT_CALL() in MockUI constructor like this:
mock_ui.hpp
class MockUI : public UI {
MockUI() : UI() {
EXPECT_CALL(*this, get_name());
}
~MockUI() = default;
MOCK_METHOD(std::string, get_name, (), (override);
};
The problem is that I might use MockUI without calling get_name() or calling it multiple times, but this is the best solution I have.
Any other suggestions?
|
You can defer initialization of Foo by using a pointer:
class FooTest : ::testing::Test {
public:
FooTest()
{
EXPECT_CALL(m_ui, get_name());
m_foo = std::make_unique<Foo>(m_ui);
}
protected:
std::unique_ptr<Foo> m_foo;
MockUI m_ui;
};
Or by adding a parent class that will initialize MockUI first:
class FooTestHelper: public ::testing::Test
{
public:
FooTestHelper() { EXPECT_CALL(m_ui, get_name()); }
protected:
MockUI m_ui;
};
class FooTest : public FooTestHelper
{
public:
FooTest(): FooTestHelper{}, m_foo{m_ui} {}
private:
Foo m_foo;
};
|
74,511,091
| 74,511,130
|
adding other random characters to the compiled code
|
enter image description here
here is the code in C++ but after compiling and seeing the results, some random characters are added to the characters that the program should display
compilation result as above picture
why is this happening why those characters that are not declared in the code are added
here is my code:
#include <iostream>
using namespace std;
int main()
{
char big_characters[26] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
cout << big_characters;
cout << endl << endl;
char small_characters[26] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'};
cout << small_characters;
cout << endl << endl;
char digits[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
cout << digits;
cout << endl << endl;
char special_characters[32] = {'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', ';', ':', '|', ',', '<', '.', '>', '/', '?', char(34), char(39), char(92)};
cout << special_characters;
cout << endl << endl;
return 0;
}
as I mentioned earlier, some random characters are added to my code as a result of compilation. I don't know why this happening
I think the solution to the problem is to use string instead of single characters (char)
I want to know why this is happening in this case
compilation result as above
|
So if you want to output your arrays with no random characters outputed(undefine behaviour) you need to use a simple for loop and then you will get the correct output, like this:
#include <iostream>
using namespace std;
int main() {
char big_characters[26] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O',
'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K',
'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
for (int i = 0; i < 26; i++) {
cout << big_characters[i];
}
cout << endl << endl;
char small_characters[26] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k',
'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm'};
for (int i = 0; i < 26; i++) {
cout << small_characters[i];
}
cout << endl << endl;
char digits[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
for (int i = 0; i < 10; i++) {
cout << digits[i];
}
cout << endl << endl;
char special_characters[32] = {
'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(',
')', '-', '_', '=', '+', '[', ']', '{', '}', ';', ':',
'|', ',', '<', '.', '>', '/', '?', char(34), char(39), char(92)};
for (int i = 0; i < 32; i++) {
cout << special_characters[i];
}
cout << endl << endl;
return 0;
}
You can see it live here. It has the output:
QWERTYUIOPASDFGHJKLZXCVBNM
qwertyuiopasdfghjklzxcvbnm
1234567890
`~!@#$%^&*()-_=+[]{};:|,<.>/?"'\
with no random characters on the end.
Or instead of the hard coded for loops you could use the std::cout member function write():
cout.write(special_characters, 32);
So you would do cout.write( then the name of the array for example special_characters, then the size for example 32 and then );. They both have the same output, it is just two ways of getting the same thing. But the second one avoids the hard coded: for(...), loop.
|
74,511,440
| 74,511,453
|
Is it possible to declare a pair that contains a pointer to a similar pair
|
I am looking for something like:
pair<int, pair<int, ...>*>*> p;
Is it possible to declare such pair? Is there already a data structure for this?
|
struct A
{
std::pair<int, A *> p;
};
You could also inherit from the pair, but I wouldn't do it to keep the code simpler.
|
74,511,594
| 74,512,715
|
Can one volatile constexpr variable initialize another one in C++?
|
C++ standard allows constexpr volatile variables per defect report 1688, which was resolved in September 2013:
The combination is intentionally permitted and could be used in some circumstances to force constant initialization.
It looks though that the intention was to allow only constinit volatile, which was not available before C++20.
Still the current compilers diverge in treatment of constexpr volatile in certain circumstances. For example, this program initializes one such variable by the other one:
int main() {
constexpr volatile int i = 0;
constexpr volatile int j = i;
return j;
}
It is accepted in GCC and MSVC, but Clang complains:
error: constexpr variable 'j' must be initialized by a constant expression
constexpr volatile int j = i;
^ ~
note: read of volatile-qualified type 'const volatile int' is not allowed in a constant expression
constexpr volatile int j = i;
Online demo: https://gcc.godbolt.org/z/43ee65Peq
Which compiler is right here and why?
|
Clang is correct. The initialization of j from i requires that an lvalue-to-rvalue conversion be performed on i, but according to [expr.const]/5.9, an lvalue-to-rvalue conversion on a volatile glvalue is never permitted inside a constant expression. Since i is a constexpr variable, it must be initialized by a constant expression.
I have no idea why GCC and MSVC choose not to enforce this rule, other than that all C++ compilers are perpetually short-staffed and can't implement everything they're expected to.
|
74,512,080
| 74,512,096
|
C++ use function's output as functions input n times
|
I'm sorry for the weird title. I don't know how to word this.
If I have function func()
How do I do this:
func(func(func(func(func(x)))))
where it repeats N times?
I'm trying to implement Conway's Game of Life. I have a function that takes a vector and outputs another vector, which is the next generation of the input vector. So generation 3's vector would be func(func(func(x))).
|
The easy way, simply using for loop:
int x = some_initial_value;
for (int i = 0; i < NUMBER_OF_ITERATIONS; ++i)
{
x = func(x);
}
|
74,512,166
| 74,552,120
|
Sorting pairs of elements from vectors to maximize a function
|
I am working on a vector sorting algorithm for my personal particle physics studies but I am very new to coding.
Going through individual scenarios (specific vector sizes and combinations) by brute force becomes extremely chaotic for greater numbers of net vector elements, especially since this whole code will be looped up to 1e5 times.
Take four vectors of 'flavors' A and B: A+, A-, B+, and B-. I need to find two total pairs of elements such that some value k(V+, V-) is maximized with the restriction that different flavors cannot be combined! (V is just a flavor placeholder)
For example:
A+ = {a1+}
A- = {a1-}
B+ = {b1+, b2+}
B- = {b1-}
Since A+ and A- only have one element each, the value k(A+, A-) -> k(a1+, a1-). But for flavor B, there are two possible combinations.
k(b1+, b1-) OR k(b2+, b1-)
I would like to ensure that the combination of elements with the greater value of k is retained. As I said previously, this specific example is not TOO bad by brute force, but say B+ and B- had two elements each? The possible values would be:
k(b1+, b1-) or k(b2+,b2-) or k(b1+, b2-) or k(b2+, b1-)
where only one of these is correct. Furthermore, say two of those four B+B- combinations had greater k than that of A+A-. This would also be valid!
Any help would be appreciated!!! I can clarify if anything above is overly confusing!
I tried something like this,
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
static bool sortbypair(const pair<double, double> &a, const pair<double, double> &b)
{
return (k(a.first, a.second) > k(b.first, b.second)) && k(a.first, b.second) < k(a.second, b.first);
}
But I can't flesh it out.
|
Thank you to everyone who commented!!! I really appreciate your effort. The solution ended up being much simpler than I was making it out to be.
Essentially, from the physics program I'm using, the particles are given in a listed form (ie. 533 e-, 534
p+, 535 e+, etc.). I couldn't figure out how to get range-v3 working (or any external libraries for that matter but thank you for the suggestion) so I figured out to make a tuple out of the indices of combined particles and their associated k value.
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
static bool weirdsort(const tuple<int, int, double> &a, const tuple<int, int, double> &b)
{
return get<2>(a) > get<2>(b);
}
int main()
{
vector<tuple<int, int, double>> net;
// Sample ptcl list
//
// A+ A- B+ B-
// 0 a1+
// 1 a1-
// 2 b1-
// 3 b1+
// 4 a2+
// 5 a2-
for(int i = 0; i < A+.size(); i++)
{
for (int j = 0; j < A-.size(); j++)
{
net.push_back(A+[i], A-[j], k(A+[i], A-[j]));
}
}
sort(net.begin(), net.end(), weirdsort);
//Now another for loop that erases a tuple (with a lower k value) if it has a repeated ptcl index.
for (int i = 0; i < net.size(); i++)
{
if (get<0>(net[i]) == get<0>(net[i + 1]) || get<1>(net[i]) == get<1>(net[i + 1]))
{
net.erase(net.begin() + i + 1);
}
}
//Now can plot third tuple element of net[0] and net[1]
return 0;
}
It's not quite perfect but since I'm only looking for the first two highest k values it works out just fine. Thanks again!
|
74,512,695
| 74,512,710
|
C++ move constructor called instead of copy constructor
|
I have this snippet of code which I'm compiling with g++.exe -std=c++20:
#include <iostream>
using namespace std;
class A {
public:
A() = delete;
A(int value) : value(value) {}
// A(auto &other) {
// cout << "Copy constructor called..." << endl;
// value = other.value;
// }
void operator=(const auto &other) = delete;
A(auto &&other) {
cout << "Move constructor called..." << endl;
value = other.value;
}
~A() { cout << "Destructor called..." << endl; }
friend ostream &operator<<(ostream &os, const A &a);
private:
int value;
};
ostream &operator<<(ostream &os, const A &a) {
os << a.value;
return os;
}
int main() {
A p1(2);
cout << "p1: " << p1 << endl;
A p2(p1);
cout << "p2: " << p2 << " p1: " << p1 << endl;
return 0;
}
The problem I'm having is that when the copy constructor is commented the output is
Move constructor called...
p2: 2 p1: 2
Destructor called...
Destructor called...
And if I uncomment the copy constructor, the output becomes
p1: 2
Copy constructor called...
p2: 2 p1: 2
Destructor called...
Destructor called...
I am wondering why doesn't the compiler just call a default copy constructor (what happens when I delete the move constructor or change its argument to const, so it doesn't match the call).
|
In this case it's not actually a move constructor, it's a constructor with a universal reference, so it takes both lvalues and rvalues. If you want to restrict it to rvalues only, you should use explicit type:
A(A &&other) {
...
}
I am wondering why doesn't the compiler just call a default copy constructor (what happens when I delete the move constructor or change its argument to const, so it doesn't match the call).
Be advised that this won't happen, because copy operations are implicitly deleted if you explicitly add any move operation, so you will have to add it explicitly in this case:
A(const A &other) = default;
|
74,512,885
| 74,512,969
|
Implementation of std::vector<T>::iterator::operator[]
|
For this code:
std::vector<int> vec{0, 1, 2, 3, 4, 5, 6, 7};
std::cout << (vec.begin() + 4)[2] << " \n"; // prints out 6
std::cout << (vec.begin() + 4)[-1] << "\n"; // prints out 3
It output 6 and 3 as expected.
I checked the cppreference, but couldn't find the definition of std::vector::iterator::operator[], so I am wondering if is this actually defined behavior.
I checked the header file vector and follows it to bits/stl_vector.h and the iterator definition at bits/stl_iterator.h. My compiler version is g++-11 (Ubuntu 11.1.0-1ubuntu1~20.04) 11.1.0
It is clear that in bits/stl_iterator.h an iterator's element (_M_current) is a T* (see the iterator's typedef in bits/stl_vector.h). So negative index as pointer arithmetic makes sense. But is it defined, that the type iterator must imitate a T*, such that all arithmetic operations of a random access iterator must be compatible with a pointer?
Also, is T*::operator[] defined in C++? Where can I find its definition?
|
std::vector<T>::iterator is a Cpp17RandomAccessIterator, where for an iterator a, a[n] works as *(a + n).
And "T*::operator[]" is called the "built-in subscript operator" which, when selected, means pointer[index] is identical to *((pointer) + (index)). It is defined here, satisfying the requirement for Cpp17RandomAccessIterator immediately.
For the purposes of overload resolution, it has the signature T& operator[](T*, std::ptrdiff_t) (Though the index isn't actually converted to std::ptrdiff_t). This is a built-in declaration, so will be somewhere in the compiler itself.
|
74,512,997
| 74,513,118
|
Why is the C++ standard library divided into several components/libraries?
|
The C++ standard divides the standard library into different distinct components/libraries. Some components are built up of several headers.
Why is the standard organized in this way? What practical advantage does this bring us? Why doesn't the standard library only define headers (+ potentially implementations)?
I am assuming that this information can even be somewhat important to a C++ Dev instead of a committee member/compiler vendor, as cppreference for example often specifies from which library a given header comes from:
This header is part of the general utility library.
See here for example. Is this assumption true? If yes, when?
|
Separation of concerns, organization, etc. is already achieved with the definitions of the headers.
Are they?
Consider Chapter 22: Utilities. This chapter covers material defined in 13 separate headers. The standard could have had 13 separate chapters, but like... why? What good is that? Is there some reason advantage to putting all of these in separate chapters, when they'd be much shorter than most other chapters?
Consider Chapter 31: Input/Output. This chapter covers stuff defined in 14 separate headers. But the stuff in those headers are often highly related to one another. All of the streams are ultimately built on the iostream base classes. Some of them reference things in other headers, like the ability for file streams to use filesystem::path objects.
But they're all ultimately stuff about input/output. So it makes sense to bundle them all into one chapter.
They could have had 14 separate chapters, one for each header, but there would be no benefit to that. Indeed, you would now have no place to put the Iostreams requirements section, which is not bound to any header at all.
Speaking of important information that isn't bound to a header, one of the most important sections in the Container chapter is the Requirements section, which applies to every container. This section is absolutely vital for understanding anything that's happening in any of the container documentation, and in many cases defines the behavior of several functions whose definitions aren't listed in the section for those individual headers. This is because those functions behave the same way for all containers.
I mean, do we really need to see nine separate repetitions the definitions for begin, end, etc? The whole point of the containers is to have a uniform interface so that you can understand how stuff works easily. And if you're going to have a uniform interface, repeating the definition of that interface is rather pointless.
And then there are places where the standard can just point directly to a chapter and says, "all that stuff also has this property." The most important being the concept of freestanding implementations. Freestanding implementations are C++ implementations that don't want to implement the entire standard library because it has a lot of stuff their customers don't really need (microcontrollers don't care about filesystems, for examples). But there are parts of the standard library that must be implemented even by those systems.
This was more prominent in pre-C++23 standards, but in many cases, the standard would just say "everything in this chapter/section must be in freestanding". That's a lot easier to do when a chapter/section can contain as many headers as it makes sense to.
This is probably part of the reason why the Atomic chapter is not part of the Threading chapter (again, pre-C++23).
The organization is purely for human purposes. It has no bearing on how implementations are written, outside of the freestanding stuff.
|
74,513,172
| 74,513,292
|
Understanding C++ function with return type void *
|
I am working in Unreal Engine C++ and wish to fetch the vertex normals of a static mesh. To do this I am using the GetTangentData() method which belongs to the FStaticMeshVertexBuffer class (link).
The GetTangentData() method is defined two ways in the docs (link1, link2):
void * GetTangentData()
const void * GetTangentData() const
My understanding is that this is a getter function. However, I am unsure why it has a void pointer return type. The following line compiles but I am unsure how to access the data:
void* TangentData = StaticMeshVertexBuffer->GetTangentData();
Q1. What is the reason to have a void pointer return type?
Q2. How can one access the data from such a return?
|
Q1. What is the reason to have a void pointer return type?
A void* is a pointer to something, but that something is not known. Thus, there is a degree of flexibility to void*, resulting in the ability to be cast into many types of pointers. For example, malloc has a return type of void* because it's supposed to be used to allocate memory for all types of pointers. In C++, we can code function overloads because templates exist, so void* is more of a C thing. It is used in C++ to maintain backwards compatibility with C for libraries that are designed for usage with both C++ and C.
Q2. How can one access the data from such a return?
You typecast it:
void* void_ptr = func_that_returns_void_ptr();
char* char_ptr_typecast = (char*) void_ptr;
std::cout << char_ptr_typecast << '\n';
|
74,513,211
| 74,513,378
|
BOOST_FUSION_ADAPT_STRUCT using a recursive struct with a std::vector<self_type> member
|
I am trying to declare a recursive AST for a spirit x3 parser. The parser grammar is working, and since it is recommended to avoid semantic actions I am trying to adapt the Rexpr official documentation example.
In the main documentation, the parsed structure can be represented by a map where keys are strings and values are either a string or another map.
In my case, the structure being parsed is a simple n-ary tree, and I hoped I could get my way out with a recursive struct and forward_ast:
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
namespace ast
{
struct node
{
std::string name;
double length;
std::vector<boost::spirit::x3::forward_ast<node>> children;
};
}
BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)
But I did not succeed having this compile - boost fusion tells me that
error: explicit specialization of undeclared template struct 'tag_of'
BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)
So I guess I failed to understand either:
the logic of recursive ast,
the syntax to use to tell boost fusion about this nested type?
or both?
|
I'm not sure I follow the problem, but perhaps this helps:
Live On Compiler Explorer
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <iostream>
namespace ast {
using boost::spirit::x3::forward_ast;
struct node {
std::string name;
double length;
std::vector<forward_ast<node>> children;
};
} // namespace ast
BOOST_FUSION_ADAPT_STRUCT(ast::node, name, length, children)
namespace ast {
using boost::fusion::operator<<;
static inline std::ostream& operator<<(std::ostream& os, std::vector<forward_ast<node>> const& nn) {
os << "[";
auto sep = "";
for (auto& n : nn)
os << std::exchange(sep, ", ") << n.get();
return os << "]";
}
} // namespace ast
int main() {
ast::node n{
"demo",
42,
{
ast::node{"nested1", 43, {}},
ast::node{"nested4",
47,
{
ast::node{"nested2", 45, {}},
ast::node{"nested3", 46, {}},
}},
ast::node{"nested5", 48, {}},
},
};
std::cout << "No problem: " << n << "\n";
}
Prints
No problem: (demo 42 [(nested1 43 []), (nested4 47 [(nested2 45 []), (nested3 46 [])]), (nested5 48 [])])
|
74,513,309
| 74,513,353
|
Program doesn't execute for loop until the end
|
I'm writing a code to enter subjects' information where I put void function and array as an object. But not sure when I wanna loop it, it doesn't come until the end. Have a look at the code.
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=1; year<=4; year++) {
for (sem=1; sem<=2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 1; i <= totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
return 0;
}
Here's the error. You can see the compiler only shows until entering the subject name but credit hour and grade are omitted. What should I do?
Expected: It should everything in void function until 3 (since I put 3) and then start over again "Enter total subject you take in Year 1 sem 2" but it also omits that
|
Take note that in C++ 0 is the first element, and n-1 is the last element. By looping to n, you cause a buffer overflow, hence resulting an error.
A solution would be as follows
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=0; year<4; year++) {
for (sem=0; sem<2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 0; i < totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
}
|
74,513,422
| 74,513,462
|
C++ Why i'm getting trailing whitespace in the output of this?
|
This is a solution i've been working on for this codewars problem: https://www.codewars.com/kata/56a5d994ac971f1ac500003e/cpp
I want the output to be "abigailtheta". I'm getting the correct output on vscode and the correct output when I compile the code from the terminal as well, but the codewars site shows that the output is "abigail which tells me that there is whitespace tail in my output that i didn't see before (the output from the terminal and vscode didn't have the strings format). Any idea where that whitespace in the end comes from?
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
class LongestConsec
{
public:
static std::string longestConsec(const std::vector<std::string> &strarr, int k)
{
std::string concChars{};
std::string maxChars{};
for (int i{}; i < strarr.size(); ++i)
{
concChars = strarr[i];
for (int y{i + 1}; y < (i + k); ++y)
{
concChars += strarr[y];
}
maxChars = (maxChars.length() < concChars.length()) ? concChars : maxChars;
}
return maxChars;
}
};
int main()
{
LongestConsec a;
std::vector<std::string> v{"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
std::cout << a.longestConsec(v, 2) << '\n';
return 0;
}
|
I think your issue comes from here.
for (int y{i + 1}; y < (i + k); ++y)
{
concChars += strarr[y];
}
What happens if i+k >= strarr.size()? what is strarr[y] when y greater than strarr.len()-1? It can be whitespace, or some stranger character, or better, it crashes your program.
|
74,513,590
| 74,513,644
|
Is the content of a predicate in c++ wait_for method mutex protected or not?
|
Suppose, countMe is a global variable and I am launching 10 threads at the same time to this while loop, is the variable countMe mutex protected in the predicate?
I think because when the code reaches to the wait_for it unlocks and releases the lock, the variable countMe isn't mutex protected. Am I right?
while (true)
{
std::unique_lock<std::mutex> lock(mtx_kill);
cv_kill.wait_for(lock, 500ms, [&]() {++countMe; return killFlag; });
if (killFlag)
{
break;
}
}
|
Am I right?
Nope, you're wrong.
I think because when the code reaches to the wait_for it unlocks the
lock, the variable countMe isn't mutext protected.
No, the mutex is in a locked state when the lambda gets evaluated. Guaranteed.
cppreference.com describes the predicate version of wait_for in terms of wait_until, which is described as follows:
while (!stop_waiting()) {
if (wait_until(lock, timeout_time) == std::cv_status::timeout) {
return stop_waiting();
}
}
Note that the initial state of the mutex is that it's locked. The predicate, called "stop_waiting" here, is always called when the mutex is in the locked state.
You can think of wait_for as just a predicate-less wait, with the additional predicate check as a discrete, separate step. After wait returns the mutex gets relocked, and that happens before the predicate, your lambda, executes. If it votes thumbs down the mutex gets, once again, atomically unlocked together with the condition variable getting waited on again.
P.S. The above discussion presumes that your countMe is always accessed, elsewhere, with the same lock being held. This is presumed by your question, but merely formally noted.
|
74,513,623
| 74,514,599
|
c++ template template syntax: simplicity vs useability why not 'auto'
|
first code below compiled fine after sweating with the word 'class' five times
in one line, and definition in "main" of shelf<std::vector, int> top_shelf;
looks too fragmented to me, all of that just extract "class E : value_type" out of
container.I needed this type_value so I can keep dummy:garbage_value in case an error out of range
indexing through the container something like:
E& return_value_type_at(int x ){ return check(x)? (*container)[x] : garbage_value; }
here is the first code:
#include <iostream>
#include <vector>
template< template<class, class> class C, class E, class A = std::allocator<E> >
class shelf
{
C<E,A>* container;
// E garbage_value; // not completely implemented
public:
// bool check(x);
shelf(C<E,A>& x) : container{&x}{ }
E& return_value_type_at(int x ){ return /*check(x)?*/(*container)[x]/* : garbage_value*/; }
};
int main()
{
std::vector<int> box = {1,2,3,4};
shelf<std::vector,int> top_shelf{box};
return 0;
}
the second code below, compiled fine, looks a lot simpler:
#include <iostream>
#include <vector>
template<class T>
class shelf
{
T* container;
public:
shelf(T& x) : container{&x}{ }
auto& value_type_at(int x ){ return (*container)[x]; }
};
int main()
{
std::vector<int> box = {1,2,3,4};
shelf< std::vector<int> > top_shelf{box};
return 0;
}
here the keyword 'auto' helped me out because I have no clue what to replace it with,
which is a problem in the same way, how am I going to do the "garbage_value"?
another thing why not 'auto' here:
/home/insights/insights.cpp:16:9: error: 'auto' not allowed in template argument
shelf<auto> top_shelf{box};
^~~~
it makes a lot of sense: auto => 'box' template structure.
so is there a way to get "class E" out of the second code?
|
If T is the vector type, then you can get the value type by T::value_type:
template<typename T>
class shelf
{
T::value_type garbage_value;
// ⋮
};
|
74,513,660
| 74,513,753
|
Using funcion overload with the different child classes when I only have a list that contains the parent class
|
First a little explanation of my code to put into context the problem:
I have a class that is responsible for drawing stuff on the screen, I use an overloaded function to draw the different types of drawable entities, the fuctions look like this:
draw(entityType1* name);
draw(entityType2* name);
draw(entityType3* name);
...
All entities classes are derived from a parent "Entity" Class
I wrote a class named "Scene" that has an entity list with all drawable objects in the scene, I'm passing that scene object to the class responsible for drawing stuff on the screen.
The idea is to go through the list and to use function overload to draw the different type of objects on the list, but since the list only contains objects of the type Entity I can't really use the function overload since it only works with the child classes
I'm looking for a code similar to this one
void Painter::draw(Scene* scene) {
std::list<Entity*> drawables = scene->getDrawables();
for (auto it = drawables.begin(); it != drawables.end(); it++) {
draw(*it); //Should apply the correct overload
}
}
This code obviously doesn't work since I dont have any draw() function that takes an entity type.
I could always ask for the entity type to do a case to case, but that defeats the purpose of having an overloaded function and breaks the "tell, don't ask" principle.
I'm probably doing something terribly wrong, but I don't really know how to proceed that's why I'm asking the question, I would like to know what's the right approach to solve this problem while respecting the OOP principles, posibilities are wide open, everything is on the table in terms of changing my code.
Thanks in advance
|
You can use the Visitor pattern to solve this problem. This pattern is delegating the function call to the object itself, so you don't need to use the type of the object to call the correct function.
Here is how you can implement it:
void Painter::draw(Scene* scene) {
std::list<Entity*> drawables = scene->getDrawables();
for (auto it = drawables.begin(); it != drawables.end(); it++) {
(*it)->accept(this); // call virtual function
}
}
// in Entity class
void Entity::accept(Painter* painter) {
painter->draw(this);
}
// in entityType1 class
void entityType1::accept(Painter* painter) {
painter->draw(this);
}
// etc...
More advanced implementation of the visitor pattern can be found here: Implementing the visitor pattern using C++ Templates
|
74,513,805
| 74,513,888
|
If allocators are stateless in C++, why are functions not used to allocate memory instead?
|
The default std::allocator class is stateless in C++. This means any instance of an std::allocator can deallocate memory allocated by another std::allocator instance. What is then the point of having instances of allocators to allocate memory?
For instance, why is memory allocated like this:
allocator<T> alloc, alloc2;
T* buffer = alloc.allocate(42);
alloc2.deallocate(buffer);
When functions could easily do that same job:
T* buffer = allocate(42);
deallocate(buffer);
|
The default allocator is stateless, but other allocators may not be. However all allocators should share the same interface.
You are not supposed to use std::allocator directly as in your example. You can just use new and delete for direct allocation/deallocation.
You use std::allocator indirectly for generic allocator-aware types, such as containers, that should be agnostic to how the memory they use is allcoated. They usually have a template parameter for the allocator type satisfying the Allocator requirements/interface and std::allocator is typically the default argument for this template parameter.
And even in these cases you should use the allocator through std::allocator_traits, not by directly calling member functions of the allocator type, since many of them are defaulted through std::allocator_traits.
|
74,514,084
| 74,518,801
|
How to convert C++17's "if constexpr(std::is_literal_type<T>::value)" to C++11 SFINAE code?
|
Currently, I have this templated function in my codebase, which works pretty well in C++17:
/** This function returns a reference to a read-only, default-constructed
* static singleton object of type T.
*/
template <typename T> const T & GetDefaultObjectForType()
{
if constexpr (std::is_literal_type<T>::value)
{
static constexpr T _defaultObject = T();
return _defaultObject;
}
else
{
static const T _defaultObject;
return _defaultObject;
}
}
The function has two problems, though:
It uses if constexpr, which means it won't compile under C++11 or C++14.
It uses std::is_literal_type, which is deprecated in C++17 and removed in C++20.
To avoid these problems, I'd like to rewrite this functionality to use the classic C++11-compatible SFINAE approach instead. The desired behavior is that for types that are constexpr-constructible (e.g. int, float, const char *), the constexpr method will be called, and for types that are not (e.g. std::string), the non-constexpr method will be called.
Here's what I've come up with so far (based on the example shown in this answer); it compiles, but it doesn't work as desired:
#include <string>
#include <type_traits>
namespace ugly_constexpr_sfinae_details
{
template<int> struct sfinae_true : std::true_type{};
template<class T> sfinae_true<(T::T(), 0)> is_constexpr(int);
template<class> std::false_type is_constexpr(...);
template<class T> struct has_constexpr_f : decltype(is_constexpr<T>(0)){};
// constexpr version
template<typename T, typename std::enable_if<true == has_constexpr_f<T>::value, T>::type* = nullptr> const T & GetDefaultObjectForType()
{
printf("constexpr method called!\n");
static constexpr T _defaultObject = T();
return _defaultObject;
}
// non-constexpr version
template<typename T, typename std::enable_if<false == has_constexpr_f<T>::value, T>::type* = nullptr> const T & GetDefaultObjectForType()
{
printf("const method called!\n");
static const T _defaultObject = T();
return _defaultObject;
}
}
/** Returns a read-only reference to a default-constructed singleton object of the given type */
template<typename T> const T & GetDefaultObjectForType()
{
return ugly_constexpr_sfinae_details::GetDefaultObjectForType<T>();
}
int main(int, char **)
{
const int & defaultInt = GetDefaultObjectForType<int>(); // should call the constexpr function in the namespace
const float & defaultFloat = GetDefaultObjectForType<float>(); // should call the constexpr function in the namespace
const std::string & defaultString = GetDefaultObjectForType<std::string>(); // should call the non-constexpr function in the namespace
return 0;
}
When I run the program above, here is the output I see it print to stdout:
$ ./a.out
const method called!
const method called!
const method called!
... but the output I would like it to emit is this:
$ ./a.out
constexpr method called!
constexpr method called!
const method called!
Can anyone point out what I'm doing wrong? (I apologize if it's something obvious; SFINAE logic is not a concept that comes naturally to me :/ )
|
As @Igor Tandetnik mentions in comments, static const T _defaultObject{}; works in both cases and performs compile-time initialization when possible. There's no need for constexpr.
N3337 [basic.start.init]:
Constant initialization is performed:
[...]
if an object with static or thread storage duration is initialized by a constructor call, if the constructor is a constexpr constructor, if all constructor arguments are constant expressions (including conversions), and if, after function invocation substitution ([dcl.constexpr]), every constructor call and full-expression in the mem-initializers and in the brace-or-equal-initializers for non-static data members is a constant expression;
if an object with static or thread storage duration is not initialized by a constructor call and if every full-expression that appears in its initializer is a constant expression.
|
74,514,368
| 74,514,459
|
Why auto cannot be used to define an implicitly deleted constructor
|
I have this small snippet (compiled with g++) where I have defined a move constructor:
#include <iostream>
using namespace std;
class A {
public:
A() = delete;
A(int value) : value(value) {}
void operator=(const auto &other) = delete;
~A() { cout << "Destructor called..." << endl; }
A(const auto &other) {
cout << "Copy constructor called..." << endl;
value = other.value;
}
A(const A &&other) {
cout << "Move constructor called..." << endl;
value = other.value;
}
private:
int value;
};
int main() {
A p1(2);
A p2(p1);
return 0;
}
The problem is that I'm getting main.cpp:27:10: error: use of deleted function 'constexpr A::A(const A&)'
From what I understand, there is a compiler convention to implicitly delete any copy operations when a move constructor is defined. They will have to be explicitly defined if the user needs them.
However, I attempt to define a copy constructor using auto as the argument. If the constructor signature is A(const A &other) the program runs fine.
Since auto will be resolved to A, what is the reason for which the compiler still deems that particular constructor deleted?
|
Since auto will be resolved to A, what is the reason for which the compiler still deems that particular constructor deleted?
Because A::A(const auto &) cannot be a copy constructor as when auto is used in the parameter of a function, that function declaration/definition is actually for a function template. Basically A::A(const auto&) is a templated constructor. But according to class.copy.ctor a templated constructor cannot be a copy constructor.
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).
(emphasis mine)
And since you've defined a move constructor A::A(const A&&), the synthesized copy ctor A::A(const A&) is implicitly deleted. But note that the implicitly deleted copy ctor A::A(const A&) takes part in overload resolution and is still a better match than the templated constructor A::A(const auto&). Thus, the copy ctor is chosen but since it is deleted(implicitly) we get the mentioned error.
|
74,514,375
| 74,514,517
|
Returning a static cast to a pointer doesn't return a pointer C++
|
In an "Entity" class, there is a function that takes in a component typename as an argument, and should return a pointer to that component, if found in the component array. Instead it just returns a copy of the component, not a pointer, despite doing this:
return static_cast<T*>(ptr)
Here is the relevant code:
ECS.h (only the necessary code).
inline ComponentTypeId getUniqueComponentID() {
static ComponentTypeId lastID = 0u;
return lastID++;
}
template <typename T> inline ComponentTypeId getComponentTypeID() noexcept {
static_assert(std::is_base_of<Component, T>::value, "Failed at getComponentTypeID/static_assert() --> ECS/ECS.h");
static const ComponentTypeId typeID = getUniqueComponentID();
return typeID;
}
// Base "Component" class
class Component {
// Code
};
// Base "Entity" class
class Entity {
private:
ComponentArray compArr;
ComponentBitset compBitset;
std::vector<std::unique_ptr<Component>> components;
bool active = true;
public:
Entity() {}
virtual ~Entity() {}
template<typename T> bool hasComponent() const {
// Returns the bitset (bool value)
return compBitset[getComponentTypeID<T>()];
}
template<typename T> T& getComponent() const {
// Returns pointer to component
return *static_cast<T*>(compArr[getComponentTypeID<T>()]);
}
void update() {
// Goes through all the components (for this entity) calls their update method
for(auto &c : components) c->update();
}
void draw() {
// Goes through all the components (for this entity) calls their draw method
for(auto &c : components) c->draw();
}
inline bool isActive() {return active;}
void destroy() {active = false;}
};
|
Turns out I was returning a reference instead of a pointer in the getComponent() function.
template<typename T> T& getComponent() const {
// Returns pointer to component
return *static_cast<T*>(compArr[getComponentTypeID<T>()]);
}
// Needs to be
template<typename T> T* getComponent() const {
// Returns pointer to component
return static_cast<T*>(compArr[getComponentTypeID<T>()]);
}
|
74,514,777
| 74,515,495
|
C++ CString format with %f, double number became very big value
|
I am maintaining C++ project but i am not family with C++.
I am facing an issue, we use CString to convert a double value to String by
double Dose;
CString Dose2;
if(Dose>0)
{
Dose2.Format("%f",Dose);
}else{
Dose2.Format("0");
}
When I set break point after format %f line of code, the value before and after totally different.
Can you explain why this problem occurred? Some time the string value is correct, sometime not correct.
Before
After
|
I tried to write Dose value to file before format string, it also had big value.
FILE *fpversion;
fpversion = fopen("doserate.txt", "a");
fprintf(fpversion, "%f", Dose);
fclose(fpversion);
I take a look at source code set Dose value in another dialog.
if(m_MapDlg.GetSafeHwnd()!=NULL)
{
m_MapDlg.Dose=Result;
}
I tried to make function to set Dose value as
void CMapDlg::SetDose(double dose) {
this->Dose = dose;
}
And replace
m_MapDlg.Dose=Result;
by
m_MapDlg.SetDose(Result);
The Dose value got corrected value.
I shared my solution for whom concerned.
Thank @Jonathan Leffler for your suggestion.
|
74,514,843
| 74,521,423
|
Is concept a variant of SFINAE
|
SFINAE is a technology that permits invalid expressions and/or types in the immediate context of a templated function while the concept seems to have the same effect since we are only permitted to use expressions and types(in requires-expression) in the constraint-expression of the concept-definition, and the constraint-expression is true if all expressions and/or types are valid, and false otherwise. It appears to me that concept cannot do anything that exceeds what SFINAE can do, the same is true the other way around.
Is my understanding right? If it is not, what is the case in which we can only by using the concept, or by using SFINAE but using the other way would result in an error? If there does not exist such a scene, is the concept merely a graceful/modern way of using the technology SFINAE(i.e. they are essentially equivalent)?
Update:
IMO, the only difference is, certain expressions and types we want to check are dispersed in the declaration for SFINAE, by contrast, certain expressions and types we want to check are collected in the constraint-expression of the single concept-definition and use the declared concept in the declaration. Their effect essentially relies on invalid expressions and types.
|
They are not equivalent. Concepts can appear in more places and are partially ordered by subsumption. Some examples:
1. Concept subsumption may be used to rank overloads. With SFINAE, this is an error:
template <typename T>
auto overload(T) -> std::enable_if_t<std::is_copy_constructible_v<T>>;
template <typename T>
auto overload(T) -> std::enable_if_t<std::is_move_constructible_v<T>>;
void test() {
overload(1); // error: ambiguous
}
With concepts, this works:
void overload(std::copy_constructible auto);
void overload(std::move_constructible auto);
void test() {
overload(1);
}
2. Similarly, concept subsumption may be used to rank partial specializations.
3. Concepts are allowed on non-template member functions, so they can constrain special member functions.
Since a copy constructor is not a template, SFINAE never applies. When one needs conditional behavior before concepts (e.g. trivial copy constructor if the template argument of the class template is itself trivial), one had to conditionally introduce different base classes.
4. Concepts can constrain deduction.
One can statically assert that a type returned satisfies your requirements without asserting the precise type.
std::integral auto i = 1;
5. Concepts can be used in abbreviated function templates.
void f(std::integral auto);
|
74,515,060
| 74,515,135
|
visibility of a class data member in a nested class?
|
AFAIK, data member of enclosing class are also visible in nested class.
struct A {
struct B {
int arr[n]; // how come n is not visible here, but it is visible in next statement.
int x = n;
};
static const int n = 5;
};
see live demo here
|
how come n is not visible here, but it is visible in next statement.
Because int x = n; is a complete class context while int arr[n]; is not. This can be understood from class.mem which states:
6) A complete-class context of a class is a:
6.4) default member initializer
within the member-specification of the class.
[ Note: A complete-class context of a nested class is also a complete-class context of any enclosing class, if the nested class is defined within the member-specification of the enclosing class.
— end note
]
7) A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing } of the class-specifier. The class is regarded as complete within its complete-class contexts; otherwise it is regarded as incomplete within its own class member-specification.
(emphasis mine)
Note that the n inside int arr[n]; is part of the type of the array but the above quoted statement doesn't allow n to be used as part of a type of a non-static data member and hence the error. For the same reason, we will get the same error if we wrote:
struct A {
struct B {
int x = n;
//----------------------v--------->same error as before
std::array<int, n> arr;
};
static constexpr int n = 5;
};
|
74,515,480
| 74,520,688
|
Vulkan storage buffer vs image sampler
|
I am currently building an application in vulkan where I will be sampling a lot of data from a buffer. I will be using as much storage as possible, but sampling speed is also important. My data is in the form of a 2D array of 32 bit integers. I can either upload it as a texture and use a texture sampler for it, or as a storage buffer. I read that storage buffers are generally slow, so I was considering using the image sampler to read my data in a fragment shader. I would have to disable mipmapping and filtering, and convert UV coordinates to array indices, but if it's faster I think it might be worth it.
My question is, would it generally be worth it to store my data in an image sampler, or should I do the obvious and use a storage buffer? What are the pros/cons of each approach?
|
Guarantees about performance do not exist.
But Vulkan API tries not to decieve you. The obvious way is likely the right way.
If you want to sample then sample. If you want to do raw access then obviously do raw access. Generally, you should not be forcefully trying to put a square in a round hole.
|
74,516,708
| 74,516,760
|
Passing objects of different derived class as a parameter to a function that expects base object of class
|
I have a base class Device and inherited class InputDevice. In class XYZ I have a function XYZ::setDevice(int num, Device device) that expects object Device as parameter. When I call the function setDevice() with parameter that is sublclass of Device (InputDevice) it gets converted to Device and I can't access the derived functions of derived class afterwards.
So if I want to call the function of "device" in function setDevice() it calls function of Device instead of overriden function in class InputDevice.
What am I doing wrong?
void XYZ::setDevice(int num, Device device) {
printf("%s\n", typeid(device).name()); //this prints "Device"
this->devices[num] = device;
}
XYZ::XYZ() {
printf("%s\n", typeid(InputDevice(cin)).name()); //this prints "InputDevice"
setDevice(STANDARD_INPUT_DEVICE, InputDevice(cin));
printf("%s\n", typeid(devices[0]).name());
}
|
I don't see the full code, but instead of storing objects, you should store pointers. Your devices array should be vector or array of Device pointers.
Here's a fully working example.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Device {
public:
virtual string getName() const {
return string("Device");
}
};
class InputDevice : public Device {
public:
string getName() const override{
return string("InputDevice");
}
};
class XYZ {
Device* devices[10];
public:
void setDevice(int num, Device *device)
{
devices[num] = device;
cout << "Name : " << device->getName();
}
};
int main()
{
Device* dev1 = new Device();
Device* dev2 = new Device();
InputDevice* dev3 = new InputDevice();
XYZ xyz;
xyz.setDevice(0, dev1);
xyz.setDevice(1, dev2);
xyz.setDevice(2, dev3);
}
|
74,517,642
| 74,518,599
|
use promise multiple times
|
I am trying to signal a function on a seperate thread using a std::promise
class MyClass {
std::promise<void> exitSignal;
std::thread monitorThread;
}
void MyClass::start() {
exitSignal = std::promise<void>();
std::future<void> futureObj = exitSignal.get_future();
monitorThread = std::thread(&MyClass::monitorFunction, this, std::move(futureObj));
}
void MyClass::stop() {
exitSignal.set_value();
if (monitorThread.joinable()) {
monitorThread.join();
}
}
void MyClass::monitorFunction(std::future<void> futureObj) {
while (futureObj.wait_for(std::chrono::seconds(1)) == std::future_status::timeout) {
// do stuff
}
}
It works well until I try to call start for a second time. Then I get an error
std::future_error: Promise already satisfied
How come? I refresh the promise every time I start and the future seems valid...
|
I am going to echo the comment by @Homer512 and suggest that you are calling stop() twice. I made a small test using your code:
#include <future>
#include <thread>
#include <iostream>
#include <chrono>
struct MyClass
{
std::promise<void> exitSignal;
std::thread monitorThread;
void start();
void stop();
void monitorFunction(std::future<void> futureObj);
};
void MyClass::start()
{
exitSignal = std::promise<void>();
std::future<void> futureObj = exitSignal.get_future();
monitorThread = std::thread(&MyClass::monitorFunction, this, std::move(futureObj));
}
void MyClass::stop()
{
exitSignal.set_value();
if (monitorThread.joinable())
{
monitorThread.join();
}
}
void MyClass::monitorFunction(std::future<void> futureObj)
{
while (futureObj.wait_for(std::chrono::seconds(1)) == std::future_status::timeout)
{
std::cout << "Bla\n";
}
}
int main()
{
MyClass myc;
std::cout << "Start 1\n";
myc.start();
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Stop 1\n";
myc.stop();
// myc.stop(); // <- Boom!
std::cout << "Wait\n";
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Start 2\n";
myc.start();
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Stop 2\n";
myc.stop();
}
When I run this as is (second stop commented out), it runs with no issues:
Start 1
Bla
Bla
Stop 1
Wait
Start 2
Bla
Bla
Stop 2
But if the second stop is put in, then it is hit by an exception:
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: Promise already satisfied
Aborted
|
74,517,701
| 74,548,823
|
PhysX Overlap Scene/Geometric Query for Capsules
|
I am trying to do a scene query using Capsule colliders and for some reason the overlap function I had returns true even though in the PVD, the capsule are definitely not colliding (they are quite close together though). This is weird because my OnTrigger/onContact functions were called correctly only after an actual collision which means that I set my PxGeometry right but for some reason my overlap() calls independently from onTrigger/onContact.
Here is an extract of my code:
for (auto& collider2 : actor2->m_colliders)
{
bool isOverlapping = physx::PxGeometryQuery::overlap(collider->GetPhysXShape()->getGeometry().any(), actor1->GetPhysXActor().getGlobalPose(), collider2->GetPhysXShape()->getGeometry().any(), actor2->GetPhysXActor().getGlobalPose());
if (isOverlapping)
return true;
}
I have tried using both scene and geometric overlap queries but for some reason, there is a strange offset for only my capsule colliders (box, sphere works fine). It isn't that big of an issue as the strange offset is quite small but I do not want it register as colliding when 2 colliders are not really colliding.
|
I discovered the issue, turns out, the overlap queries do not consider the local transform of the PxShape, thus I solved it using:
physx::PxGeometryQuery::overlap(collider->GetPhysXShape()->getGeometry().any(), actor1->GetPhysXActor().getGlobalPose() * collider->GetPhysXShape()->getLocalPose(), collider2->GetPhysXShape()->getGeometry().any(), actor2->GetPhysXActor().getGlobalPose());
|
74,518,289
| 74,518,325
|
C++ pointer arithmetic for linked lists
|
I am just starting out self-learning C++, and as a toy problem, I am trying to do the following - given a linked list, I want to store all nodes that are even into a new list, and return this new list. For context, I come from a Python background.
I have the following program -
#include <iostream>
using namespace std;
struct node
{
unsigned val;
struct node *next;
};
node *even_nodes(node **root)
{
node *new_list_head = NULL;
node *new_list_runner = NULL;
node *runner = *root;
while (runner != NULL)
{
if (new_list_head != NULL){
printf("OUTSIDE LOOP new_list_head.val = %d\n", new_list_head->val);
}
if (runner->val % 2 == 0)
{
cout << runner->val << endl;
node new_node = {.val = runner->val, .next = NULL};
if (new_list_head == NULL)
{
printf("new_list_head is NULL!\n");
new_list_head = &new_node;
new_list_runner = &new_node;
printf("after allocation. new_list_head.val = %d\n", new_list_head->val);
}
else
{
printf("new_list_head is NOT NULL! new_list_head.val = %d\n", new_list_head->val);
new_list_runner->next = &new_node;
new_list_runner = new_list_runner->next;
printf("after allocation. new_list_head.val = %d\n", new_list_head->val);
}
}
runner = runner->next;
}
printf("new_list_head val = %d\n", new_list_head->val);
return new_list_head;
};
void add_data(node **root, int new_data)
{
node *new_node = (node *)malloc(sizeof(node *));
new_node->val = new_data;
new_node->next = (*root);
(*root) = new_node;
}
void print_list(node *root)
{
node *head = root;
while (head != NULL)
{
printf("%d -> ", head->val);
head = head->next;
}
printf("END\n");
};
int main()
{
node *head = NULL;
add_data(&head, 19);
add_data(&head, 18);
add_data(&head, 3);
add_data(&head, 4);
add_data(&head, 1);
printf("Initial list:\n");
print_list(head);
node *new_list = even_nodes(&head);
printf("New list of even numbers: \n");
print_list(new_list);
return 0;
}
The output is the following -
Initial list:
1 -> 4 -> 3 -> 18 -> 19 -> END
4
new_list_head is NULL!
after allocation. new_list_head.val = 4
OUTSIDE LOOP new_list_head.val = 4
OUTSIDE LOOP new_list_head.val = 4
18
new_list_head is NOT NULL! new_list_head.val = 18
after allocation. new_list_head.val = 18
OUTSIDE LOOP new_list_head.val = 18
new_list_head val = 18
New list of even numbers:
[1] segmentation fault
I do not understand why the new_list_head also changes with the new_list_runner? Why is my new_list_head pointing to the last element of the new list, and not the first?
Also, why is there a seg fault error? In the print_list method, why is the guard
while (head != NULL)
not working?
Any help will be appreciated!
|
You cannot do dynamic allocation by taking addresses of local variables. When the scope exits the local variable is destroyed and you are left with a pointer to an object which does not exist (known as a dangling pointer).
Your code has this problem here
node new_node = {.val = runner->val, .next = NULL}; // local variable
if (new_list_head == NULL)
{
new_list_head = &new_node; // BAD
new_list_runner = &new_node; // BAD
}
else
{
new_list_runner->next = &new_node; // BAD
new_list_runner = new_list_runner->next;
}
instead you should use new to allocate new nodes, Objects created with new do not get destroyed until you delete them.
node* new_node = new node{runner->val, NULL};
if (new_list_head == NULL)
{
new_list_head = new_node;
new_list_runner = new_node;
}
else
{
new_list_runner->next = new_node;
new_list_runner = new_list_runner->next;
}
|
74,518,307
| 74,518,551
|
Why q is not equal to 1.0?
|
I'm a neophyte with c++. I wrote this code but the result for q have to be 1.0, but the code give me, changing the variable's order when I recall function "intercetta", for example -34, 0, 9.75. Why?
#include <iostream>
using namespace std;
float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) {
return m = ((y2 - y1) / (x2 - x1));
}
float intercetta(float m, float x1, float y1, float q) {
return q = y1 - m * x1;
}
int main() {
float x1, x2, y1, y2, m=0, q=0;
x1 = 3.5;
x2 = 6.5;
y1 = 9.75;
y2 = 17.25;
cout << "m= " << coefficienteAngolare(x1, x2, y1, y2, m) << endl;
cout << "q= " << intercetta(x1, y1, m, q) << endl;
}
|
This function
float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) {
return m = ((y2 - y1) / (x2 - x1));
}
has parameters passed by value. It means that it receives copies of the parameters you give. Whatever you do inside the function, cannot alter the parameters passed to it in main().
If you really want to modify m, you have to pass it by reference
float coefficienteAngolare(float x1, float x2, float y1, float y2, float& m) {
return m = ((y2 - y1) / (x2 - x1));
}
But then, if you modify m, why do you need to return it?
Most probably you either want to not return anything and just store the result in m
void coefficienteAngolare(float x1, float x2, float y1, float y2, float& m) {
m = ((y2 - y1) / (x2 - x1));
}
//....
// in main()
coefficienteAngolare(x1, x2, y1, y2, m);
cout << "m= " << m << endl;
Or you want to return the resulting value, without passing a variable to store it.
float coefficienteAngolare(float x1, float x2, float y1, float y2) {
return ((y2 - y1) / (x2 - x1));
}
//....
// in main()
m = coefficienteAngolare(x1, x2, y1, y2);
cout << "m= " << m << endl;
Along the same line you have to modify intercetta.
Please notice that the order of the parameters is relevant. The compiler cannot guess that the q variable in main() should be the same as the q variable in intercetta, they belong to different scopes.
|
74,518,420
| 74,531,052
|
Exception in Concurrency task.then.wait affects further call of ::ShellExecuteEx()
|
Following logic is implemented to open a file by a "filename.extension" in a C++ application using managed-C++:
try
{
CoInitialize(nullptr);
auto task = Concurrency::create_task(Windows::Storage::StorageFile::GetFileFromPathAsync(filePath));
// an excpetion is thrown in the next line
Concurrency::task_status status = task.then([&](Windows::Storage::StorageFile^ file){
if (file != nullptr)
{
concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file));
launchFileOperation.then([&](bool success)
{
if (!success)
return 0;
}).wait();
}
}).wait();
}
catch (...)
{
CoUninitialize(); // an exeption is catched
return 0;
}
Since the above code throws an exception, we go further to an alternative file open approach via ::ShellExecuteEx
SHELLEXECUTEINFO exec_info = {0};
exec_info.cbSize = sizeof exec_info;
exec_info.fMask = SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_DOENVSUBST;
exec_info.fMask &= ~SEE_MASK_NOASYNC;
exec_info.lpVerb = "open";
exec_info.lpFile = full_path_str;
exec_info.nShow = SW_SHOW;
bool result_b = ::ShellExecuteEx(&exec_info) ? true : false;
The ::ShellExecuteEx fails and ends up in Microsofts ppltasks.h
_REPORT_PPLTASK_UNOBSERVED_EXCEPTION();.
::ShellExecuteEx works correctly if the managed-C++ Concurrency::create_task approach is removed.
Why does Concurrency::create_task affect the further call of ::ShellExecuteEx?
This issue appears only in release build.
|
Adding try/catch-blocks to the innermost .wait()-block solved the issue
try {
concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file));
launchFileOperation.then([&](bool success) {
// logic
}).wait();
}
catch (concurrency::invalid_operation& ex)
{
...
}
catch (concurrency::task_canceled& ex)
{
...
}
|
74,519,025
| 74,519,305
|
c++20 implement an interface for a vector
|
I'd like to create a class with can use any Vector.
Possible types could be std::vector, boost::vector, etl::vector.
All used vector types must implement std::vector member functions.
I'd like to create a concept which validates that the used vector type implements all std::vector member functions
So far I have come up with
#include <concepts>
#include <vector>
template < typename T , typename Element_T>
concept IVector_T = requires(T vec, Element_T elem)
{
{vec.push_back(elem) } -> std::same_as<void>; ///< Add an element to the vector
{vec.back()} ->std::convertible_to<Element_T>;
};
template<typename Element_T, IVector_T Vector_T>
class TestVector
{
public:
void push_back(const Element_T& elem)
{
myVec.push_back(elem);
}
Element_T& back()
{
//return ref to last element
return myVec.back();
}
private:
Vector_T<Element_T> myVec;
};
However I'm getting a compiler error
<source>(27): error C2059: syntax error: '<'
<source>(28): note: see reference to class template instantiation 'TestVector<Element_T,Vector_T>' being compiled
<source>(27): error C2238: unexpected token(s) preceding ';'
<source>(19): error C3861: 'myVec': identifier not found
<source>(19): error C2065: 'myVec': undeclared identifier
I'm using latest MSVC17 on Win 10, however this should also run an Linux and Mac
I have a godbolt link for you to easily reproduce this issue
https://godbolt.org/z/54zac583j
Thx for your help guys :)
Edit:
As noted in the comments pop_into() is not std. => replaced it with back().
To clearify: Some vectors like boost::vector and std::vector need 1 template argument (i.e. std::vector)
Other vector types like etl::vector may need more template arguments. etl::vector for example is a preallocated vector therefore we need a max vector size (i.e. etl::vector<int, 100>)
|
You should do template instantiation of Vector_T like this.
template<typename Element_T, IVector_T<Element_T> Vector_T>
class TestVector
{
...
private:
Vector_T myVec;
};
|
74,519,642
| 74,519,715
|
how do I create an undordered map containing functions?
|
I have functions that are working with the following struct:
struct stm {
size_t op;
std::string st_out;
}
and I have declared the signature of the unordered map that will save the references:
std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)> instruction_actions;
I wrote the functions of which I want to save the reference:
bool write(stm&s, const uint64_t item) {
std::cout << "op: " << s.st_out << std::endl;
return true;
}
but how should I add them in the map?
|
First things first, your function write is missing a return statement.
how should I add them in the map?
There are multiple ways of doing this as shown below:
std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)>>
instruction_actions{{5, write}};
Or using std::map::insert
instruction_actions.insert({5, write});
Or using std::map::operator[]:
instruction_actions[5] = write;
Working demo
|
74,520,572
| 74,520,689
|
how does the compiler write values to the second value of the pair in this construct?
|
map<int,int> a;
pair<std::map<int,int>::iterator ,bool> f;
f=(a.insert({0,0}));
cout<<f.second;
why is it outputting 1?
it always outputs 1 for any values in the pair
|
It's because the bool f.second tells you if insert inserted the pair<int,int> into the map. 1 means that it did insert it.
bools are normally printed as either 0 (false) or 1 (true). You can use the I/O manipulator std::boolalpha to make it print true or false instead.
it always outputs 1 for any values in the pair
No. If you try to insert a pair with a Key value that already exists in the map<int,int> it will return a pair<std::map<int,int>::iterator ,bool> where the bool is false and the iterator will point at the existing element in the map<int,int>.
|
74,521,146
| 74,521,949
|
Is writing in parallel to the values of a map thread safe?
|
AFAIK if two unsynchronized threads access the same memory location and at least one tries to write to it, you get a data race.
This being said, in the following code sample, what is "the same memory location":
std::unordered_map<int, std::string> map{{0, {}}, {1, {}}, {2, {}}, {3, {}},
{4, {}}, {5, {}}, {6, {}}, {7, {}}};
std::for_each(std::execution::par, map.begin(), map.end(),
[](auto &kvp) { kvp.second = std::to_string(kvp.first); });
Is it the map, meaning that parallel execution introduces a data race, or, as I suspect, is it each value in kvp, meaning that the code is thread safe?
|
Most concurrent, non-const accesses to standard library objects do constitute data races. However, accesses through iterators are given an explicit carveout:
Operations on iterators obtained by calling a standard library container or string member function may access the underlying container, but shall not modify it.
Since they are non-modifying accesses to the object, they don't by themselves cause a data race.
Since no other parallel operations in your code are performing write accesses to the container object itself (just the contents of it), there are no data races inherent to your code. What you do inside the function could induce data races, but that would be through manipulation of the objects in the container, not the nature of the container itself.
|
74,522,105
| 74,522,269
|
Static priority queue of pointers in c++
|
I have a class foo, and inside the class, I need a static priority queue bar that holds pointers to some number of foo objects, and the foo object also has a private member buzz that will hold the weight of the objects when compared.
So far, I have tried the following:
class foo{
private:
// some stuff
int buzz;
public:
// some more stuffs
static bool compare (const foo* l, const foo* r){
return l->buzz < r->buzz;
}
static std::priority_queue<foo*, std::vector<foo*>, foo::compare> bar;
};
But I get this error in clang:
template argument for template type parameter must be a type
I read this and this but could not get my head around how to do it or what i was doing wrong.
|
As you can see in the std::priority_queue documentation,
the 3rd template argument Compare is:
A Compare type providing a strict weak ordering.
A function pointer (like you used) cannot be used for the compare type.
One way to supply a compare type is via a class with opertor() (preferably a const one):
#include <queue>
class foo {
private:
int buzz;
public:
// Our compare type:
struct Compare
{
bool operator()(const foo* l, const foo* r) const
{ return l->buzz < r->buzz; }
};
//--------------------------------------------------vvvvvvvvvvvv-----
static std::priority_queue<foo*, std::vector<foo*>, foo::Compare> bar;
};
|
74,522,160
| 74,522,668
|
Why does the compiler require return type in the following lambdas
|
I am implementing recursive DFS as a lambda passing itself as a parameter. If I comment out the logic that checks if the current node has no children, I get build errors saying that the lambda is used before type deduction.
#include <vector>
int main() {
int root;
std::vector<std::vector<int>> graph;
// ...
// build the tree as adjacency list starting from root
// ...
auto dfs = [&graph](auto self, auto u) {
// if (empty(graph[u])) {
// return;
// }
for (auto v : graph[u]) {
self(self, v);
}
};
dfs(dfs, root);
}
/usr/bin/g++-10 -std=c++20 -Wall -Wextra -Wshadow -pedantic -fdiagnostics-color=always -g -o main main.cpp
main.cpp: In instantiation of ‘main()::<lambda(auto:44, auto:45)> [with auto:44 = main()::<lambda(auto:44, auto:45)>; auto:45 = int]’:
main.cpp:66:18: required from here
main.cpp:63:17: error: use of ‘main()::<lambda(auto:44, auto:45)> [with auto:44 = main()::<lambda(auto:44, auto:45)>; auto:45 = int]’ before deduction of ‘auto’
63 | self(self, v);
| ~~~~^~~~~~~~~
However, once I have that check-if-empty logic back, the code compiles with no issues.
Is that because in the latter case, the return statement gives the compiler a hint that the lambda returns void and therefore, its type is known at the time self(self, v) is called?
More broadly, where can I read and learn more about how compilers process lambda definitions to avoid relying on their error messages and know when it's necessary to declare the return type and when it's not?
|
Yes, the return; statement is exactly what tells the compiler the return type of the lambda. In this example, the statement says the function return void.
Without knowing the return type, the call to self(self, v); is ill-formed, since you're effectively relying on auto being deduced without giving the compiler a way of figuring it out.
The language explicitly mentions this example in dcl.spec.auto#general-11:
If a variable or function with an undeduced placeholder type is named by an expression ([basic.def.odr]), the program is ill-formed. Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.
(emphasis mine), and provides a simpler version of the problem in your code:
auto sum(int i) {
if (i == 1)
return i; // sum's return type is int
else
return sum(i-1)+i; // OK, sum's return type has been deduced
}
|
74,522,843
| 74,544,232
|
AsyncWait in Lely CANopen is not behaving asynchronously?
|
I'm trying to perform some tasks using fibers in the Lely CANopen stack. However, I either don't understand the model, or something is broken. What I would like to do is run multiple tasks at different rates.
An example based on the tutorial here:
class MyDriver : public canopen::FiberDriver {
public:
using FiberDriver::FiberDriver;
private:
// Configure device
void OnConfig(std::function<void(std::error_code ec)> res) noexcept override {
try {
// Do some SDO configuration
// Schedule tasks
Defer(&MyDriver::TaskA, this);
Defer(&MyDriver::TaskB, this);
// Return no error
res({});
} catch (canopen::SdoError& e) {
res(e.code());
}
}
void TaskA() noexcept {
while (true) {
// Do some processing
std::cout << "Hello from task A" << std::endl;
// Wait
Wait(AsyncWait(duration(std::chrono::milliseconds(1000))));
}
}
void TaskB() noexcept {
while (true) {
// Do some processing
std::cout << "Hello from task B" << std::endl;
// Wait
Wait(AsyncWait(duration(std::chrono::milliseconds(500))));
}
}
};
int main() {
// A lot of set up omitted for clarity
// Create context, event loop, CAN channel, etc.
// Create master
canopen::AsyncMaster master(timer, chan, "../config/master.dcf", "", 1);
// Start NMT service by pretending to get a reset command
master.Reset();
// Create a driver for CAN device
MyDriver driver(exec, master, 2);
// Run the event loop
loop.run();
return 0;
}
I would expect this to print something like:
Hello from task A
Hello from task B
Hello from task B
Hello from task A
Hello from task B
Hello from task B
...
However, I get output like this:
Hello from task A
Hello from task A
Hello from task A
Hello from task A
...
So it seems that Wait(AsyncWait(d)) is not actually yielding execution. What am I doing wrong?
|
(Answered here, but repeated below to make it easy to find.)
That's because you're scheduling the tasks with Defer() instead of Post().
Defer() submits a task to a "strand" executor. A strand guarantees that tasks submitted to it never run concurrently. So it will only execute task B once task A finishes. This can be useful in multithreaded applications (such as when using LoopDriver) to prevent race conditions without having to use mutexes or other explicit synchronization mechanisms.
Defer() is probably not the most obvious name for this. It originally comes from the executors in Boost.Asio and is meant to indicate that the submitted task will not run concurrently with the task that does the submitting (OnConfig() in your example). In this case, it means "defer task A until OnConfig() is complete and defer task B until task A is complete".
|
74,522,871
| 74,523,221
|
Efficient way to repeatedly generate same random number in C++?
|
I am working on a secure LoRa transmission, where I need to generate the same pseudo-random number on the transmitter and the receiver (it would be part of the encryption algorithm) based on an input counter. So this function should give the same output for a given input, just like a hashing algorithm.
As an example here is what I mean, but as you can see the computation gets longer based on the input:
unsigned int f(unsigned int input) {
srand(1234);
for (unsigned int i = 0; i < input; i++) {
rand();
}
return rand();
}
Is there a more efficient way to do this? I am on an ESP32 microcontroller.
edit. Thanks for all the answers. I could have accomplished what I was trying to do with a CRC function, but as per your recommendation I ended up ditching this approach and used a standard encryption algorithm instead.
|
You should not use rand for this purpose as it is implementation-defined which presents a couple of issues for your use-case:
It may produce different numbers on different targets
It is not guaranteed to be cryptographically secure
What you describe is a cryptographic hash function. There are many libraries available which offer these. Generally there is a trade-off between security and performance, so you will have to select one.
it would be part of the encryption algorithm
If the application must be truly secure, I would recommend using an existing algorithm such as AES rather than trying to write your own, as it appears you are trying to do here. Again, these are available as libraries, some of which are small and suitable for embedded systems such as tiny-AES.
|
74,522,923
| 74,523,122
|
Why does declaring a copy constructor not delete the copy assignment operator and vice versa?
|
So if I've got a class and declare a copy assignment operator in it, obviously I want some special behavior when copying. I would expect the language to try to help me out by implicitly deleting the copy constructor until I explicitly bring it back, so as to avoid unintended different behavior when doing type instance = type() as opposed to already_existing_instance = type().
It's recommended anyway that you explicitly declare both copy constructor and copy assignment operator when trying to declare one of them, precisely because C++ doesn't delete the other and causes you a headache.
An example of where I find this annoying is when deleting the copy assignment operator. If I want to quickly make a class non-copyable, I would expect deleting the copy assignment operator does the trick, but I have to explicitly delete the copy constructor as well.
My question is why does the compiler do this? Who thought this was a good idea? All it does is create a needless obstacle for the programmer or am I missing something?
P.S. This behavior doesn't present itself when doing the same thing with move constructors/assignment operators, why make a distinction between copy and move in this case?
|
Them not being deleted is deprecated.
E.g. Clang 15 with -Wextra, given
struct A
{
A() {}
A(const A &) {}
};
int main()
{
A a, b;
a = b;
}
spits
<source>:4:5: warning: definition of implicit copy assignment operator for 'A' is deprecated because it has a user-provided copy constructor [-Wdeprecated-copy-with-user-provided-copy]
A(const A &) {}
^
<source>:10:7: note: in implicit copy assignment operator for 'A' first required here
a = b;
^
Similarly,
struct A
{
A() {}
A &operator=(const A &) {return *this;}
};
int main()
{
A a, b(a);
}
gives
<source>:4:8: warning: definition of implicit copy constructor for 'A' is deprecated because it has a user-provided copy assignment operator [-Wdeprecated-copy-with-user-provided-copy]
A &operator=(const A &) {return *this;}
^
<source>:9:10: note: in implicit copy constructor for 'A' first required here
A a, b(a);
^
|
74,523,636
| 74,526,573
|
inline const(expr) variables vs functions returning static const(expr) variables - Is there any reason to prefer one or the other approach?
|
Several times I've seen code like this in a header
IMPORTOREXPORT std::string const& foo();
IMPORTOREXPORT std::string const& bar();
IMPORTOREXPORT std::string const& baz();
and the following corresponding code in a cpp file
std::string const& foo() {
static std::string const s{"foo"};
return s;
}
std::string const& bar() {
static std::string const s{"bar"};
return s;
}
std::string const& baz() {
static std::string const s{"baz"};
return s;
}
where IMPORTOREXPORT is a macro to deal with linkage, so yes, I'm talking of a multi-module code, where different translation units are compiled independently and then linked together.
Is there any reason why I should prefer the above solution to simply have these in the header?
inline std::string const foo = "foo";
inline std::string const bar = "bar";
inline std::string const baz = "baz";
I found this related question, but I'm not sure it entirely answers this. For instance, the accepted answer contains this (part of a) statement
for different modules would be different addresses
but this doesn't seem to be inline with what read on cppreference (emphasis mine):
An inline function or variable (since C++17) with external linkage (e.g. not declared static) has the following additional properties:
It has the same address in every translation unit.
|
As you note, the inline variable approach guarantees that the variable has a unique address, just like the static local variable approach.
The inline approach is certainly easier to write, but:
It doesn't work on pre-C++17 compilers.
It's more expensive to build:
Every translation unit that odr-uses the inline variable must emit a weak definition for that variable, and the linker must discard all but one of these symbols so that the variable has a unique address.
If the variable has dynamic initialization, then every translation unit that odr-uses it also needs to emit a piece of code to dynamically initialize it, and again, the linker must discard all but one copy.
Every translation unit that includes the header that defines the inline variable is forced to have a compile-time dependency on the header that defines the variable's type, even if there are no uses of the variable besides the definition itself.
|
74,523,718
| 74,523,855
|
No matching function when calling the function
|
I am a newbie to C++ and I wanted to know what should I do. I need to write a program where the user will be filling the 2d array. I need to program to show the 2d array in the form of matrix and do some other things, like counting elements that are not 0. But I am stuck. I can't call functions in main(), because there is no matching call error. I suppose this is because of the array initializing, but I saw people on the internet who does
int arr[row][col];
Code:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
// for filling the 2d array
void fillTheMatrix(int **arr, int row, int col) {
cout << "Please, enter here the elements you want to use for the matrix A:\n";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << "a[" << i << "][" << j << "] = ";
cin >> arr[i][j];
}
}
}
// for viewing this s2d array as matrix
void theMatrixView(int **arr, int row, int col) {
cout << "The matrix A\n";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << setw(3) << arr[i][j] << "\t";
}
cout << endl;
}
}
int main() {
int row;
int col;
cout << "Please, enter the number of rows of the matrix A: " << endl;
cin >> row;
cout << "Please, enter the number of columns of the matrix A: " << endl;
cin >> col;
int arr[row][col];
// TASK 1
fillTheMatrix(arr, row, col); // No matching function for call to 'fillTheMatrix'
theMatrixView(arr, row, col); // // No matching function for call to 'theMatrixView'
return 0;
}
Can you help me fixing this problem? I would be glad to have any recommendations to refactor code.
|
As suggested in the comments better way is to use std::vector, however if you really want to use raw C++ arrays, to have a correctly type passed in, you need to declare a pointer to pointers to dynamically allocated memory:
int** arr = new int*[row];
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
arr[i] = new int[col];
}
fillTheMatrix(arr, row, col);
theMatrixView(arr, row, col);
for (int i = 0; i < row; ++i)
{
delete[] arr[i];
}
|
74,523,742
| 74,530,121
|
Parsing path in JSON
|
I'm trying to pass a JSON object containing a path from my frontend (Node) to the backend (C++) using RapidJSON, like so:
#include <iostream>
#include "rapidjson/document.h"
int main() {
const char* json1 = "{\"path\":\"C:\\test.file\"}"; // works
const char* json2 = "{\"path\":\"C:\\fol der\\test.file\"}"; // works
const char* json3 = "{\"path\":\"C:\\fol der\\Test.file\"}"; // ERROR!
const char* json4 = "{\"path\":\"C:\\few dol\\test.file\"}"; // ERROR!
const char* json5 = "{\"path\":\"C:\\folder\\anotherOne\\test.file\"}"; // ERROR!
rapidjson::Document d;
d.Parse(json3); // works using json1 or json2
assert(d.HasMember("path"));
std::string pathString = d["path"].GetString();
return 0;
}
The first two strings work. However, I can't get any longer paths to work and even capitalization is giving me trouble (the only difference between json2 and json3 is the "T").
How do I properly pass and parse paths (Windows and maybe Linux)?
Thank you in advance!
Edit: I just tried nlohman's JSON library and have the same problem.
How do I pass paths in JSON???
|
If you print your json variables you will get the following (C++ interprets the escape characters):
json1: {"path":"C:\test.file"}
json2: {"path":"C:\fol der\test.file"}
json3: {"path":"C:\fol der\Test.file"}
json4: {"path":"C:\few dol\test.file"}
json5: {"path":"C:\folder\anotherOne\test.file"}
Now you can test these json in any tool like https://jsonlint.com/, you will get errors. the reason for error is that the strings represented by "path" in the case of json3 and json5 are not valid string because of invalid escape characters present in them.
Here is the list of escape sequences per string:
json1 has \t
json2 has \f and \t
json3 has \f and \T
json4 has \f and \t
json5 has \f and \a and \t
Among all of these escape characters, \T and \a are invalid and hence json3 and json5 are invalid as well.
Now, if you want to parse it properly, then one simple way could be using four backslashes \\\\ for example:
const char* json3 = "{\"path\":\"C:\\\\fol der\\\\Test.file\"}";
which will be equivalent to C:\fol der\Test.file
|
74,524,029
| 74,524,098
|
What is "%rdi" in assembly and where does it take its value?
|
Intrigued by this post about UB, I've decided to start reading Jonathan Bartlett's Programming from the Ground Up in order to play around with C++ UB and see what the assembly looks like.
But while trying out things I've found something strange in a pretty simple case. Consider this code
int foo(int * p) {
int y = 7;
if (p)
++y;
return y;
}
Its assembly is
foo(int*):
cmpq $1, %rdi
movl $7, %eax
sbbl $-1, %eax
ret
(Compiler Explorer)
Now I understand that movl $7, %eax is putting the value 7 into the eax register, then one that's gonna be returned to the caller by ret. So I also understant that sbbl $-1, %eax is the instruction taking care of subtracting -1 from the content of eax and storing the result into eax itself, and that this instruction happens only if p is not null. Which leads me to assume that sbbl is making use of a hidden boolean value computed by earlier lines. The only candidate, even by the name, is cmpq $1, %rdi.
But what is that doing? From the aforementioned book I've understood that functions arguments are passed from caller to callee via the stack: the caller pushes arguments on the stack, and the callee extracts those values. But there's no such a thing here.
So is %rdi what? The register of the first (and in this case only) arugument of the function? Why is it so? Are there other registers referring to further arguments? How many? And besides, what is a good source of information on this topic?
|
%rdi is reference to the register rdi.
In this case, it appears that the compiler is passing the first parameter in a register instead of on the stack.
Parameter passing is basically a convention: as long as the compiler is consistent in how it passes parameters, a compiler can switch from passing parameters one way (e.g., always on the stack) to another (some in registers) almost any time it sees fit (new version of the compiler, or even just passing some switch on the compiler command line).
Depending on when and where you look, it's pretty routine for a single compiler to support multiple calling conventions. For example, for quite a while Microsoft's 32-bit compiler supported four: cdecl, fastcall, stdcall, and thiscall (the last used only for C++ member functions). Of those, cdecl and stdcall were purely stack based, and fastcall and thiscall both used registers for some arguments.
|
74,524,080
| 74,524,511
|
C++ Convert Unix time (nanoseconds) to readable datetime in local timezone
|
I have a Unix time (nanoseconds since epoch) and I would like to go back and forth between this and a readable string in a specifiable timezone (using TZ strings), with nanoseconds preserved. I am using C++17 but willing to migrate to C++20 if it would make things much easier.
Example:
uint64_t unix_time = 1669058870115719258;
std::string datetime = convert_unix_to_datetime(unix_time, "America/Detroit");
std::cout << datetime << "\n";
std::cout << convert_datetime_to_unix_time(datetime) << "\n";
Desired output:
2021-11-21 14:27:50.115719258
1669058870115719258
Apologies if this is a basic question--I have searched around the site and tried to implement solutions but keep getting confused by different C++ versions, whether the datetime is in UTC or local timezone, different types like chrono::time_point vs. time_t etc. Hoping to find a simple solution here.
|
Using C++20, this is very easy. Using C++11/14/17 it is harder but doable with a free, open-source time zone library.
Here is what it looks like with C++20:
#include <chrono>
#include <cstdint>
#include <format>
#include <iostream>
#include <sstream>
#include <string>
std::string
convert_unix_to_datetime(std::uint64_t unix_time, std::string const& tz)
{
using namespace std;
using namespace chrono;
sys_time<nanoseconds> tp{nanoseconds{unix_time}};
return format("{:%F %T} ", zoned_time{tz, tp}) + tz;
}
The first line converts the uint64_t, first into a nanoseconds chrono::duration, and then into a nanoseconds-precision chrono::time_point based on system_clock. chrono::system_clock uses Unix Time as its measure: http://eel.is/c++draft/time.clock.system#overview-1
The second line creates a chrono::zoned_time from the time zone name, and the sys_time timepoint. A zoned_time is a simple pairing of these two objects from which you can extract a local time. When formatted, it is the local time that is printed. Here I've used "%F %T" as the format which will output with the syntax: YYYY-MM-DD HH:MM:SS.fffffffff. Many formatting flags are available..
Finally I've added the time zone name to the timestamp. This is done so that the parsing function can recover the time zone name as it is not passed in as one of the parameters to convert_datetime_to_unix_time.
std::uint64_t
convert_datetime_to_unix_time(std::string s)
{
using namespace std;
using namespace chrono;
istringstream in{std::move(s)};
in.exceptions(ios::failbit);
std::string tz_name;
local_time<nanoseconds> tp;
in >> parse("%F %T %Z", tp, tz_name);
zoned_time zt{tz_name, tp};
return zt.get_sys_time().time_since_epoch().count();
}
The first line moves the string into a istringstream as the parsing must use a stream. I've set the stream to throw an exception if there is a syntax error in the input s. If you would rather check for failbit manually, remove the line that sets failbit to throw an exception.
Next arguments are default constructed which will be parsed into:
std::string tz_name;
local_time<nanoseconds> tp;
Here it is important to use the type local_time as opposed to sys_time because it is the local time that was formatted out. Use of the local_time type informs the library how to apply the UTC offset under the zoned_time constructor after parse.
The parse can pick up the time zone name with the %Z flag, and will place it in the last argument to parse.
Construct the zoned_time with the time zone and time point.
Finally, the sys_time (Unix Time) can be extracted from the zoned_time with the .get_sys_time() member function. This will have precision nanoseconds since the input local_time has precision nanoseconds. The underlying integral count of nanoseconds is extracted with .time_since_epoch().count().
Using your example driver, this will output:
2022-11-21 14:27:50.115719258 America/Detroit
1669058870115719258
As I write this, only the latest MSVC tools fully implement this part of C++20.
If you need to use the free, open-source time zone library, a few minor changes are needed:
Add using namespace date; to each function.
Change the format string from "{:%F %T} " to "%F %T ".
Add #include "date/tz.h".
Compile and link to tz.cpp using the instructions at https://howardhinnant.github.io/date/tz.html#Installation
This will by default download a copy of the IANA time zone database, though there are ways to avoid that on non-Windows platforms (described in the installation instructions).
|
74,524,472
| 74,526,685
|
C++ Function Template is not deducing Eigen vector sizes
|
I have written a function
template <int N>
bool checkColinear(const std::array<Eigen::Vector<double, N>, 3>& points) noexcept;
which takes three N-D points and returns true if they are collinear within a certain tolerance. Everything works if I call the function and explicitly specify N:
std::array<Eigen::Vector3d, 3> points = {Eigen::Vector3d{0.0, 1.0, 0.0},
Eigen::Vector3d{0.0, 3.0, 0.0},
Eigen::Vector3d{0.0, 2.0, 0.0}};
auto result = checkCollinear<3>(points);
But if I try to call the function without specifying N explicitly the compiler reports an error:
auto result = checkCollinear(points);
The error I get is "error C2672: 'checkCollinear': no matching overloaded function found".
Is it possible for the compiler to deduce the template argument in this case? I am using MSVC143 (VS2022) and using C++20.
I have already tried to explicitly change the Eigen::Vector3d to Eigen::Vector<double, 3> and Eigen::Matrix<double, 3, 1>, but that neither of those fix it. I have also tried making the type of N a std::size_t too, but that doesn't help either.
|
As mentioned in the comments, this is likely a bug. A workaround is to spell out the full type name for Vector<double, N> as:
Matrix<double, N, 1, 0, N, 1>
^ ^ ^ ^
col row/col major max rol max col
And your function signature will become:
template <int N>
bool checkCollinear(const std::array<Eigen::Matrix<double, N, 1, 0, N, 1>, 3>& points) noexcept;
Demo
|
74,524,907
| 74,525,011
|
Why can't i search for vs code extensions?
|
So i have fresh Manjaro installation and only software i have is ws code and some bloatware.
But when i want to search for extesions like C/C++ it find somethink but not what i need.
This is what i get
my output
what i want
I find something like product.json but i cannot find its location or anything.
I tried reinstalling... nothing.
Also I can't find it as .vsix file so i don't know what to do.
Search for solution on internet.
|
What you're using is Code - OSS and not VSCode; they're built from almost the same source except for the telemetry and the part that handles the marketplace (the latter being a proprietary component by Microsoft). As far as I know it's not possible to have VSCode's Marketplace working for another editor. Code - OSS relies on Open VSX Registry.
References:
Differences between Code OSS and Visual Studio Code
https://github.com/microsoft/vscode/wiki/Differences-between-the-repository-and-Visual-Studio-Code
|
74,525,865
| 74,526,081
|
Which is correct for sizing a vector
|
Hi I am just starting to learn cpp and I have two examples of getting the size of a vector in the for statements both seem to work but which is right and why? sizeof(vector) or vector.size()?
Thanks
Brian
void print_vector(vector<string> vector_to_print){
cout << "\nCars vector = ";
for(int i = 0; i < sizeof(vector_to_print); i++){
cout << vector_to_print[i];
(i < vector_to_print.size()-1) ? (cout << ", ") : (cout << endl); // ? the tenrary operator is an if statement (?) do one outcome (:) or the other
}
}
void print_vector(vector <string> vector_to_print){
cout << "\nVector contents = ";
for( int i = 0; i < (vector_to_print.size()); i++ ){
cout << vector_to_print[i];
(i < (vector_to_print.size()-1)) ? (cout << ", ") : (cout << endl);
}
}
Both seem to work I try to rewrite the same code from memory each day for a week to help me learn it and I couldn't quite get the sizeof() to work so I googled it and the example I found used .size() but when I got home and checked what I did yesterday I had used sizeof().
|
std::vector<std::string> is a container class, which stores an array of std::strings plus other values to assist with manipulation of the array and providing information about the state of the stored array. When you call sizeof(vector_to_print) you are simply getting the size of the container class not the amount of elements in the array that it is storing.
run the following code to prove it to yourself:
std::vector<std::string> vec{"hello","world"};
std::cout << sizeof(vec) << '\n';
vec.push_back("!");
std::cout << sizeof(vec);
the size of the underlying array is changing it goes from 2 elements to 3, but not only does the sizeof(vec) not change, it is always = to 24!
sizeof(vec) must be the same each time (24 bytes on my machine) because sizeof is a compile time constant, because the size of a type must be a compile time constant.
The latter (.size()) is the only valid method
|
74,526,201
| 74,526,329
|
Defaulted template argument in std::optional constructor
|
std::optional has the following constructor:
template < class U = T >
constexpr optional( U&& value );
The question here is: why template parameter U is defaulted to type T? What happens if simply change constructor to following:
template < class U /* = T */>
constexpr optional( U&& value );
|
It's so if you give it an initializer list (which doesn't have a type, so can't infer a type for U), it will initialize a T temporary.
For example:
std::optional<std::vector<int>> opt({1, 2, 3});
// No type deduced for `U`, defaults to `std::vector<int>`
struct X {
int a, b;
};
std::optional<X> opt({.a = 1, .b = 2});
// Same here
|
74,526,571
| 74,540,764
|
How do I disable Manifest in VisualStudio using C++?
|
I'd like to have the UI elements switch to the Windows 95 UI for my program. But I am not sure how to disable Manifest in Visual Studio. Setting generate Manifest to off in the Linker doesn't seem to do it. Still new to this, not sure what the process is to shut it off.
|
Snippet SetWindowTheme(hWnd, L"", L""); SetThemeAppProperties(0); will disable visual style and use classic ui.
|
74,527,011
| 74,540,560
|
How to use Vector Class Library for AVX vectorization together with the openmp #pragma omp parallel for reduction?
|
I'm using OpenMP to parallelize the loop, that is internally using AVX-512 with Agner Fog's VCL Vector Class Library.
Here is the code:
double HarmonicSeries(const unsigned long long int N) {
unsigned long long int i;
Vec8d divV(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Vec8d sumV(0.0);
const Vec8d addV(8.0);
const Vec8d oneV(1.0);
#pragma omp parallel for reduction(+:sumV,divV)
for(i=0; i<N; ++i) {
sumV += oneV / divV;
divV += addV;
}
return horizontal_add(sumV);
}
When trying to compile the code above, I'm getting
g++ -Wall -Wextra -O3 -g -I include -fopenmp -m64 -mavx2 -mfma -std=c++17 -o harmonic_series harmonic_series.cpp
harmonic_series.cpp:87:40: error: user defined reduction not found for ‘sumV’
87 | #pragma omp parallel for reduction(+:sumV,divV)
| ^~~~
harmonic_series.cpp:87:45: error: user defined reduction not found for ‘divV’
87 | #pragma omp parallel for reduction(+:sumV,divV)
Any hints on how to solve this and provide the user-defined reduction for the Vec8d class? It's simply the plus operator which is defined by the VCL class, but I cannot find any example how to code this.
Thanks a lot for any help!
|
Here is the final solution. It's using automatic reduction and avoids u64->fp conversion by computing divV = startdivV + i * addV only in the first iteration of each loop and then using divV += addV for all other iterations. Runtime to compute the sum of first 9.6e10 elements is {real 9s, user 1m46s} with 12 threads on Intel Core i7-10850H CPU - it's the same as for the manual reduction.
double HarmonicSeries(const unsigned long long int N) {
unsigned long long int i;
Vec8d divV(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Vec8d sumV(0.0);
const Vec8d addV(8.0);
const Vec8d oneV(1.0);
const Vec8d startdivV = divV;
bool first_loop = true;
#pragma omp declare reduction( + : Vec8d : omp_out = omp_out + omp_in ) initializer (omp_priv=omp_orig)
//It's important to mark "first_loop" variable as firstprivate so that each private copy gets initialized.
#pragma omp parallel for firstprivate(first_loop) lastprivate(divV) reduction(+:sumV)
for(i=0; i<N; ++i) {
if (first_loop) {
divV = startdivV + i * addV;
first_loop = false;
} else {
divV += addV;
}
sumV += oneV / divV;
}
return horizontal_add(sumV);
}
|
74,527,151
| 74,534,935
|
How to connect signal from a different class?
|
// splashscreen.h
class SplashScreen : public QMainWindow
{
Q_OBJECT
public:
explicit SplashScreen(QWidget *parent = nullptr);
~SplashScreen();
QTimer *mtimer;
public slots:
void update();
private:
Ui_SplashScreen *ui;
};
// app.h
#include "splashscreen.h"
class App: public QMainWindow
{
Q_OBJECT
public:
App(QWidget *parent = nullptr);
~App();
SplashScreen s;
private:
Ui::AppClass ui;
};
// app.cpp
App::App(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect();
s.centralWidget()->setGraphicsEffect(eff);
QPropertyAnimation* a = new QPropertyAnimation(eff, "opacity");
a->setDuration(2000);
a->setStartValue(0);
a->setEndValue(1);
a->start(QPropertyAnimation::DeleteWhenStopped);
s.show();
connect(a, &QAbstractAnimation::finished, this, [this]
{
auto *timer = new QTimer();
this->s.mtimer = timer;
QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));
timer->start(100);
});
}
I'm getting an error at this line: QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));
no instance of overloaded function "QObject::connect" matches the argument list
I think it's mismatching the class signal, as this passed to the lambda refers to App not SplashScreen.
When i try to pass s (SplashScreen) to the lambda:
connect(a, &QAbstractAnimation::finished, this, [s]
{ ... }
I get an error: App::s is not a variable.
I'm confused, what is the proper way to connect in this case?
|
In App class, s is an instance, not a pointer to an instance. Function connect needs pointer, not reference.
Use these syntax should help:
QObject::connect(timer, &QTimer::timeout, &s, &SplashScreen::update);
|
74,527,726
| 74,527,780
|
Deduce types of template-defined base class constructor parameters
|
I have a derived class, Wrapper, that inherits from a template-defined base class. I'd like to configure Wrapper so that if the base class has constructor parameters, Wrapper's constructor also includes the base class's constructor params so that it can forward them to the base class constructor:
struct Base1 {
Base1(int) {}
};
struct Base2 {
Base2(std::string) {}
};
// I'd like variadic template param `Args` to be deduced to a parameter
// pack matching a valid constructor for type T, if available.
template <typename T, typename... Args>
struct Wrapper : public T {
Wrapper(int, Args&&... v) : T(std::forward<Args>(v)...) {}
};
int main() {
auto wrapper = Wrapper<Base1>(1, 2);
}
This example fails because the compiler is not deducing anything for Args, and so the resulting error is:
no matching function for call to ‘Wrapper<Base1>::Wrapper(int, int)’:
candidate: ‘Wrapper<T, Args>::Wrapper(int, Args&& ...) [with T = Base1; Args = {}]’
candidate expects 1 argument, 2 provided
Is it possible to force the compiler to deduce the type(s) for the variadic template parameter Args, based on the deduced value of T and the parameters provided to Wrapper at construction?
|
Instead of having Args as a template parameter pack of the class template, you can make the constructor a template as shown below:
//------------------v--------------->removed Args from here
template <typename T >
struct Wrapper : public T {
//--vvvvvvvvvvvvvvvvvvvvvvvvvv----->made this a templated ctor
template<typename... Args>
Wrapper(int, Args&&... v) : T(std::forward<Args>(v)...) {}
};
int main() {
auto wrapper = Wrapper<Base1>(1, 2); //works now
}
Working demo
|
74,527,986
| 74,529,336
|
Is casting an address by reinterpret_cast an undefined behaviour?
|
I want to find a way to encapsulate a header-only 3rd party library without exposing its header files. In our other projects, we encapsulate by using void*: in the implementation, we allocate memory and assign to it, and cast to pointer of its original type when we use it. But this time, the encapsulated class is used frequently, hence dynamic allocation is unacceptable. Here is another solution I'm currently considering.
Assuming that the encapsulated class need N bytes, I will make a char array member variable of size N in the wrapper class, named data, for instance. In the implementation, when I try to assign an object of the encapsulated class to the wrapper, or forward a function call, I need to cast &data to the pointer of encapsulated class by reinterpret_cast, firstly. The char array is completely a placeholder. To make this clear, here is a sample code.
#include <iostream>
struct Inner {
void print() const {
std::cout << "Inner::print()\n";
}
};
struct Wrapper;
Inner* addressof(Wrapper&);
const Inner* addressof(const Wrapper&);
struct Wrapper {
Wrapper() {
Inner* ptr = addressof(*this);
*ptr = Inner();
}
void run() const {
addressof(*this)->print();
}
char data[1];
};
Inner* addressof(Wrapper& w) {
return reinterpret_cast<Inner*>(&(w.data));
}
const Inner* addressof(const Wrapper& w) {
return reinterpret_cast<const Inner*>(&(w.data));
}
int main() {
Wrapper wrp;
wrp.run();
}
From the view of memory, this seems make sense. But I'm sure if this is some kind of undefined behaviour.
Additionally, I want to know if there is a list of undefined behaviour. Seems like cppreference doesn't contain such thing and C++ standard specfication is really hard to understand.
|
What you have here is undefined behavior. The reason is when you reinterpret an object to a different type, you are not allowed to modify it until you cast it back to the original type.
In your code, you originally have the data as a char[1]. Later, in your constructor, you reinterpret_cast &data as Inner*. At this point, modifying the its value will produce undefined behavior.
What you could do however, is to first create a Inner object, then cast it and store it in the char[1]. Later you can cast the char[1] back to the Inner object and do anything with the Inner object as wanted.
So now your constructor would look like this:
Wrapper() {
Inner inner;
char* ptr = reinterpret_cast<char*>(&inner);
std::memcpy(data, ptr, 1);
}
However, if you did it like this, then you don't even need the reinterpret_cast there as you can directly memcpy from inner:
Wrapper() {
Inner inner;
std::memcpy(data, &inner, 1);
}
Better, if you have C++20, then you can and should use std::bit_cast, along with std::byte(C++17) and std::array(C++11):
struct Wrapper {
Wrapper()
: data(std::bit_cast<decltype(data)>(Inner{}))
{}
void run() const {
std::bit_cast<Inner>(data).print();
}
std::array<std::byte, 1> data;
};
Demo: https://godbolt.org/z/MaT5sasaT
|
74,528,017
| 74,529,354
|
C++ , cout line in function effects the result, function does not work without cout line
|
I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
|
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
|
74,528,094
| 74,528,751
|
Find the number of subarrays whose average is greater than or equal K
|
Given an array of integers, find the number of subarrays whose average is greater than or equal to K.
Constraints:
1 <= N <= 10^5
-10^9 <= A[i] <= 10^9
My solution:
If A[i] is prefix sum upto ith index in the array then
(A[j] - A[i]) / (j - i) >= K
(A[j] - A[i]) >= K * (j - i)
(A[j] - K * j) >= (A[i] - K * i) <- Let's call this expression e
So expression e tells me If I hash the running sum till the current index along with -K * current index, then all I need to search is the number of elements less expression e.
What I was mapping in hash table after processing ith index
A[i] - K * i, where A[i] is running sum of the array
But I was struggling to find a data structure which can give me number of elements less than a given element in Constant time or may be O(logN) time.
Data structures that I explored to solve this problem -
Segment trees but the constraints were too high for segment tree since we need to allocate the max size.
Multi-sets (C++) and do the upper_bound (binary search) which would give me iterator, and to get the elements less than X I can find the difference between upper_bound and begin() iterator but runtime of this could go upto O(N) and then my overall runtime goes to O(N^2).
Note: Whatever I've mentioned in the question, considering C++ as primary language since I was solving problem in C++.
Would love to hear your thoughts/suggestions.
|
You're already setting A[i] = A[i] - (K * i), so you need to find all i,j such that
A[j] - A[i] >= 0, or
A[j] >= A[i]
Assuming j>i, the number of valid pairs should just be the total number pairs minus the inversion count. You won't require any special data structure that way (an array would suffice), and inversion count calculation can be done in O(NlogN).
|
74,528,301
| 74,528,997
|
Why C-style Arrays performance in O3 is less than no optimization on Quick Bench?
|
Base on C-style Arrays vs std::vector using std::vector::at, std::vector::operator[], and iterators
I run the following benchmarks.
no optimization
https://quick-bench.com/q/LjybujMGImpATTjbWePzcb6xyck
O3
https://quick-bench.com/q/u5hnSy90ZRgJ-CQ75b1c1a_3BuY
From here, vectors definitely perform better in O3.
However, C-style Array is slower with -O3 than -O0
C-style (no opt) : about 2500
C-style (O3) : about 3000
I don't know what factors lead to this result. Maybe it's because the compiler is c++14?
(I'm not asking about std::vector relative to plain arrays, I'm just asking about plain arrays with/without optimization.)
|
Your -O0 code wasn't faster in an absolute sense, just as a ratio against an empty
for (auto _ : state) {} loop.
That also gets slower when optimization is disabled, because the state iterator functions don't inline. Check the asm for your own functions, and instead of an outer-loop counter in %rbx like:
# outer loop of your -O3 version
sub $0x1,%rbx
jne 407f57 <BM_map_c_array(benchmark::State&)+0x37>
RBX was originally loaded from 0x10(%rdi), from the benchmark::State& state function arg.
You instead get state counter updates in memory, like the following, plus a bunch of convoluted code that materializes a boolean in a register and then tests it again.
# part of the outer loop of your -O0 version
12.50% mov -0x8060(%rbp),%rax
25.00% sub $0x1,%rax
12.50% mov %rax,-0x8060(%rbp)
There are high counts on those instructions because the call map_c_array didn't inline, so most of the CPU time wasn't actually spent in this function itself. But of the time that was, about half was on these instructions. In an empty loop, or one that called an empty function (I'm not sure which Quick Bench is doing), that would still be the case.
Quick Bench does this to try to normalize things for whatever hardware its cloud VM ends up running on, with whatever competing load. Click the "About Quick Bench" in the dropdown at the top right.
And see the label on the graph: CPU time / Noop time. (When they say "Noop", they don't mean a nop machine instruction, they mean in a C++ sense.)
An empty loop with a loop counter runs about 6x slower when compiled with optimization disabled (bottlenecked on store-to-load forwarding latency of the loop counter), so your -O0 code is "only" a bit less than 6x slower, not exactly 6x slower.
With a counter in a register, modern x86 CPUs can run loops at 1 cycle per iteration, like looptop: dec %ebx / jnz looptop. dec has one cycle latency, vs. subtract or dec on a memory location being about 6 cycles since it includes the store/reload. (https://agner.org/optimize/ and https://uops.info/. Also
The performance of two scan functions (benchmarked without optimization; my answer explains that they bottleneck on store-forwarding latency.)
Why does this difference in asm matter for performance (in an un-optimized ptr++ vs. ++ptr loop)?
Why does clang produce inefficient asm with -O0 (for this simple floating point sum)?
Adding a redundant assignment speeds up code when compiled without optimization (Intel Sandybridge-family store-forwarding has variable latency depending on how soon you try to reload).
With that bottleneck built-in to the baseline you're comparing against, it's normal that adding some array-access work inside a loop won't be as much slower as array access vs. an empty loop.
|
74,528,443
| 74,528,889
|
How to use cmake and vcpkg to import GLAD/GLFW3/ImGUI libraries on MacOS?
|
My goal is to write a simple, portable application using ImGUI. I also want a platform-agnostic build experience using cmake, and vcpkg to install dependencies. I got the program built and running on my Windows machine, but it's failing on my Macbook (macOS Monterey 12.6).
This is my vcpkg.json:
{
"name": "imguitest",
"version": "1.0",
"dependencies": [
"glad",
"glfw3",
{
"name": "imgui",
"features": [ "glfw-binding", "opengl3-binding" ]
}
]
}
This is my CMakeLists.txt:
cmake_minimum_required (VERSION 3.23)
project(ImGui-Test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
add_executable(${PROJECT_NAME}
src/main.cpp
)
find_package(glad CONFIG REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE glad::glad)
find_package(glfw3 CONFIG REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE glfw)
find_package(imgui CONFIG REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE imgui::imgui)
find_package(OpenGL REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE OpenGL::GL)
After running this:
# export VCPKG_DIR=/path/to/vcpkg/repo/
cmake -B ./build -S . "-DCMAKE_TOOLCHAIN_FILE=$VCPKG_DIR/scripts/buildsystems/vcpkg.cmake"
I get this error:
CMake Error at CMakeLists.txt:14 (find_package):
Could not find a package configuration file provided by "glad" with any of
the following names:
gladConfig.cmake
glad-config.cmake
Add the installation prefix of "glad" to CMAKE_PREFIX_PATH or set
"glad_DIR" to a directory containing one of the above files. If "glad"
provides a separate development package or SDK, be sure it has been
installed.
Do I have to manually install GLAD package myself and set the path? I thought vcpkg would handle that for me. Please let me know if I'm misunderstanding something, as I'm new to modern cmake and vcpkg.
|
This fixed it: brew install pkg-config
I got more descriptive error messages after I deleted the build folder. This error message was hidden when configuring cmake with vscode, but was visible when doing it through zsh terminal.
Building glfw3[core]:arm64-osx...
warning: -- Using community triplet arm64-osx. This triplet configuration is not guaranteed to succeed.
-- [COMMUNITY] Loading triplet configuration from: /Users/munta/Dev/vcpkg/triplets/community/arm64-osx.cmake
-- Downloading https://github.com/glfw/glfw/archive/7482de6071d21db77a7236155da44c172a7f6c9e.tar.gz -> glfw-glfw-7482de6071d21db77a7236155da44c172a7f6c9e.tar.gz...
-- Extracting source /Users/munta/Dev/vcpkg/downloads/glfw-glfw-7482de6071d21db77a7236155da44c172a7f6c9e.tar.gz
-- Using source at /Users/munta/Dev/vcpkg/buildtrees/glfw3/src/172a7f6c9e-7678776297.clean
GLFW3 currently requires the following libraries from the system package manager:
xinerama
xcursor
xorg
libglu1-mesa
pkg-config
These can be installed via brew install libxinerama-dev libxcursor-dev xorg-dev libglu1-mesa-dev pkg-config
-- Configuring arm64-osx
-- Building arm64-osx-dbg
-- Building arm64-osx-rel
-- Fixing pkgconfig file: /Users/munta/Dev/vcpkg/packages/glfw3_arm64-osx/lib/pkgconfig/glfw3.pc
CMake Error at scripts/cmake/vcpkg_find_acquire_program.cmake:619 (message):
Could not find pkg-config. Please install it via your package manager:
brew install pkg-config
Call Stack (most recent call first):
scripts/cmake/vcpkg_fixup_pkgconfig.cmake:151 (vcpkg_find_acquire_program)
ports/glfw3/portfile.cmake:43 (vcpkg_fixup_pkgconfig)
scripts/ports.cmake:147 (include)
|
74,528,554
| 74,528,640
|
Finding the average of a variable belonging to an object in a BST?
|
I am very new to cpp and am currently facing the following problem.
I have csv file filled with Person object class which I need to insert into my BST.
class Person{
string name;
string job;
int age;
}
I have successfully populated my BST with this Person object. I now need to calculate the average age of all the Persons in the BST (there is an appropriate getter method for the age).
I have the following as my inorder traversal (with function pointers)
template <class T>
void Bst<T>::InOrder(Node<T>* root, void(*InOrderPtr)(T &)) const
{
if (root->left != nullptr)
{
InOrder(root->left, *InOrderPtr);
}
InOrderPtr(root->GetData());
if (root->right != nullptr)
{
InOrder(root->right, *InOrderPtr);
}
}
template <class T>
void Bst<T>::InOrderTraversal(void (*InOrderPtr)(T&)) const
{
InOrder(this->root, *InOrderPtr);
}
However I am stuck in that I do not know how to proceed next to traverse and find the average of all the ages. Can someone direct me how to do so?
|
Make the second argument to the BST visitor not a function pointer but a templated argument:
template <typename T, typename Callback>
void Bst<T>::InOrder(Node<T>* root, Callback&& callback) const {
// ...
callback(root->getData());
// ...
}
template <typename T, typename Callback>
void Bst<T>::InOrderTraversal(Callback&& callback) const
{
InOrder(this->root, std::move(callback));
}
That will allow you to not only pass a function pointer if you like, but also pass a lambda function with state:
int sum = 0;
int num = 0;
bst->InOrderTraversal([&](Person const& person) {
sum += person.age;
num += 1;
});
auto const average = static_cast<float>(sum) / num;
|
74,528,719
| 74,529,674
|
Backgammon/Table game in Qt Creator, C++, how can I track the clicked buttons?
|
I'm trying to program Backgammon in Qt Creator using C++,
This is what I got until now, I created diverse Qgroupboxes for example grp_b1, here I have now 5 Buttons which are the black figures in the upper corner.
grid = new QGridLayout();
ui->grp_b1->setLayout(grid);
feld1=new QButtonGroup;
feld1_buttons[0]=ui->b1;
feld1_buttons[1]=ui->b2;
feld1_buttons[2]=ui->b3;
feld1_buttons[3]=ui->b4;
feld1_buttons[4]=ui->b5;
for(int i=0;i<5;i++)
{
feld1->addButton(feld1_buttons[i],i);
grid->addWidget(feld1_buttons[i]);
I want to ask for help to develop the game logic, I don't know how to track the clicked button.
So when I click on the button I get their id, but how could I know which field is actually being clicked? Because I have many fields, and I can only know which id inside each field is being clicked but not the field.
I would be very thankful for any help or suggestion.
|
You can call method sender() in your slot to get a pointer of call object. After that get pointer parent to get widget field.
Example:
QObject* obj = sender();
QObject* parent =obj ->parent();
And make static cast to widget
|
74,529,066
| 74,529,321
|
How to read the first byte of HAL_UART_Receive?
|
I'm trying to send a single char ("A") to my STM32 from my ESP32. I can see that the char goes through as I am receiving the char back on the ESP32 in the Arduino serial monitor but I can't seem to understand how to access it for using it to do something else on the STM32. Here is what I've been trying...
//STM32 Code:
uint8_t RxTx_1[100];
while (1)
{
/* USER CODE END WHILE */
HAL_UART_Receive(&huart1, (uint8_t*)RxTx_1, sizeof(RxTx_1), 100); // Receive comms from ESP32
if (RxTx_1[0] = "A"){
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); // Blink
HAL_Delay(1000);
}
HAL_Delay(1000);
HAL_UART_Transmit(&huart1, (uint8_t*)RxTx_1, sizeof(RxTx_1), 100);
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
I know its got to be something simple but I can't seem to find anything online about how to do it.
|
To expand on the comment from @πάντα ῥεῖ:
"A" is a string literal, with a type of const char[N]. This particular one is the string/array {'A', '\0'} (remember the terminating null-character). So if (RxTx_1[0] = "A") compares your Rx char to a pointer.
'A' is the character A with a char type, and if (RxTx_1[0] == 'A') does what you want.
|
74,529,584
| 74,543,844
|
Protobuf oneof has_field private
|
I have made a simple protobuf file to reproduce my problem:
syntax = "proto3";
package proto;
message Test {
uint32 test1 = 1;
oneof param {
uint32 test2 = 2;
bool test3 = 3;
}
}
When I generate the c++ code the oneof's has_param() member function is private. Is it normal ? How do I know if the oneof is set ?
By the way I tried with protobuf 3.12.4 and 3.21.9 and got the same result.
|
Refer to the documentation for Protobuf C++ generated code.
The generator creates a method param_case(), which returns enumeration type that identifies which field inside the oneof is present. If the oneof is empty, it returns PARAM_NOT_SET.
|
74,530,070
| 74,531,099
|
Seek Highest Column Value From Today (Postgres, C++, QT)
|
Edit: The below query doesn't work but the concept given in the answer still applies. Check here for how to fix the query sqlite IFNULL() in postgres
I have a table in Postgresql called 'transaction'. The primary key of this table is composite with (id, date), where id is an int and date is a timestamp. Every day, the first order starts at order #1. The next order that day would be #2, then #3, and so on until the next day with #1 again.
I'm not sure how I would change this SQL query to find the max transaction ID specifically from today then increment 1 to it.. or start again at 1 if there are no transactions today. So far the only thing I can do is just start at 1 if there are no transactions at all, or increment based on the highest ID across all dates.
/* Insert Transaction */
bool dbmanager::addTransaction(const int& custPhone=0, const int& totalCents=0, const qstr& items="",
const qstr& paymentType="", const int& tender=0, const int& change=0,
const int& cardNum=0, const int& cardExp=0, const int& cardCVV=0, QWidget* from=nullptr)
{
QSqlQuery q;
// TODO: This query increments the largest order number that exists across all dates. Make it so the order number is 1+ the max order number from today
q.prepare("insert into pos_schema.transaction values( (select ifnull(max(id), 0) + 1 from pos_schema.transaction), NOW(), "
":phone, :total_cents, :items, :payment_type, :tender, :change, :card_number, :card_exp, :card_cvv);");
q.bindValue(":phone",custPhone);
q.bindValue(":total_cents", totalCents);
q.bindValue(":items", items);
q.bindValue(":payment_type", paymentType);
q.bindValue(":tender", tender);
q.bindValue(":change", change);
QString cryptCardNum = crypt.encryptToString(qstr::number(cardNum));
QString cryptCardExp = crypt.encryptToString(qstr::number(cardExp));
QString cryptCardCVV = crypt.encryptToString(qstr::number(cardCVV));
q.bindValue(":card_number", cryptCardNum);
q.bindValue(":card_exp", cryptCardExp);
q.bindValue(":card_cvv", cryptCardCVV);
if (q.exec())
return true;
qDebug() << "Transaction Insertion Error:" << q.lastError().text();
displayError("Insertion", from, q);
return false;
}
|
You need to update your sub-select
select ifnull(max(id), 0) + 1 from pos_schema.transaction
to something like
SELECT
ifnull(max(id), 0) + 1
FROM pos_schema.transaction
WHERE
pos_schema.transactiondate.date::date = CURRENT_DATE
Please note that your field date should really be of type date instead of timestamp. Otherwise your primary key does not protect you from inserting two duplicate IDs for the same date if they have different timestamps.
|
74,530,809
| 74,531,322
|
Template that calls member function on argument
|
I have some code that creates several listeners. Thus I was thinking about adding a template that calls the notify on different types of listeners. However I am not sure how to call the member function (which all have different arguments) in a template. I am using C++17.
template <class T>
void notifyListeners(std::vector<T*> listeners, std::function<???> memfunc) {
// perhaps add a compile time check to see if memfunc exists
for (auto& listener : listeners) {
listener->memfunc();
}
}
For example I have two classes of listeners :
class IFooListener {
void Foo(int, double, std::string);
}
class IBarListener {
void Bar(std::string, std::string)
}
std::vector<IFooListeners*> fooListeners;
std::vector<IBarListeners*> barListeners;
I would like to be able to do something like this:
notifyListeners(fooListeners, &IFooListener::Foo, 1, 2.0, "Bla");
notifyListeners(barListeners, &IBarListener::Bar, "one", "two");
How can this be done?
|
template <class T, typename F, typename... Args>
void notifyListeners(std::vector<T*> listeners, F f, Args&&... args) {
for (auto& listener : listeners) {
(listener->*f)(std::forward<Args>(args)...);
}
}
Demo
|
74,532,771
| 74,534,804
|
C++ check input floats (-0.0f, +0.0f)
|
I am currently trying to build a program which prints an input float value to binary.
The first bit is 0 if positive or 1 if negative, but with an input value of e.g.: -0.0g my if statement always prints 1, also for a positive input. How would I check that correctly?
string sign = "sign: ";
if(value <= -0.0f)
sign.append("1\n");
else if (value >= 0.0f)
sign.append("0\n");
...
|
+0.0 and -0.0 have the same value, yet different signs.
value <= -0.0f is true for value as +0.0 and -0.0. @MSalters
To distinguish the sign, use std::signbit(). @john
if(std::signbit(value)) {
sign.append("1\n");
} else {
sign.append("0\n");
}
Note that signbit() also applies to infinities and NaN.
Even though std::signbit reports "Along with std::copysign, std::signbit is one of the only two portable ways to examine the sign of a NaN.", there may be others.
|
74,532,879
| 74,532,909
|
Stack problem c++. Error: ‘cin’ does not name a type
|
This stack program runs correctly for given array size arr[5] or arr[10].But when i take size as input from the user cin>>n it says "Error: ‘cin’ does not name a type."
Here is that code:
#include <iostream>
using namespace std;
class Stack
{
private:
int n;
cin>>n;
int arr[n];
int top=-1;
public:
rest of the code
So i tried to take a random input for size of array but got this error when used cin to take input. I have used namespace std but still got the error Error: ‘cin’ does not name a type.
It's my first time asking question in stack overflow so ask me if you need more clarification.
|
There are two problems with this class definition
class Stack
{
private:
int n;
cin>>n;
int arr[n];
int top=-1;
//...
The first one is that you may not use statements that are not declarations
cin>>n;
And the second one is that variable length arrays are not a standard C++ feature.
You could define the class for example the following way
class Stack
{
private:
int n;
int *arr;
int top=-1;
//...
public:
Stack( int n ) : n ( n < 1 ? 1 : n ), arr( new int[n] )
{
}
//...
|
74,532,913
| 74,561,679
|
What is the best way traversing an unordered_map with a starting from a random element in C++?
|
I have an unordered_map of 'n' elements. It has a some eligible elements. I want to write a function such that each time, a random eligible element is picked.
Can this be achieved in the following time complexity?
Best case: O(1)
Avg case: O(1)
Worst case: O(n)
Referring - retrieve random key element for std::map in c++, I have come up with the following solution.
#include <iostream>
#include <unordered_map>
#include <random>
using namespace std;
void select_random_best(const std::unordered_map<std::string, int>& umap, const int random_start)
{
cout << "Selected random number " << random_start << endl;
auto it = umap.begin();
std::advance(it, random_start);
for(int i = 0; i < umap.size(); i++, it++) {
if(it == umap.end())
it = umap.begin();
// Check if the selected element satisfies the eligibility criteria.
// For the sake of simplicity, I am taking the following example.
if(it->second % 3 == 0) {
cout << it->first << ", " <<
it->second << endl;
return;
}
// Element not found continue searching
}
}
int main()
{
srand(time(0));
unordered_map<string, int> umap;
// inserting values by using [] operator
umap["a"] = 6;
umap["b"] = 3;
umap["f"] = 9;
umap["c"] = 2;
umap["d"] = 1;
umap["e"] = 3;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(0, umap.size() - 1);
const int random_start = distrib(gen);
select_random_best(umap, distrib(gen));
// another iteration
select_random_best(umap, distrib(gen));
cout << "Full list :" << endl;
// Traversing an unordered map
for (auto x : umap)
cout << x.first << ", " <<
x.second << "\t";
}
Can someone suggest if the use of std::advance() here would lead to the avg case time comlexity of O(1)? Or is there a better way of doing this?
|
std::unordered_map has forward iterators, which do not allow random access. Refer to iterator on the documentation page of the container.
Assuming all elements are eligible, std::advance() will go through size/2 elements on average. Because you only accept eligible elements, you will go through more than that. If you know the probability of the eligibility, you can estimate the average elements searched.
To achieve O(1) in the std::advance() step, you must use a data type with random access iterators, such as std::vector. However, the next step does not have constant compexity. In the worst case, you will go through all ineligible elements (not considering the possibility of an infinite loop if there are no eligible ones). So this approach is still O(n) as whole.
For the best performance, you need two lists: std::vector with only eligible elements, used for finding a random element, and std::unordered_map for other things.
|
74,533,641
| 74,533,817
|
Global variables in a translation unit, will they be stored contiguous and can pointer arithmetic be done?
|
Say I have global variables defined in a TU such as:
extern const std::string s0{"s0"};
extern const std::string s1{"s11"};
extern const std::string s2{"s222"};
// etc...
And a function get_1 to get them depending on an index:
size_t get_1(size_t i)
{
switch (i)
{
case 0: return s0.size();
case 1: return s1.size();
case 2: return s2.size();
// etc...
}
}
And someone proposes replacing get_1 with get_2 with:
size_t get_2(size_t i)
{
return *(&s0 + i);
}
Are global variables defined next to each other in a translation unit like this guaranteed to be stored contiguously, and in the order defined?
Ie will &s1 == &s0 + 1 and &s2 == &s1 + 1 always be true?
Or can a compiler (does the standard allow a compiler to) place the variables s0 higher than s1 in memory ie. swap them?
Is it well defined behaviour to perform pointer arithmetic, like in get_2, over such variables? (that crucially aren't in the same sub-object or in an array etc., they're just globals like this)
Do rules about using relational operators on pointers from https://stackoverflow.com/a/9086675/8594193 apply to pointer arithmetic too? (Is the last comment on this answer about std::less and friends yielding a total order over any void*s where the normal relational operators don't relevant here too?)
Edit: this is not necessarily a duplicate of/asking about variables on the stack and their layout in memory, I'm aware of that already, I was specifically asking about global variables. Although the answer turns out to be the same, the question is not.
|
Pointer arithmetic on disparate objects yields undefined behavior as per [expr.add]:
4 When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.
(4.1) — If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.
(4.2) — Otherwise, if P points to an array element i of an array object x with n elements (9.3.4.5), the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) array element i + j of x if 0 ≤ i + j ≤ n and the expression P - J points to the (possibly-hypothetical) array element i − j of x if 0 ≤ i − j ≤ n.
(4.3) — Otherwise, the behavior is undefined.
Since s0 through s2 are not elements of an array, get_2 yields explicitly documented undefined behavior.
As far as I can tell, the standard puts no limits on the order in memory of these variables, so the compiler could order them any way it wanted, with any amount of padding or other variables between them. This is not explicitly mentioned as such, but as was pointed out to me in the comments, [expr.rel] and [expr.eq] determine that the results of relational operators in these cases are undefined/unspecified. In particular, [expr.eq] states about operators == and != that
(3.1) — If one pointer represents the address of a complete object, and another pointer represents the address one past the last element of a different complete object, the result of the comparison is unspecified.
and [expr.rel] about <, >, <=, >= that
4 The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules:
(4.1) — If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript is required to compare greater.
(4.2) — If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare greater provided the two members have the same access control (11.9), neither member is a subobject of zero size, and their class is not a union.
(4.3) — Otherwise, neither pointer is required to compare greater than the other.
Again, since s0, s1, s2 are not part of the same array and not members of the same object, 4.3 is relevant, and the results of comparing pointers to them is unspecified. In practical terms, this means that the compiler can order them in memory in an arbitrary fashion.
|
74,533,928
| 74,626,521
|
Upload file to Google Drive folder is failing
|
I am developing a function "uploading file to Google Drive folder" using c++ / Poco library.
File is always getting uploaded to root folder only
I have added optional parameter parents as below
std::string strParents = "[ { "id": "" + std::string(locationId) + ""} ]"
The code that I am currently using is as below and it uploads to root folder only.
Poco::URI uri("https://www.googleapis.com/upload/drive/v3/files");
uri.addQueryParameter("uploadType", "resumable");
uri.addQueryParameter("supportsAllDrives", "true");
uri.addQueryParameter("name", targetFilePath.filename().string());
uri.addQueryParameter("description", "file from sdk");
uri.addQueryParameter("properties", metaData);
std::string strParents = "[ { \"id\": \"" + std::string(locationId) + "\"} ]";
uri.addQueryParameter("parents", strParents);
Poco::Net::HTTPRequest* req = new Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_POST, uri.toString(), Poco::Net::HTTPMessage::HTTP_1_1);
req->add("Authorization", std::string("Bearer ") + accessToken);
req->add("Content-Type", "application/json; charset=UTF-8");
req->add("X-Upload-Content-Type", "application/octet-stream");
req->add("X-Upload-Content-Length", std::to_string(iFileSize));
//req->add("parents", std::string("[{\"id\":\"") + locationId + std::string("\"}]"));
req->add("parents", strParents); // added here also as a trial
Whatever the format I set for parents option, its uploading to root folder only.
|
I have found the issue. The issue is with Poco usage.
Its for those developers who are struggling like me.
"parents" should be added as an array object. Not as a single key-value object
if I add as below
fileDataObject.add("parents", "[ id ]");
its taking as a single value. When I stringify the post body, parents value appeared as below
parents : "[ *id* ]"
but it should come as
parents : [ *id* ]
Then I have added it as an array object as below
Poco::JSON::Object fileDataObject;
Poco::JSON::Array parents;
parents.add(parentId);
fileDataObject.set("name", targetFilePath.filename().generic_wstring());
fileDataObject.set("parents", parents);
|
74,534,000
| 74,534,176
|
How to define class attribute after creating class
|
I am trying to figure out how to define a Variable which is a member of a class in C++, Outside of the normal class body. It may be inside of a Function, or outside of the class. Is this possible. What I need is that the variable should be a member of the class such that if I call Nodesecond.birthdate, it returns the birthdate.
I am attempting to understand the language, there is no real-world application involved.
This was my attempt at doing it:
#include <iostream>
using namespace std;
struct Nodesecond {
public:
int Age;
string Name;
// I dont want to define Birthdate here. It should be somewhere else.
Nodesecond() {
this->Age = 5;
this->Name = "baby";
this->birthdate = "01.01.2020";
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
Nodesecond mynode;
cout << mynode.Age << endl << mynode.Name << mynode.Birthdate;
return 0;
}
|
You can do something close to JavaScript objects.
#include <iostream>
#include <unordered_map>
using namespace std;
struct Nodesecond {
public:
int Age;
string Name;
unordered_map<string, string> Fields;
string& operator[](const string& name) {return Fields[name];}
Nodesecond() {
this->Age = 5;
this->Name = "baby";
*(this)["Birthdate"] = "01.01.2020";
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
Nodesecond mynode;
cout << mynode.Age << endl << mynode.Name << mynode["Birthdate"];
return 0;
}
|
74,534,196
| 74,535,257
|
linked list destructor with std::move c++
|
I'm learning data structures in C++;
I've written a destructor for a linked list as follows:
~List(){
Node* temporary = new Node;
Node* node = head;
while(node != nullptr){
temporary = node;
node = node->next;
delete temporary;
}
}
But then I realized that I can do:
~List(){
Node* node = head;
while(node != nullptr){
node = std::move(node->next);
}
}
Avoiding creating a temporary object, I tried it and worked fine, but I don't know if it is okay, I didn't find a destructor like this in any other place.
|
std::move doesn't do anything by it's own, it only cast something to rvalue.
How the rvalue is used is determined by the function that accept it, and assignment of raw pointer does nothing different than copy in that case.
But for example, if you're using std::unique_ptr, the operator=(unique_ptr&&) would delete the original data after assignment*.
so if you're using something like
#include <memory>
struct Node{
std::unique_ptr<Node> next;
// possibly move List destructor here
// i.e. destruct a Node would safely remove all sub-node non-recursively
};
struct List{
std::unique_ptr<Node> head;
// write destructor to prevent deep recursion
~List(){
while(head) head = std::move(head->next); // current head is deleted after assignment
}
};
then it would work
*btw, self-assignment is safe because it's actually effectively reset(r.release())
|
74,534,510
| 74,534,683
|
Deleting items from QT's QListWidget leading to undeletion/corruption of other entries
|
Disclaimer : I am pretty new to UI and QT.
I have UI that have QListWidget comprising of some numbers (1 to 5), now I am trying to delete the item one by one..
Problem :
After deletion of all entries are done, I can still see some entries (specifically 2 & 4).
Code:
File : main.cpp
Here I have created one async thread that will call MainWindows::display function.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
static MainWindow w;
w.show();
std::thread([]{
w.display();
}).detach();
a.exec();
return 0;
}
File : mainwindow.cpp
Here display function is deleting the items.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::display()
{
sleep(15);
for(int i = 0; i < 5 ; i++)
{
auto j = ui->listWidget->takeItem(i);
delete j;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
File : mainwindow.UI
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QListWidget" name="listWidget">
<property name="geometry">
<rect>
<x>180</x>
<y>20</y>
<width>256</width>
<height>192</height>
</rect>
</property>
<item>
<property name="text">
<string>1</string>
</property>
</item>
<item>
<property name="text">
<string>2</string>
</property>
</item>
<item>
<property name="text">
<string>3</string>
</property>
</item>
<item>
<property name="text">
<string>4</string>
</property>
</item>
<item>
<property name="text">
<string>5</string>
</property>
</item>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>19</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
Output:
Questions:
Why this is happening? am I doing something wrong?
If this leads to undeletion/corruption is there any other way to achieve it?
Any help is very much appreciated.
|
The reason is not really related to Qt but has to do with arrays and loops in general.
Say, initially, I start with a list:
0. Apple
1. Orange
2. Jackfruit
I remove the item at index 0:
0. Orange
1. Jackfruit
Now in the loop, we do i++, and then remove the item at index 1.
0. Orange
Notice that we completely skipped Orange because it moved down as we incremented our index.
If you want to delete everything, you can use QListWidget::clear() instead.
As for memory "corruption", the delete j is ok, since you need to manage the pointer yourself after calling takeItem.
On a side note, I wouldn't mix std::thread with Qt (see comments here).
|
74,534,571
| 74,534,767
|
Forward declaration of structure pattern
|
I am forced to use the architecture which will be presented below. Forward declaration is the pattern I'm trying to implement to counter the issue.
Here is what I have so far :
class_with_config.h :
#include "config_file.h"
#include "i_class_with_config.h"
class ClassWithConfig : public I_ClassWithConfig
{
// specific implem
};
config_file.h :
struct A {
bool A1;
bool A2;
}
struct B {
bool B1;
bool B2;
}
struct C {
A a;
B b;
}
i_class_with_config.h :
struct B; // forward declaration of struct B
class I_ClassWithConfig
{
// definition of interface
};
side_class.h :
#include "i_class_with_config.h"
class SideClass
{
public :
SideClass(B* config);
private :
void Foo(void);
B* my_config;
};
side_class.cpp :
SideClass::SideClass(B* argConfig) : my_config(argConfig)
{
}
void SideClass::Foo(void)
{
if (my_config->B1 == true)
{
// do something
}
}
I need to use my_config in my SideClass implementation, but I get
pointer to incomplete class type "B" is not allowed
This looks like a forward declaration of structure issue but the pattern is unlike anything I've ever come across.
Main constraint is that I do not have the right to include config_file.h into side_class.h
EDIT 1: corrected typo based on @Stack Danny and @Vlad from Moscow anwsers.
|
Main constraint is that I do not have the right to include config_file.h into side_class.h
You can solve the issue by including side_class.h and config_file.h into side_class.cpp as shown below.
side_class.cpp
#include "side_class.h" //added this
#include "config_file.h" //added this
SideClass::SideClass(B* argConfig) : my_config(argConfig)
{
}
void SideClass::Foo(void)
{
if (my_config->B1 == true)
{
// do something
}
}
Working demo
Note also that you should use include guards in the headers as done in the above linked working demo.
|
74,534,852
| 74,535,116
|
Storing and using smart_ptr address
|
I'm trying to pass a shared_ptr to an object around, which may or may not be null:
#include <iostream>
#include <memory>
struct MyObject {
int i = 0;
MyObject(const int i_) : i(i_) {}
};
struct Command {
std::shared_ptr<MyObject> cmdObj;
Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {
std::cout << "Store and use this address: " << &obj << std::endl; // [1]
}
void execute() {
if (cmdObj == nullptr) {
cmdObj = std::make_shared<MyObject>(42);
} else {
cmdObj->i = 7;
}
}
};
struct CommandManager {
std::shared_ptr<MyObject> globalObj; // [1]
CommandManager() { globalObj = nullptr; }
void runCommand() {
Command cmd(globalObj);
cmd.execute();
}
};
int main() {
CommandManager cm;
std::cout << "cm.globalObj address: " << &cm.globalObj << std::endl; // [1]
cm.runCommand();
if (cm.globalObj == nullptr) {
std::cout << "globalObj is null" << std::endl;
} else {
std::cout << "globalObj is " << cm.globalObj->i << std::endl;
}
}
As you can see, I'm trying to manipulate or create globalObj from within Command. However, despite passing the address in the constructor ([1]), I'm not storing it correctly so that the new object is usable in the CommandManager.
How do I make it so I can store and use the address of the shared_ptr<MyObject> correctly?
Thank you in advance.
|
To store an address, you need a pointer. In this case, a pointer to a std::shared_ptr.
struct Command {
std::shared_ptr<MyObject>* cmdObj;
Command(std::shared_ptr<MyObject>& obj) : cmdObj(&obj) {
std::cout << "Store and use this address: " << &obj << std::endl; // [1]
}
void execute() {
if (*cmdObj == nullptr) {
*cmdObj = std::make_shared<MyObject>(42);
} else {
(*cmdObj)->i = 7;
}
}
};
Demo
You can also use a reference here since you need to pass something to Command's constructor, and a you won't have a dangling reference problem unless you'd have a dangling pointer problem with the previous option.
struct Command {
std::shared_ptr<MyObject>& cmdObj;
Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {
std::cout << "Store and use this address: " << &obj << std::endl; // [1]
}
void execute() {
if (cmdObj == nullptr) {
cmdObj = std::make_shared<MyObject>(42);
} else {
cmdObj->i = 7;
}
}
};
Demo
However, I'm not sure you actually want a std::shared_ptr to begin with. A simple variable would work just as well.
struct Command {
MyObject* cmdObj;
Command(MyObject* obj) : cmdObj(obj) {
std::cout << "Store and use this address: " << obj << std::endl; // [1]
}
void execute() {
cmdObj->i = 7;
}
};
struct CommandManager {
MyObject globalObj = 42; // [1]
void runCommand() {
Command cmd(&globalObj);
cmd.execute();
}
};
int main() {
CommandManager cm;
std::cout << "cm.globalObj address: " << &cm.globalObj << std::endl; // [1]
cm.runCommand();
std::cout << "globalObj is " << cm.globalObj.i << std::endl;
}
Demo
If your original intent was to share the MyObject object through a std::shared_ptr, then you need to create that object before you can share it.
struct Command {
std::shared_ptr<MyObject> cmdObj;
Command(std::shared_ptr<MyObject>& obj) : cmdObj(obj) {
}
void execute() {
cmdObj->i = 7;
}
};
struct CommandManager {
std::shared_ptr<MyObject> globalObj; // [1]
CommandManager() { globalObj = std::make_shared<MyObject>(42); }
void runCommand() {
Command cmd(globalObj);
cmd.execute();
}
};
Demo
Or you can create it in Command and then share it with CommandManager.
struct Command {
std::shared_ptr<MyObject> cmdObj;
Command(std::shared_ptr<MyObject>& obj) {
if (obj == nullptr) {
obj = std::make_shared<MyObject>(42);
}
cmdObj = obj;
}
void execute() {
cmdObj->i = 7;
}
};
Demo
Or you can create a std::unique_ptr, share it, and then create the MyObject object in Command if needed.
struct Command {
std::shared_ptr<std::unique_ptr<MyObject>> cmdObj;
Command(std::shared_ptr<std::unique_ptr<MyObject>> obj) : cmdObj(obj) {
}
void execute() {
if (*cmdObj == nullptr) {
*cmdObj = std::make_unique<MyObject>(42);
} else {
(*cmdObj)->i = 7;
}
}
};
struct CommandManager {
std::shared_ptr<std::unique_ptr<MyObject>> globalObj; // [1]
CommandManager() { globalObj = std::make_shared<std::unique_ptr<MyObject>>(nullptr); }
void runCommand() {
Command cmd(globalObj);
cmd.execute();
}
};
Demo
|
74,534,956
| 74,535,009
|
::tolower using std::transform
|
Why std::transform doesn't work this way:
std::string tmp = "WELCOME";
std::string out = "";
std::transform(tmp.begin(), tmp.end(), out.begin(), ::tolower);
out is empty!
But this works:
std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
I don't want the transformation to happen in-place.
|
You are writing in out-of-bounds memory, since the range of out is smaller than that of tmp. You can store the result in out by applying std::back_inserter.
As user17732522 pointed out, since it's not legal to take the adress of a standard libary function, it's better to pass over a lamda object that calls std::tolower on the character when needed.
std::transform(tmp.begin(), tmp.end(), std::back_inserter(out), [](auto c) {
return std::tolower(static_cast<unsigned char>(c));
});
|
74,535,434
| 74,536,777
|
ffmpeg set hdr options through av_opt_set
|
How can I add the following HDR options to a video encoder written in C++, using av_opt_set or similar ?
ffmpeg -i GlassBlowingUHD.mp4 -map 0 -c:v libx265 -x265-params hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=0,0 -crf 20 -preset veryfast -pix_fmt yuv420p10le GlassBlowingConverted.mkv
Currently I have successfully used av_opt_set to set the "crf" option, so it works, but I'm not sure how to add these ones:
-x265-params hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=0,0
This is a snippet of my code and how I use it:
AVCodecContext* cctx;
cctx = avcodec_alloc_context3(vcodec);
cctx->width = dst_width;
cctx->height = dst_height;
cctx->pix_fmt = output_scaler_pixel_format;
cctx->time_base = av_inv_q(dst_fps);
cctx->framerate = dst_fps;
av_opt_set(cctx->priv_data, "crf", "20", AV_OPT_SEARCH_CHILDREN);
It is worth mentioning that I did add some of the options with visible succes, such as the color-space, directly through the CodecContext properties.
cctx->colorspace = AVCOL_SPC_BT2020_NCL;
cctx->color_trc = AVCOL_TRC_SMPTE2084;
cctx->color_primaries = AVCOL_PRI_BT2020;
I have also tried using av_set_options_string, but no luck.
av_set_options_string(cctx->priv_data, "hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=0,0", "=", ":");
|
The option name is x265_params, and its value is its arg.
av_opt_set(cctx->priv_data, "x265-params", "hdr-opt=1:repeat-headers=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=0,0", AV_OPT_SEARCH_CHILDREN);
|
74,535,578
| 74,535,845
|
How to store parameter packed function for later called
|
I'm building a project with a signal/slot library, and i'd like to be able to execute the slot in a different thread than the signal calling it, like Qt does.
To do that, I'm trying to store a function call with parameter pack to allow varying args number :
#include <functional>
#include <iostream>
struct SlotProxy {
template<typename Func, typename ...Args>
void PostEvent(Func func, Args ... args) {
_callback = [func, &args...]() {
func(args...);
};
}
void operator()() {
_callback();
}
std::function<void()> _callback;
};
struct Obj {
int i{};
void Print() {
std::cout << this << " - Obj val : " << i << std::endl;
}
void Slot(Obj& obj) {
obj.Print();
}
};
void Test(Obj& obj) {
obj.Print();
}
int main() {
Obj obj{};
obj.Print();
SlotProxy sp{};
// error : no matching call for bind
auto bind = std::bind(&SlotProxy::PostEvent, &sp, &Test, std::placeholders::_1);
bind(obj);
}
Here std::bind gives me an error that it can't find the matching definition, what am I doing wrong?
Subsidary question : How can I bind a member function as a parameter to PostEvent? Does a
nested std::bind would work ?
std::bind(&SlotProxy::PostEvent, &p, std::bind(&Obj::Slot, obj, ???), std::placeholders::_1);
|
The problem(error) is that PostEvent is a member function template and when it is used as an argument to std::bind as in &SlotProxy::PostEvent, the type of its template parameter(s) aren't known.
This means that we need to either use default arguments or explicitly tell the compiler the type of its template parameters. Below is a contrived example:
template <typename T>
class myclass {
public:
template<typename U>
void func(const U&)
{
}
};
int main(){
myclass<int> obj;
//--------------------------------------------vvvvvv----------->pass the argument explicitly
auto mylambda = std::bind(&myclass<int>::func<double>, &obj, 5);
mylambda();
}
Similarly, you will either need to explicitly pass the template arguments or use default arguments wherever possible.
You should also take care of additional problems that the code might have like dangling references etc.
|
74,536,081
| 74,585,883
|
Get a vector of map keys without copying?
|
I have a map of objects where keys are std::string. How can I generate a vector of keys without copying the data?
Do I need to change my map to use std::shared_ptr<std::string> as keys instead? Or would you recommend something else?
My current code goes like this:
MyClass.h
class MyClass {
private:
std::map <std::string, MyType> my_map;
public:
const std::vector<std::string> MyClass::getKeys() const;
}
MyClass.cpp
const std::vector<std::string> MyClass::getKeys() const
{
std::vector<std::string> keys = std::vector<std::string>();
for (const auto& entry : my_map)
keys.push_back(entry.first); // Data is copied here. How can I avoid it?
return keys;
}
|
As suggested by Kevin, std::views::keys was pretty much made for this. The view it produces is a lightweight object, not much more than a pointer to the range argument, which solves the ownership and lifetime issues. Iterating over this view is identical to iterating over the map, the only difference is that the view's iterator dereferences to the first element of the underlying map value.
As for some code, it is pretty simple:
// ...
#include <ranges>
class MyClass {
private:
std::map<std::string, MyType> my_map;
public:
std::ranges::view auto getKeys() const;
};
std::ranges::view auto MyClass::getKeys() const
{
return std::views::keys(my_map);
}
Since ranges and concepts go hand in hand, I've used the std::ranges::view to constrain the auto return type. This is a useful way to let the compiler and user of your function know that it will return a particular category of object, without having to specify a potentially complicated type.
|
74,536,489
| 74,536,521
|
Can you reuse a std::future once it has already been assigned to std::async()?
|
I am curious if a std::future is instantiated and used to assign to the value of an std::async() operation, then waited for completion with .wait(), can it be re-assigned to a new async() operation?
Take this small code snippet for an example:
int fib(int n)
{
if (n < 3) return 1;
else return fib(n-1) + fib(n-2);
}
int main()
{
std::future<int> f1 = std::async(std::launch::async, [](){
return fib(40);
});
f1.wait();
std::cout << "f1 first operation: " << f1.get() << '\n';
f1 = std::async(std::launch::async, [](){
return fib(43);
});
std::cout << "f1 second operation: " << f1.get() << '\n';
}
Are futures allowed to simply be re-assigned once they have been used once before?
I have not been able to find much reading material on this so far, and am interested if this is creating any undefined behavior for the future.
Any information is appreciated and thank you for the help!
|
Yes, it's fine.
This is explicitly described in the documentation for operator=:
future& operator=( future&& other ) noexcept;
Releases any shared state and move-assigns the contents of other to *this. After the assignment, other.valid() == false and this->valid() will yield the same value as other.valid() before the assignment.
|
74,536,736
| 74,573,808
|
Application silently crashes at glfwCreateWindow()
|
I am making a C++ application using GLFW/GLEW for windowing and graphics:
#include <GLEW/glew.h>
#include <GLFW/glfw3.h>
int main()
{
// init glfw
if (!glfwInit())
{
std::cout << "GLFW init failed!: " << std::endl;
}
// set up window hints
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// APP FAILS ON THIS LINE
GLFWwindow* window = glfwCreateWindow(320, 180, "Test Window!", NULL, NULL);
// verify window is valid
if (window == NULL)
{
std::cout << "Failded to create GLFW window" << std::endl;
glfwTerminate();
std::cin.get();
}
glfwMakeContextCurrent(window);
// init GLEW now that we have a current context (window)
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cout << "Failed to init GLEW: " << glewGetErrorString(err) << std::endl;
abort();
}
}
This works perfectly on my system, but I am trying to distribute it to my friend since I will eventually like to share this app. I am using visual studio's guide on distributing, and it has the needed dlls to function on my friends machine. However, in my initialize function, the app is killed without a glfw error callback or anything.
My friend's machine is a windows 10 laptop, with Intel UHD Graphics 620. The installed opengl version is 4.5.
I have tried verifying the installed opengl version, which is higher than what my application requests.
I have tried checking if any missing dlls are not present in my app using Dependencies and Dependency Walker, all of which show nothing is amiss.
I set the GLFW error callback to spam console if there is a problem, and it is not called at all during the runtime on my friends computer.
Edit: I had another person test the code, they also see the same issue. I dont think this is a system issue.
|
Solved. I was building this in Visual Studio under Debug configuration, so it was trying to use the VC++ debug runtime libraries when shared with others. Rebuilding my libraries and application for Release fixed the issue.
|
74,537,475
| 74,565,253
|
SAPI - How to stop all asynchronous speech tasks?
|
I'm using the Microsoft's Speech Application Programming Interface (SAPI) to enable speech in my app. However, when I try to stop asynchronous speech tasks, they stop, but after a second.
In .NET framework, I tried to stop all asynchronous speech tasks, and they stop immediately when I call the SpeechSynthesizer.SpeakAsyncCancelAll. However, when I try to cancel speech in SAPI (C++), speech stopped but after a second (or more). I call ISpVoice::Speak with the SVSFlagsAsync, and of course the SVSFPurgeBeforeSpeak from the SpeechVoiceSpeakFlags enumeration. I tried to call ISpVoice::Pause, then trying to speak again, but it still speaks after a second. I tried using ISpVoice::Skip also, but it didn't work. I tried ISpVoice::SetPriority to Alert, but it didn't stop the speech. I wonder if there is some W3C SSML tag to stop speech that I will send to ISpVoice::Speak as Speech Synthesis Markup language (SSML)? Or if there is some way to stop asynchronous speech tasks immediately?
|
Maybe you could construct two ISpAudio interfaces, then switching between them whenever you need to stop speech.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.