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 |
|---|---|---|---|---|
72,246,117 | 72,246,335 | Does modern compilers use copy elision when using the builder pattern | I am using a few builder patterns in my code base and I was wondering whether return by value should be favoured over the return by reference, given that is the push I am feeling with modern C++. The example, in my opinion, would generate loads of copies if I applied the return by value approach.
class EmailBuilder
{
public:
EmailBuilder from(const string &from) {
m_email.m_from = from;
return *this;
}
EmailBuilder to(const string &to) {
m_email.m_to = to;
return *this;
}
EmailBuilder subject(const string &subject) {
m_email.m_subject = subject;
return *this;
}
EmailBuilder body(const string &body) {
m_email.m_body = body;
return *this;
}
operator Email&&() {
return std::move(m_email);
}
private:
Email m_email;
};
EmailBuilder Email::make()
{
return EmailBuilder();
}
int main()
{
Email mail = Email::make().from("me@mail.com")
.to("you@mail.com")
.subject("C++ builders")
.body("message");
}
My question is whether is if compilers would optimise the many copies generated here. As I see it, for each of the function class we generate a new copy of the builder.
| There are many cases where returning by value is favored since it typically side-steps life-time issue. This is not one of those cases because life-time of the builder is usually well defined and well understood. Thus returning by reference should be favored.
Also, in C++20 you can use designated initializers:
#include <string>
struct Email {
std::string from = "unknown";
std::string to = "unknown";
std::string subject = "unknown";
std::string body = "unknown";
};
int main() {
Email email = {
.from = "me@example.com",
.to = "you@example.com",
.body = "This is my email"
};
}
(See online)
Here, subject is left "unknown".
|
72,247,050 | 72,247,283 | Vectors in functions | I have these code lines in my .cpp file:
void Student::operator+=(const Subject &a){
vector<Subject> v;
v.push_back(a);
}
and I have this operator overloaded:
ostream &operator<<(ostream &output, Student &a){
vector<Subject>v;
/*for (auto& a:v){
output<<a<<endl;
}
*/
cout<<v.size()<<endl;
return output;
}
As It seems ,when Im trying to print the elements of the vector it shows that its empty.
The v.size() of it is 0.
Although I have commented out another way of showing the elements,it doesnt work as well.
I dont know why my vector loses its size when its used in functions.
Any possible help?
| Your vector vector<Subject> v; is in each operator implementation function, and therefore is generated just locally in each function, and will be destroyed by its end.
Think about declaring this vector one time, as a private member of your Student class.
|
72,247,334 | 72,247,589 | using shared_ptr of a type of Class A as a member variable of class B | Assume that my class B is something like this:
class B {
B (double d,double e)
private:
std::shared_ptr < class A > sp;
}
The Constructor from class A looks like:
A(double a, double b){...};
Now, I want to write the constructor function for my class B, in which an object from class A is constructed(initialized or assigned) using the constructor function written above. Can someone explain me how can i do it professionally? I tried something like below but i get errors like "term does not evaluate to a function taking 1 argument" and "an initializer list is unexpected in this context" ...
class B (double d, double e){
double a1 = d*2;
double b2= e*2;
sp { std::make_shared<class A>(a1,b2) };
I'd appreciate to correct me either if i did typing mistake or if i misunderstood something conceptually(or any other explanation)
In general, why should we use make_shared? what are the other approaches and what are their pros and cons? Actually i don't understand if by private: std::shared_ptr < class A > sp; i already created the object by calling the default constructor of class A? So by make_shared i am creating another object?
How can i use the constructor initilizer list using : ?
P.S According to one answer below, it seems that i cannot use the initializer list approach. Because the simple computation i wrote for a1 and b2 were only for showing my problem. My real computations are longer than that and I think i cannot use approaches like B (double d,double e): sp{std::make_shared<A>(d*2, e*2)} .
Thanks
|
How can i use the constructor initilizer list using :
If you want to initialize sp you can do it in the constructor initializer list as shown below, (and not inside the body of the constructor as you were doing):
//---------------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv-->constructor initializer list
B (double d,double e): sp{std::make_shared<A>(d*2, e*2)}
{
}
From std::make_shared's documentation:
template< class T, class... Args > shared_ptr<T> make_shared( Args&&... args );
std::make_shared is used to construct an object of type T and wraps it in a std::shared_ptr using args as the parameter list for the constructor of T.
(end quote)
The template parameter T in this case is A and thus std::make_shared is used to construct a std::shared_ptr<A> and initialize sp with it in the constructor initializer list.
Note that we can also use in-class initializer to initialize sp.
From How to create and use shared_ptr instance:
Whenever possible, use the make_shared function to create a shared_ptr when the memory resource is created for the first time. make_shared is exception-safe. It uses the same call to allocate the memory for the control block and the resource, which reduces the construction overhead. If you don't use make_shared, then you have to use an explicit new expression to create the object before you pass it to the shared_ptr constructor.
|
72,247,462 | 72,248,214 | write a rolling sd function in R and implement in C++ | I have to write implement R function for C++. for e.g I am trying to calculate rolling SD but below code is not working. any help will be highly appreciated.
#Below code is working fine
library(roll)
n <- 150
x <- rnorm(n)
x
weights <- 0.9 ^ (n:1)
weights
roll_sd(x, width = 5)
#But when I am passing it though the CPPFunction it is not working
cppFunction("roll_sd(x, width = 5)")
| This is not how cppFunction works. You cannot simply pass it an R call and expect it to magically transpile to C++.
In fact, it's more like the other way round. You write the function in C++ and cppFunction makes that function available in R.
A crude implementation of a rolling standard deviation that matches roll_sd would be something like this:
cppFunction("NumericVector rolling_sd(NumericVector x, int width) {
NumericVector y = clone(x);
for(int i = 0; i < (int)x.size(); i++) {
if(i < (width - 1)) {
y[i] = NA_REAL;
} else {
double sum = 0.0;
double total = 0.0;
for(int j = i - (width - 1); j <= i; j++) {
sum += x[j];
}
double mean = sum / width;
for(int j = i - (width - 1); j <= i; j++) {
total += pow(x[j] - mean, 2);
}
y[i] = sqrt(total / (width - 1));
}
}
return y;
}")
After we run this code, the function rolling_sd is now available to us in R, and gives the same result as roll_sd:
set.seed(1)
x <- rnorm(10)
roll::roll_sd(x, width = 5)
#> [1] NA NA NA NA 0.9610394 1.0022155 1.0183545
#> [8] 0.8694145 0.6229882 0.6688342
rolling_sd(x, width = 5)
#> [1] NA NA NA NA 0.9610394 1.0022155 1.0183545
#> [8] 0.8694145 0.6229882 0.6688342
However, our C++ version is over 10 times faster, as the following benchmark shows.
microbenchmark::microbenchmark(roll_sd(x, width = 5), rolling_sd(x, width = 5))
#> Unit: microseconds
#> expr min lq mean median uq max neval cld
#> roll_sd(x, width = 5) 38.7 41.4 44.310 42.2 44.3 154.5 100 b
#> rolling_sd(x, width = 5) 2.1 2.6 3.346 3.3 3.7 15.0 100 a
|
72,247,716 | 72,248,109 | Debug Assertion Failed: Expression vector subscript out of range | I dont understand why it says subscript out of range when I have reserved the space in the vector. I have created a short form of my code to explain what the problem is better:
#include <vector>
#include <string>
#include <thread>
#include <iostream>
using namespace std;
class A {
public:
vector<vector<string>> foo;
thread* aThread;
A() {
foo.reserve(10); //makes sure we have space...
aThread = new thread([this]() {
for (int i = 0; i < 10; i++) {
foo[i].push_back("Hello"); // Debug assertion failed. :(
}
});
}
};
int main()
{
A a;
a.aThread->join();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < a.foo.size(); j++) {
cout << a.foo[i][j] << " ";
}
cout << endl;
}
return 0;
}
Here it gives the error as soon as I am trying to add the element into my foo vector inside the thread. I cannot figure out what is wrong. Please help.
| foo.reserve(10)
Reserves space for elements in foo, but it does not populate any of the elements with an empty std::vector.
You can change it to:
foo.resize(10);
Which will reserve the space and create the empty vector< string > elements, so that you can access them.
|
72,247,817 | 72,247,863 | how to write forward iterator using private std::vector base class | I need a vector class that exposes a small subset of the std::vector API. Everything works except range-based for. Here my attempt at implementing a forward iterator, which however does not compile.
#include <vector>
#include <iostream>
template <class T>
class OwningVector : private std::vector<T*> {
using super = std::vector<T*>;
public:
OwningVector() = default;
~OwningVector()
{
for (T* e : *this)
delete e;
super::clear();
}
OwningVector(const OwningVector& other)
: super()
{
super::reserve(other.size());
for (T* e : other)
super::emplace_back(e->clone());
}
OwningVector& operator=(const OwningVector& other)
{
if (this == &other)
return *this;
OwningVector ret(other);
swap(*this, ret);
return *this;
}
void emplace_back(T* e) { super::emplace_back(e); }
size_t size() const { return super::size(); }
T* const& operator[](int i) const { return super::operator[](i); }
T* const& at(int i) const { return super::at(i); }
const T* back() const { return super::back(); }
// Here the questionable part of my code:
class Iterator : public std::vector<T*>::iterator {};
Iterator begin() const { return super::begin(); }
Iterator end() const { return super::end(); }
Iterator begin() { return super::begin(); }
Iterator end() { return super::end(); }
};
class A {
public:
A(int m) : m(m) {}
int m;
};
int main() {
OwningVector<A> v;
v.emplace_back(new A(1));
for (const A*const a: v)
std::cout << a->m << std::endl;
}
Compilation fails:
h.cpp: In instantiation of ‘OwningVector<T>::Iterator OwningVector<T>::begin() [with T = A]’:
h.cpp:56:27: required from here
h.cpp:43:43: error: could not convert ‘((OwningVector<A>*)this)->OwningVector<A>::<anonymous>.std::vector<A*, std::allocator<A*> >::begin()’ from ‘std::vector<A*, std::allocator<A*> >::iterator’ to ‘OwningVector<A>::Iterator’
43 | Iterator begin() { return super::begin(); }
| ~~~~~~~~~~~~^~
| |
| std::vector<A*, std::allocator<A*> >::iterator
h.cpp: In instantiation of ‘OwningVector<T>::Iterator OwningVector<T>::end() [with T = A]’:
h.cpp:56:27: required from here
h.cpp:44:39: error: could not convert ‘((OwningVector<A>*)this)->OwningVector<A>::<anonymous>.std::vector<A*, std::allocator<A*> >::end()’ from ‘std::vector<A*, std::allocator<A*> >::iterator’ to ‘OwningVector<A>::Iterator’
44 | Iterator end() { return super::end(); }
| ~~~~~~~~~~^~
| |
| std::vector<A*, std::allocator<A*> >::iterator
| class Iterator : public std::vector<T*>::iterator {};
Why? This looks like a certain other language's way of doing that. It's also not guaranteed to work because vector<T*>::iterator may actually be a pointer type, in which case you can't derive from it.
using Iterator = typename super::iterator;
using ConstIterator = typename super::const_iterator;
ConstIterator begin() const { return super::begin(); }
ConstIterator end() const { return super::end(); }
Iterator begin() { return super::begin(); }
Iterator end() { return super::end(); }
This works. The typename is required up to C++17, can be dropped for C++20.
|
72,247,970 | 72,279,500 | what is multisample per pixel in directx11 DXGI_SAMPLE_DECS | I was reading documentation about DXGI_SWAP_CHAIN_DESC and i came across with DXGI_SAMPLE_DESC
Count
Type: UINT
The number of multisamples per pixel.
now what exactly is multisamples per pixel?
| DXGI_SAMPLE_DESC as you surmised is for specifying Multi-Sample Anti-Aliasing (MSAA).
That said, you should be aware that the SwapChain support for MSAA is not something you should use anymore. As such, just always set DXGI_SWAP_CHAIN_DESC.SampleDesc.Count = 1; and DXGI_SWAP_CHAIN_DESC.SampleDesc.Quality = 0;.
Instead, to use MSAA you should explicitly create your own MSAA render target and explicitly resolve the result yourself as part of your presentation of the results to the single-sample SwapChain. For details on why and how, see this blog post series.
Note that you can use MSAA SwapChains for DirectX 11 with the older DXGI_SWAP_EFFECT_DISCARD and DXGI_SWAP_EFFECT_SEQUENTIAL flip-effects, and the DirectX 11 runtime will do the resolve automatically. Per the blog post, this is NOT supported for DirectX 12 or the use of modern DXGI_SWAP_EFFECT_FLIP_DISCARD or DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL swap effects. This is really a 'toy' setup as any production rendering will do additional processing after the resolve from multi-sample to single-sample before putting it into the swapchain for display.
As you are likely new to DirectX 11, you may want to look at DirectX Tool Kit. I have a tutorial that covers MSAA.
|
72,247,990 | 72,261,555 | Remove some, but not all overloaded functions inherited from base class | I am writing a vector class that takes ownership of member pointers. As far as possible, I want to reuse std:vector. I have been trying private and public inheritance; in both cases I am running into difficulties.
For private inheritance, see issue how to write forward iterator using private std::vector base class.
For public inheritance, I need to delete certain methods from the base class. Specifically, I need to prevent users from replacing member pointers without deleting objects. So I want to delete T* & operator[](int i). At the same time, I still want to support T* const operator[](int i) const. Somehow, the deletion of the former seems to overrule the reimplementation of the latter. Here a minimal complete example:
#include <vector>
#include <iostream>
/* Vector class that takes ownership of member pointers */
template <class T>
class OwningVector : public std::vector<T*> {
using super = std::vector<T*>;
public:
~OwningVector() { /* deletes objects pointed to */ };
T* & operator[](int i) = delete;
T* const operator[](int i) const { return super::operator[](i); }
};
class A {
public:
A(int m) : m(m) {}
int m;
};
int main() {
OwningVector<A> v;
v.emplace_back(new A(1));
std::cout << v[0]->m << std::endl;
}
Compilation fails:
hh.cpp: In function ‘int main()’:
hh.cpp:23:21: error: use of deleted function ‘T*& OwningVector<T>::operator[](int) [with T = A]’
23 | std::cout << v[0]->m << std::endl;
| ^
hh.cpp:9:10: note: declared here
9 | T* & operator[](int i) = delete;
| ^~~~~~~~
| From the comments:
Using v[0]->m will call the const-version of the operator if v is const. Otherwise it calls the non-const operator.
The fact that you don't write to v doesn't affect this.
|
72,248,200 | 72,248,229 | Error: (One function) cannot be overloaded with (other function) | I have the following class structure:
class DBData
{
public:
DBData();
virtual
~DBData() = 0;
virtual
DBData* Clone() const = 0;
virtual
std::unique_ptr<DBData>& Clone() const = 0;
};
This does no compile, and the compiler objects with the following error message:
error: ‘virtual std::unique_ptr<DBData>& DBData::Clone() const’ cannot be overloaded with ‘virtual DBData* DBData::Clone() const’
Why does this error occur? My guess would be that it has something to do with both return types being either references or pointers (which are in some ways similar).
Or possibly unique_ptr is too similar to a raw pointer, but that doesn't seem to make a lot of sense to me.
Obvious Solution:
Obvious problem obvious solution. Should have realized this. Taking inspiration from operator++:
virtual
std::unique_ptr<DBData>& Clone(int dummy = 0) const = 0;
Or perhaps better, just rename it:
virtual
std::unique_ptr<DBData>& CloneUniquePtr() const = 0;
Edit: Nope - this doesn't work either.
The reason being that this
virtual
std::unique_ptr<DBDataDerived>& CloneUniquePtr() const;
is an invalid covariant return type. Given that this is a reference type, I thought this should be ok. Is it the case that only raw pointers can be covariant return types?
Edit 2: For a type to be covariant (in this context at least) it has to obey Liskov Substitution Principle.
It seems the only way to write something compilable is to do:
std::unique_ptr<DBData> DBDataDerived::Clone() const;
Which means not using covariant return types at all.
| The problem is that we cannot overload a member function(or a function) based only on its return type.
This is because overload resolution takes into account the function's signature.
And from defns.signature.member
signature
〈class member function〉 name, parameter type list (11.3.5), class of which the function is a member,
cv-qualifiers (if any), and ref-qualifier (if any)
As we can see the return type isn't part of the signature of the member function. Hence it(the return type) cannot be used to overload the member function.
|
72,248,443 | 72,248,487 | Problem with a junk value in a member when using an empty default constructor | I am trying to create a very basic class with a default constructor:
class Point {
public:
Point() = default;//con 1
explicit Point(double x): x_axis(x), y_axis(0){}//con 2
Point(const Point &other) = default;
~Point() = default;
private:
double x_axis;
double y_axis;
}
When I try to use the default constructor in the main() function, it generates a random junk value for x_axis:
Point p1;//generates random value
Point p2{};//works as intended
Why is that? When I use the other constructor (con 2) like so:
explicit Point(double x = 0): x_axis(x), y_axis(0){}
Both of them work as intended.
why, in the first try with no brackets, does it generate a random value, but {} worked, but in the second try they both work?
what is calling the default constructor with {}?
| It's because the second constructor initializes the member variables with values while the first constructor leaves the member variables with indeterminate values.
Either do:
class Point {
public:
Point() : x_axis{}, y_axis{} {} // instead of = default
...
or
class Point {
public:
Point() = default;
// ...
private:
double x_axis{}; // {} or
double y_axis = 0.0; // = 0.0
};
|
72,248,495 | 72,248,846 | would anything happen if I pass a pointer function as a parameter? | I wonder that what would happen if I pass a pointer function as a parameter, is it valid and is the memory of that pointer function stuck somewhere in RAM?
This is the example:
char* Function1(char *array1, int N) {
...
return newChar;
}
char* Function2(char *array2, int M) {
...
return newChar;
}
char* newArray = Function2(Function1(oldArray, N), M);
delete[] oldArray;
delete[] newArray;
Whether Function1(oldArray, N) after having been called will have anything wrong with it?
Thank you very much.
| It is valid to write these kind of function calls but as you suspected, the memory you've allocated for the character array in subsequent function calls will be stuck in RAM, a memory leak. Let me explain with the following code.
char* Function1(char *array1, int N) {
char *newarray = new char [N];
for (int i = 0; i < N; ++i)
newarray[i] = array1[i] + 1;
return newarray;
}
char* Function2(char *array2, int N) {
char *newarray = new char [N];
for (int i = 0; i < N; ++i)
newarray[i] = array2[i] + 1;
return newarray;
}
Both the functions allocates a new space, stores the incremented value of the given character array and returns the pointer to the allocated space. Call both the functions as,
int main()
{
int N = 4;
char *oldArray = "abcd";
char *newArray = Function2(Function1(oldArray, N), N);
}
There is nothing wrong in the function call Function1 as it returns the pointer to the newly allocated space and passed it to Function2 as array2. But at the end of Function2, the pointer array2 will be deleted leaving the memory it holds as it is. This results in a memory leak.
To avoid this leak, delete the memory the array2 holds before the end of Function2.
char* Function2(char *array2, int N) {
...
delete[] array2;
return newarray;
}
Hope it helps!
|
72,248,532 | 72,248,556 | Does definition includes declaration? | int a = 0;
This code can be read either: declaration of a or
definition of a, right?
|
declaration of a or definition of a right?
Note that every definition is necessarily a declaration in C++, but not the other way round. That is, not every declaration is a definition.
Thus,
int a = 0; // A definition and hence also a declaration
The above is both a definition and also a declaration.
On the other hand, if you were to write:
extern int a; // This is a nondefining declaration
The above statement extern int a; is a declaration that is not a definition (aka a nondefining declaration)
Moreover,
extern int a = 0; // This is a definition and hence also a declaration even when we have used extern!
Note that even though we have used extern in the above statement, the presence of the initializer 0 makes this a definition and hence also a declaration.
|
72,248,803 | 72,248,849 | What is the difference between iterator and &iterator? | vector<int> A = {1, 2, 3};
//case 1
for(auto it : A){
it = 0;
}
print(A) //OUTPUT -> 1, 2, 3
//case 2
for(auto &it : A){
it = 0;
}
print(A) //OUTPUT -> 0, 0, 0
How are 'it' and '&it' different? How exactly are iterator and &iterator working?
| Case 1
The auto keyword(without the use of &) infers a non-reference type. This means in your case 1, auto infers it to be of type int. This is a non-reference type, meaning that the values from the std::vector will get copied into the loop variable it, which in turn means that any changes made to it will not be reflected in the std::vector itself.
Case 2
In case 2, however, due to the use of & in auto, the loop variable it is of type int& which is a reference type and any change you make on it will be reflected on the original vector.
|
72,248,910 | 72,249,110 | C++ creating Queue using Dynamic Memory | I am trying to create Queue using standard library for some part of my code. For abstract idea my Queue will have Front, Back pointers which points Front and Back elements in the Queue. So when I push something Back ptr will point to new value that has been pushed. And When I pop something front ptr will point the next front value.
For example:
First we declare and it is empty, Front Back both points to nullptr,
[] - Front = nullptr, Back = nullptr
push(5)
[5] - Front = 5, Back = 5
push(7)
[7 , 5] - Front = 5, Back = 7
push(4)
[4, 7, 5] - Front = 5, Back = 4
pop()
[4, 7] - Front = 7, Back = 4
pop()
[4] - Front = 4, Back = 4
pop()
[] - Front = nullptr, Back = nullptr
class Queue
{
private:
struct node
{
int value;
node* next;
node(int value, node* next = nullptr)
{
this->value = value;
this->next = next;
}
};
node* front, * back;
public:
//Constructor
Queue()
{
front = nullptr;
back = nullptr;
}
//Class methods:
void push(int num);
int pop();
bool isEmpty();
};
Methods definitions:
void Queue::push(int num)
{
back = new node(num, back);
}
int Queue::pop()
{
int num = front->value;
node * temp = front;
front = front->next;
delete temp;
return num;
}
bool Queue::isEmpty()
{
if (front == nullptr)
{
return true;
}
else
{
return false;
}
}
For now I am getting runtime error from the pop() and pop() is not removing the front value.
| I rewrite your code:
#include <iostream>
using namespace std;
class Queue
{
private:
struct node
{
int value;
node* next;
node(int value, node* next = nullptr)
{
this->value = value;
this->next = next;
}
};
node* front, * back;
public:
//Constructor
Queue()
{
front = nullptr;
back = nullptr;
}
//Class methods:
void push(int num);
int pop();
bool isEmpty() { return (front == nullptr); }
void print();
};
void Queue::print()
{
node* tmp = this->front;
cout << "[ ";
while(tmp != nullptr) {
cout << tmp->value << " ";
tmp = tmp->next;
}
cout << "]";
}
void Queue::push(int num)
{
node* tmp = new node(num, nullptr);
if(!isEmpty()) { // if not empty
back->next = tmp;
back = tmp;
return;
}
// if list is empty
front = tmp;
back = tmp;
}
int Queue::pop()
{
if (isEmpty()) return 0;
int num = front->value;
if (front->next == nullptr) { // if list have only one element
delete front;
front = nullptr;
back = nullptr;
return num;
}
node * temp = front;
front = front->next;
delete temp;
return num;
}
int main() {
Queue q;
q.push(5);
q.push(2);
q.push(2);
q.push(5);
q.print();
q.pop();
q.print();
q.pop();
q.print();
q.push(5);
q.print();
q.pop();
q.print();
q.pop();
q.print();
q.pop();
q.print();
q.pop();
q.print();
q.push(5);
q.print();
return 0;
}
I added a print() method because of testing, made isEmpty() cleaner, and added a few conditions to check special cases.
If list is empty and pop() is called nothing needs to be done.
If list is empty and push() is called back and front needs to point to same object.
If list have only one element and pop() is called list need to be cleared, front and back needs to be nullptr
|
72,249,280 | 72,249,349 | Issue with unique_ptr | Can anyone tell me what the issue is with this code? It throws an error:
cannot convert argument 1 from '_Ty' to 'const day18::BaseInstruction &'
enum Command { snd, set, add, mul, mod, rcv, jgz };
struct BaseInstruction {
Command cmd;
char reg;
BaseInstruction(Command cmd, char reg)
:cmd{cmd}, reg{reg}
{}
};
template <typename T>
struct Instruction : public BaseInstruction {
T val;
Instruction(Command cmd, char reg, T val)
:BaseInstruction(cmd, reg), val{ val }
{}
};
std::unique_ptr<BaseInstruction> getInstructionPtr(Command cmd, char reg, std::string valStr) {
const static std::regex nr("-?\\d+");
if (valStr.length() == 0) return std::make_unique<BaseInstruction>(new BaseInstruction(cmd, reg));
if (std::regex_match(valStr, nr)) return std::make_unique<BaseInstruction>(new Instruction<int>(cmd, reg, std::stoi(valStr)));
return std::make_unique<BaseInstruction>(new Instruction<char>(cmd, reg, valStr[0]));
}
| std::make_unique() is the smart-pointer equivalent of new, which means it calls the constructor of the specified type, passing the input parameters to that constructor, and returns a std::unique_ptr that points to the new object.
The statement:
std::make_unique<BaseInstruction>(new Instruction<char>(...));
is therefore equivalent to this:
new BaseInstruction(new Instruction<char>(...))
I'm quite sure that's not what you meant to write.
If you just want to convert a raw pointer to a std::unique_ptr, construct the std::unique_ptr directly and don't use std::make_unique():
return std::unique_ptr<BaseInstruction>(new Instruction<char>(...));
Otherwise, use std::make_unique() to construct Instruction<char> instead of BaseInstruction:
return std::make_unique<Instruction<char>>(...);
|
72,249,892 | 72,250,049 | Building C++ code with different version of Visual Studio produces different file size of .exe? | I can build my own .sln manually on my machine, or have Azure DevOps build it on a remote machine. The software is targeting .NET Core 3.1, and using C++17. I had noticed that building the same code, from the same branch, produced a different size .exe: the remote one had 9 KB less than the local one.
I finally got the same result when I upgraded the remote machine's version of Visual Studio 2019 to match mine (from 16.8.something up to 16.11.14). But how can this difference be explained? Is there something missing from the smaller file? It should have all the same methods, logic, and functionality. There were no errors, so no part of it could have failed to compile.
I also have to build Java projects with Maven and have heard that it can be built "slightly differently" depending on Maven versions. That made sense at first, but in hindsight I don't know exactly what that means.
Has anyone been really in the weeds with software builds (specifically with Visual Studio and its C++ compiler) that can explain this concept of "slightly different builds", or has a good idea?
Would both version be functionally identical, or is there no easy way to tell?
| The C++ standard does not dictate the machine code that should be produced by the compiler. It just specifies the expected observable behavior.
So if for example you have a for loop the standard dictates the behavior (initializing, checking the condition etc.). But you can translate to machine code in various ways, e.g. using different registers, or executing the statements in different order (as long as the observable behavior is the same).
This principle is called the as-if rule.
So different compilers (or compiler versions) can produce different machine code. The cause might be either different optimizations, or different ways of translating C++ into machine code (as the mapping between C++ and machine code is not 1-1).
Examples related to optimizations:
If you have various statements in the code that are not dependent (e.g. you modify different unrelated variable), the compiler/optimizer might re-order them if memory access patern would be more efficient. Or the compiler/optimizer might eliminate statement that do not have observable behavior (like incrementing a variable that is never read afterwards). Another example is whether functions are inlined which is entirly up to the compiler/optimizer, and affect the binary code.
Therefore there's no guarentee for the size (or content) of a compiled binary file.
|
72,249,905 | 72,253,206 | asio::ip::tcp::socket auto reconnect by io_service | Under Ubuntu 2404LTS with boost version 1.65.1.
I use io_service to initiate asio::ip::tcp::socket async_connect and get socket1, then I read several messages from it.
After receving some specific message from socket1, I call io_service::stop() with remaining/unhandler handler in the io_service and explicitly invoke socket1.close(), and check ec is 0 so the close is successful.
This is the magic part, I call io_service::reset() and after I try to create another socket2 and run io_service::run() again, this also initiate connect for socket1, so there are now 2 live sockets.
What's happening here? I think it may be caused by the remaining handlers in the io_service object, but how come it will initiate connect for the socket1?
| We can't tell without seeing the code, but my suspicion is to undefined behaviour.
Here's a literal implementation of your description:
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;
int main()
{
std::cout << std::boolalpha;
asio::io_service ios;
tcp::socket socket1(ios);
{
asio::streambuf buf;
socket1.async_connect({{}, 8787}, [&](error_code ec) {
std::cout << "socket1 now connected (" << ec.message() << ") to "
<< socket1.remote_endpoint() << std::endl;
async_read_until(
socket1, buf, "some_specific_message", [&](error_code ec, size_t n) {
std::cout << "Received some specific message (" << ec.message()
<< ") at " << n << " bytes" << std::endl;
ios.stop();
std::cout << "ios stopped: " << ios.stopped() << std::endl;
socket1.close();
std::cout << "socket1 closed: " << !socket1.is_open() << std::endl;
});
});
ios.run();
}
std::cout << "about to reset" << std::endl;
ios.reset(); // consider using restart()
tcp::socket socket2(ios);
socket2.async_connect({{}, 9898}, [&](error_code ec) {
std::cout << "socket2 now connected (" << ec.message() << ") to "
<< socket2.remote_endpoint() << std::endl;
});
ios.run();
std::cout << "socket1.is_open(): " << socket1.is_open() << std::endl;
std::cout << "socket2.is_open(): " << socket2.is_open() << std::endl;
}
When we open to services:
(cat main.cpp ; sleep 3; echo "some_specific_message") | netcat -l -p 8787 &
echo "hello socket2" | netcat -l -p 9898 &
We get the output:
socket1 now connected (Success) to 127.0.0.1:8787
Received some specific message (Success) at 570 bytes
ios stopped: true
socket1 closed: true
about to reset
socket2 now connected (Success) to 127.0.0.1:9898
socket1.is_open(): false
socket2.is_open(): true
As you can see, only socket2 is open. Here's a live demo:
Feel free to edit the example to show how it is failing. When you do, you might notice the problem in your code.
|
72,250,228 | 72,250,287 | How should I implement a copy constructor & assignment operator for a matrix class? | I have a matrix class with fields like this:
template <typename T>
class Matrix
{
private:
T **matrix = nullptr;
int rows;
int cols;
At this stage, I have written an assignment operator and a copy constructor. But firstly, there is code duplication, how can it be avoided, and secondly, they seem very similar to me, how can these methods be improved to look normal?
Matrix(const Matrix &matrix_) : rows(matrix_.rows), cols(matrix_.cols)
{
matrix = static_cast<T **>(new T *[rows]);
for (int i = 0; i < rows; i++)
{
matrix[i] = static_cast<T *>(new T[cols]);
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = matrix_[i][j];
}
}
}
Matrix &operator=(const Matrix &matrix_)
{
if (&matrix == this)
{
return *this;
}
clean();
rows = matrix_.rows;
cols = matrix_.cols;
matrix = static_cast<T **>(new T *[rows]);
for (int i = 0; i < rows; i++)
{
matrix[i] = static_cast<T *>(new T[cols]);
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = matrix_[i][j];
}
}
}
void clean()
{
if (cols > 0)
{
for (int i = 0; i < rows; i++)
{
delete[] matrix[i];
}
}
if (rows > 0)
{
delete[] matrix;
}
}
According to the condition of the assignment, it is forbidden to use STL containers, I must implement the controls myself
Added move semantics
Matrix(Matrix &&other) noexcept : rows(std::move(other.rows)), cols(std::move(other.cols)), data(new T(rows * cols))
{
other.data = nullptr;
rows = 0;
cols = 0;
}
Matrix &operator=(Matrix &&other) noexcept
{
if (&other == this)
{
return *this;
}
if (rows != other.rows && cols != other.cols)
{
std::cout << "Error assigning matrices of different sizes" << std::endl;
exit(-1);
}
clean();
std::swap(data, other.data);
std::swap(rows, other.rows);
std::swap(cols, other.cols);
return *this;
}
| Use a 1D array then. It will be much cleaner and simpler and faster than an array of pointers to arrays... You can do something like:
template <typename T>
class Matrix
{
private:
// Note: Assuming T is a trivial type, most likely a fundamental type...
T* data; // Flattened matrix with size = rows*cols. Be careful,
// for really big matrices this multiplication could overflow!!!
// You can use unsigned type since negative size is a nonsense...
unsigned int rows;
unsigned int cols;
public:
Matrix(const Matrix& other)
: data(new T[other.rows*other.cols])
, rows(other.rows)
, cols(other.cols)
{
/// You can do this:
/// for(int i = 0; i < rows*cols; ++i)
/// data[i] = other.data[i];
/// or simply call the copy assign operator:
operator=(other);
}
Matrix& operator=(const Matrix& other)
{
// This is only for matrix with the same dimensions.
// Delete and allocate new array if the dimensions are different.
// This is up to the OP if he can have differently sized matrices or not...
// Also assert will "disappear" if NDEBUG (ie. in release) is defined.
assert(rows == other.rows);
assert(cols == other.cols);
for(int i = 0; i < rows*cols; ++i)
data[i] = other.data[i];
return *this;
}
};
Note: You will also need to define the constructor(s) and destructor of course...
I'm pretty sure you can't make it much simpler than this...
|
72,250,271 | 72,280,172 | Barycentric rational interpolation | I'm trying to write a function which returns a function for calculating Barycentric rational interpolation in C++.
Note:
It is not at all a wise idea to recalculate weight coefficients
W, = 1, 2,…, within the function itself that returns as a result of “Barycentric Interpolation”. Namely, in this way, these coefficients will be recalculated every time such a returned function is called, which is an unacceptable waste of time if it is large. Instead, these coefficients should be calculated within the “Barricentric Interpolation” function, placed somewhere, and “trapped” in the function that returns as a result. In this way, pre-calculated coefficients will be used for each call to the returned function, which is a great time saving
FORMULA:
EXAMPLE:
for nodes: {{1, 3}, {2, 5}, {4, 4}, {5, 2}, {7, 1}}, and row=2
std::cout<<f(2.5) would print 5.425
Code:
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <functional>
#include <cmath>
int max(int a, int b)
{
if (a > b)return a;
return b;
}
int min(int a, int b)
{
if (a < b)return a;
return b;
}
std::vector<double> ComputeWeights(const std::vector<std::pair<int, int>>& nodes, int d) {
std::vector<double>w;
int n = nodes.size();
for (int i = 0; i < n; i++)
{
double sum = 0;
int k = max(1, i - d);
double product = product_f(k, k + d);
for (int j = k; j < k + d; j++)
sum += (pow(-1, k - 1) * 1. / (nodes[i].first - nodes[k].first));
w.push_back(sum);
}
return w;
}
double ComputeF(double x, const std::vector<std::pair<int, int>>& nodes, const std::vector<double>& w) {
double f, ff = 0;
int n = nodes.size();
for (int i = 0; i < n; i++) {
f = ((w[i] * nodes[i].second) / (x - nodes[i].first)) /
(w[i] / (x - nodes[i].first));
ff += f;
}
return ff;
}
std::function<double(double)> formula(std::vector<std::pair<int, int>>nodes, int d)
{
if (d < 0 || d > nodes.size())
throw std::domain_error("Forbidden row");
int n = nodes.size();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (nodes[j].first == nodes[i].first)
throw std::domain_error("Forbidden coordinates");
auto w = ComputeWeights(nodes, d);
return [nodes, w](double x) { return ComputeF(x, nodes, w); };
}
int main ()
{
auto f = formula({{1, 3}, {2, 5}, {4, 4}, {5, 2}, {7, 1}}, 2);
std::cout << f(2.5);
return 0;
}
Could you help me to write this function properly?
My output is: -nan (correct is 5.425)
| Here you go. Note that I rewrote basic parts of your code using my own code from the previous edit version. Further, to clarify: You are actually looking for a thing named Floater-Hormann approximation, which is basically an approximation by a rational function without poles in the interpolation region (and that is usually evaluated using the barycentric formula).
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <functional>
#include <cmath>
std::vector<double> ComputeWeights(const std::vector<std::pair<double, double>>& nodes, int d) {
int n = (int)nodes.size();
std::vector<double> w(n);
for (int k = 0; k < n; ++k)
{
int imin = std::max(k - d, 0);
int imax = std::min(n - d - 1,k);
double temp = imin & 1 ? -1.0 : 1.0;
double sum = 0.0;
for (int i = imin; i <= imax; ++i)
{
int jmax = std::min(i + d, n - 1);
double term = 1.0;
for (int j = i; j <= jmax; ++j)
{
if (j == k) continue;
term *= (nodes[k].first - nodes[j].first);
}
term = temp / term;
temp = -temp;
sum += term;
}
w[k] = sum;
}
return w;
}
double ComputeF(double x, const std::vector<std::pair<double, double>>& nodes, const std::vector<double>& w)
{
double num = 0.0;
double denom = 0.0;
for (int i = 0; i < (int)nodes.size(); ++i)
{
if (x == nodes[i].first)
{
return nodes[i].second;
}
auto ad = w[i] / (x - nodes[i].first);
num += ad * nodes[i].second;
denom += ad;
}
return num / denom;
}
auto formula(std::vector<std::pair<double, double>>nodes, int d)
{
if (d < 0 || d > (int)nodes.size())
throw std::domain_error("Forbidden row");
int n = nodes.size();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (nodes[j].first == nodes[i].first)
throw std::domain_error("Forbidden coordinates");
auto w = ComputeWeights(nodes, d);
return [nodes, w](double x) { return ComputeF(x, nodes, w); };
}
Further, on the C++ level, note that I didn't use a std::function, but directly the lambda, which doesn't add any overhead by indirection. Moreover, I used a std::pair<double, double>, as we are usually in the floating-point regime when it comes to approximation.
The result is, as required
int main()
{
std::vector<std::pair<double, double> > nodes = {{1, 3}, {2, 5}, {4, 4}, {5, 2}, {7, 1}};
auto f = formula(nodes,2);
std::cout<<f(2.5)<<std::endl; //Prints 5.425
}
DEMO
|
72,250,322 | 72,250,422 | cpp - is vtable pointer being altered during construction/destruction | So, while being in a ctor/dtor of a base class while doing smth with a derived class and calling member functions (including virtual), whether via this pointer or not, the function of the relevant class will be called.
How come? Is vtable pointer of the object being altered somehow during the process? Because, as I may understand it, there is generally a single vtable pointer in an object unless multiple inheritance is used.
I have the following code to exemplify what I mean:
#include <stdio.h>
class B {
public:
B()
{ printf("B constructor!\n"); f(); g(); }
virtual ~B()
{ printf("B destructor!\n"); f(); g(); }
virtual void f()
{ printf("f() in B!\n"); }
void g()
{ printf("g() in B!\n"); }
void h()
{ printf("h() in B!\n"); }
};
class D : public B {
public:
D()
{ printf("D constructor!\n"); f(); g(); }
virtual ~D()
{ printf("D destructor!\n"); f(); g(); }
virtual void f()
{ printf("f() in D!\n"); }
void g()
{ printf("g() in D!\n"); h(); }
};
int main()
{
D *d = new D;
B *b = d;
delete b;
}
In ctors/dtors, the member functions of created/destructed object is called.
| An object is the type that it is... until it isn't.
Per C++'s rules, an object's constructors get called in a specific order. Because a derived class instance is a base class instance at all times, the base class instance constructor needs to be called before the derived class instance.
But if that's the case, then what is the object while the base class constructor is called? The derived class constructor hasn't even started, so it doesn't make sense to consider it a derived class instance yet.
So it isn't.
Therefore, during the period of the base class constructor's execution within a derived class's initialization, all virtual calls work as if that is all the class is: a base class instance. It is not yet an instance of the derived class type, so you cannot yet call any of the derived class's members.
I mean, yes, you can static_cast to the derived class instance, but using such a pointer yields undefined behavior, since you're accessing an object of a derived class type before that type has been initialized.
The reverse happens in destructors. The derived class destructor gets called first, then base classes. But after the derived class destructor is finished... the object is no longer a derived class instance. So any virtual calls in base class destructors go to the base class methods.
In vtable-based implementations, this behavior is implemented by changing the vtable pointer between constructors/destructors at various points during initialization. The base class constructor sets the vtable to point at the base class vtable. When the derived class destructor starts, it sets the vtable to point to the derived class vtable.
|
72,250,680 | 72,250,805 | Inherited Templates - C++ | I have a template base class and an inherited class. There is a function inside the baseclass which can accept difference types, I expected that I would call this from inside the inherited class with 'BaseClass::Add();' but I instead receive the error "expected primary-expression before ‘>’ token".
How do I call BaseClass::Add with U?
template <typename T>
class BaseClass
{
public:
template <typename U>
void Add() {
// Do stuff
}
};
template <typename T>
class InheritedClass : public BaseClass<T>
{
public:
template <typename U>
void Add() {
BaseClass<T>::Add<U>(); // Error here
}
};
Thanks in advance
| Use this syntax
BaseClass<T>::template Add<U>()
|
72,250,710 | 72,250,913 | Which version of C++ standard allows reuse of storage previously occupied by an object of a class that has const or reference members? | This answer cites some unknown revision of C++ standard draft:
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:
the storage for the new object exactly overlays the storage location which the original object occupied, and
the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
neither the original object nor the new object is a potentially-overlapping subobject ([intro.object]).
This means that the following code is invalid if class A has const or reference members:
A a;
a.~A();
new (&a) A;
The current revision of [basic.life]p8 doesn't have this requirement:
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object. An object o1 is transparently replaceable by an object o2 if:
the storage that o2 occupies exactly overlays the storage that o1 occupied, and
o1 and o2 are of the same type (ignoring the top-level cv-qualifiers), and
o1 is not a complete const object, and
neither o1 nor o2 is a potentially-overlapping subobject ([intro.object]), and
either o1 and o2 are both complete objects, or o1 and o2 are direct subobjects of objects p1 and p2, respectively, and p1 is transparently replaceable by p2.
This make the code above valid.
But both citations are from the draft. So I don't know starting from witch version of the standard I can use the code above for the class objects that have const or reference members. The answer date is May 7, 2018. So I guess it can be only C++20?
| In terms of the "Major" Standard releases, the clause about the const qualification (which you have emphasised in the excerpt you cite in your question) was present in the final draft for the C++17 Standard (N4659) but not present in that for the C++20 Standard (N4861).
So, from that it would appear that conformance to C++20 (or later) is required to reuse storage previously occupied by a const- or reference-containing class object (in this context).
|
72,251,287 | 72,252,534 | Why isn't explicit specialization with private type allowed for function templates? | https://godbolt.org/z/s5Yh8e6b8
I don't understand the reasoning behind this: why is explicit specialization with private type allowed for class templates but not for function templates?
Say we have a class:
class pepe
{
struct lolo
{
std::string name = "lolo";
};
public:
static lolo get()
{
return {};
}
};
Class template can be explicitly specialized.
And function templates have no problems upon implicit instantiation.
Though you can't create spec_class<pepe::lolo>{} because pepe::lolo is inaccessable.
template <typename>
struct spec_class
{};
// this is ok
template <>
struct spec_class<pepe::lolo>
{};
// this will be ok also upon implicit instantiation
template <typename T>
void template_func(const T &t)
{
std::cout << "implicit: " << t.name << std::endl;
}
But:
// this is not ok!
// template <>
// void template_func(const pepe::lolo &p)
// {
// std::cout << "explicit: " << p.name << std::endl;
// }
// this is ok, but more or less understandable why
template <>
void template_func(const decltype(pepe::get()) &p)
{
std::cout << "explicit: " << p.name << std::endl;
}
// not ok, but expected
// void func(const pepe::lolo&)
// {}
So:
Why is explicit specialization prohibited for a function template?
| From C++20, using private members in the parameter of a specialization of a function template is perfectly valid, due to PR0692. In particular, the following wording was added to temp.spec.general#6:
The usual access checking rules do not apply to names in a declaration of an explicit instantiation or explicit specialization, with the exception of names appearing in a function body, default argument, base-clause, member-specification, enumerator-list, or static data member or variable template initializer.
[ Note 1: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) can be private types or objects that would normally not be accessible. - end note]
(emphasis mine)
The code not compiling is due to a GCC bug 97942, and it compiles just fine in Clang. demo.
|
72,251,624 | 72,251,708 | Polymorphism produces odd behaviour | I have a vector wrapper class which is aimed to simplify polymorphism:
class Shape
{
public:
Shape(string Name) : name(Name) {}
virtual ~Shape() = default;
string name;
private:
};
class Point : public Shape
{
public:
Point(string Name, float X, float Y) : Shape(Name), x(X), y(Y) {}
float x = 0.0f;
float y = 0.0f;
private:
};
// A vector wrapper for unique ptrs, simplifies polymorphism
template <typename T>
class Vector_UniquePtrs {
public:
// Constructor with no parameters
Vector_UniquePtrs() = default;
// Constructor with initialiser list
Vector_UniquePtrs(std::initializer_list<T> items)
{
m_Items.reserve(items.size());
// fill `m_Items` from the initializer list by creating a unique_ptr from each element
std::transform(items.begin(), items.end(), std::back_inserter(m_Items), [](const T& item) {
return std::make_unique<T>(item);
});
};
// Adds a Polymorphic Item (and returns a raw ptr to it)
// usage: v.Add<sub_class>()
template <class U, class... Args>
T& Add(Args&&... args) {
// Forward args to make_unique
m_Items.emplace_back(std::make_unique<U>(std::forward<Args>(args)...));
// Return a reference
return *m_Items.back();
}
// Adds an Item (and returns a raw ptr to it)
// usage: v.Add() (equivelent to v.Add<base_class>())
template <class... Args>
T& Add(Args&&... args) {
// Forward to Add<U>
return Add<T>(std::forward<Args>(args)...);
}
// Remove item from vector
void Remove(size_t index) {
Assert_IsValid(index);
m_Items.erase(std::next(m_Items.begin(), index));
}
// Access item in vector
T& operator[](size_t index) { Assert_IsValid(index); return *m_Items[index]; } // non-const
const T& operator[](size_t index) const { Assert_IsValid(index); return *m_Items[index]; } // const
// Swaps items[n] and items[n_Next]
void ItemSwap(size_t n, size_t n_Next) {
Assert_IsValid(n);
Assert_IsValid(n_Next);
std::swap(m_Items[n], m_Items[n_Next]);
}
// Gets the number of elements in the vector
size_t Size() const { return m_Items.size(); }
protected:
// The container
std::vector<std::unique_ptr<T>> m_Items;
// Validity function
void Assert_IsValid(int index) { assert(index > -1 && index < (int)Size()); }
};
But when called with the following:
Vector_UniquePtrs<Shape> v;
v.Add<Point>("A", 1.0f, 10.0f);
Shape& ref = v[0];
v.Add<Point>("B", 2.0f, 20.0f);
ref = v[1];
Point& pt1 = dynamic_cast<Point&>(ref);
Point& pt2 = dynamic_cast<Point&>(v[1]);
cout << pt1.name << ": " << pt1.x << ", " << pt1.y << endl;
cout << pt2.name << ": " << pt2.x << ", " << pt2.y << endl;
The output is:
B: 1, 10
B: 2, 20
The reference is somehow still 'thinking' it is looking at the v[0] for the inherited variables and v[1] for the base variables.. Can someone explain what is happening and how I should go about to resolve this?
Thanks!
| You can't reassign a reference. ref = v[1] copies the value of v[1] into the object referenced by ref. As the compiler only knows that ref is a Shape it calls Shape's assignment operator and therefore only copies the Shape members leaving the members from Point unchanged.
If you need to change what a reference points to then you probably need to use a pointer instead.
If you want assignment to work polymorphically then you'll need to add a virtual method which does that for you.
|
72,252,179 | 72,252,209 | Why does full `constexpr` enabling of a data structure cause the compiled code to be bigger? | At this moment of Jason Turner's 2016 CppCon talk "Practical Performance Practices", he mentions that full constexpr enabling of every data structure that can be (I'm guessing that means making every field and function constexpr that can be) can result in bigger code "because this causes more data structures to be compiled into your code so you have more data in the data segment than something that would be calculated at runtime" (this quote is kind of a combination of what he actually said at this time stamp and what he said at the end as an answer to a question about this topic).
I don't really understand what that means. Why would constexpr data structures compile to be bigger than non-constexpr data structures? Does anyone have an actual example that shows this?
| When implementing a 7-bit cyclic redundancy check (CRC) algorithm on a microcontroller, I find it handy to build a 256-byte lookup table ahead of time, with some code like this:
uint8_t crc_table[256];
for (unsigned int i = 0; i < 256; i++)
{
crc_table[i] = some_crc_function(i);
}
So if you turn crc_table into a constexpr thing that gets computed at compile time, your toolchain would have to store a 256-byte table in your executable, which takes up space. It would also be able to remove the code for generating the CRC table, but if the machine instructions for that code take less than 256 bytes, then I'd expect the executable to get bigger.
|
72,252,931 | 72,267,379 | How to determine the first function that gets called when running a program in Visual Studio? | I'm currently working on a project that already has lots of files and functions. When I run the program, it executes properly, but I want to know how to find out the first function that gets called when we initially run the application.
More info:
When you run the application, it opens up a small window, asks the users to input some data (like username, password, etc), and waits for the users' data
The call stack is empty, so that doesn't help
The call hierarchy isn't helpful either, since this is a big project
This is a C++ project, and I'm using Visual Studio 2019.
Thanks in advance for any help provided.
| It's the main function (or the WinMain function in my case).
|
72,253,146 | 72,253,400 | Adjust floats to satisfy the condition: abs(float) <= 0.5? | I have got a vector of float of an arbitrary size. I would like to adjust the floats so that they satisfy the condition abs(float) <= 0.5. The fractional part should be preserved although it can differ from the original value, thus setting "x = 0.5" is incorrect. If the float is close to integer, discard it (the input float must not be an integer or close to one within an arbitrary precision).
This is what I wrote, but the code looks somewhat branchy. I wonder if there are ways to make it more elegant / efficient or there's something cruical I might have missed.
Input: float
Output: adjusted float x, so that fabs(x) <= 0.5
Examples with integer part
-5.3 -> -0.3 (take the fractional part, if abs(fractional) <= 0.5)
-5.8 -> 0.2 (add the closest integer, rounded upwards, relative to the absolute value).
5.3 -> 0.3
5.8 -> -0.2 (substract, but round down)
-5.5 -> -0.5 (sign is preserved here)
5.5 -> 0.5 (sign is preserved here)
Examples with only fractional part
0.3 -> 0.3
0.8 -> -0.2 (substract 1)
-0.3 -> -0.3
-0.8 -> 0.2 (add the 1)
Corner cases
any integer -> 0
0.5 -> 0.5
-0.5 -> -0.5
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
float scale(float x)
{
const auto integerPart = std::abs(static_cast<std::int32_t>(x));
const auto fractionalPart = std::fabs(x - static_cast<std::int32_t>(x));
if (x < 0) {
if (integerPart == 0) {
if (fractionalPart > 0.5) {
x += 1;
}
}
else {
x += integerPart + (fractionalPart > 0.5 ? 1 : 0);
}
}
else {
if (integerPart == 0) {
if (fractionalPart > 0.5) {
x -= 1;
}
} else {
x -= integerPart + (fractionalPart > 0.5 ? 1 : 0);
}
}
return x;
}
int main() {
std::vector<float> floats(10000);
static std::default_random_engine e;
static std::uniform_real_distribution<float> distribution(-5, 5);
std::generate(floats.begin(),
floats.end(),
[&]() { return distribution(e); });
for (std::size_t i = 0; i < floats.size(); ++i) {
floats[i] = scale(floats[i]);
}
std::cout << std::boolalpha
<< std::all_of(floats.cbegin(),
floats.cend(),
[&](const float x){ return std::fabs(x) <= 0.5; }) << "\n";
}
Sign preservation is relevant here, if fractional part exceeds 0.5, the sign of resulting value is inverted.
Thank you.
| You can use the floor function to reduce the amount of branches:
#include <iostream>
#include <cmath>
float scale(float x) {
bool neg = std::signbit(x);
x -= std::floor(x + 0.5);
if (!neg && x == -0.5) {
return 0.5;
} else {
return x;
}
}
int main() {
std::cout << "-1.23 " << scale(-1.23) << std::endl;
std::cout << "-0.5 " << scale(-0.5) << std::endl;
std::cout << "0.123 " << scale(0.123) << std::endl;
std::cout << "0.5 " << scale(0.5) << std::endl;
std::cout << "1.23 " << scale(1.23) << std::endl;
}
-1.23 -0.23
-0.5 -0.5
0.123 0.123
0.5 0.5
1.23 0.23
|
72,253,393 | 72,253,530 | How do I apply modifications to a locally scoped range and return it? | The code below, when compiled under g++-11.3 using --std=c++20 -D_GLIBCXX_DEBUG and executed, produces a bizarre runtime error about iterators. I'm not exactly sure what it means but I suspect it has something to do with the vector range going out of scope when test() returns: range doesn't get moved or copied, rather whatever it is the pipe operator returns just retains a reference to range.
#include <ranges>
#include <unordered_set>
#include <vector>
auto to_unordered_set(auto && range) {
using r_type = std::ranges::range_value_t<decltype(range)>;
auto common = range | std::views::common;
return std::unordered_set<r_type>(std::ranges::begin(common), std::ranges::end(common));
}
auto test() {
std::vector<int> range {1,2,3,4,5};
return range | std::ranges::views::transform([](auto x) { return x%2; });
}
int main() {
auto y = to_unordered_set(test());
return 0;
}
/*
/opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/debug/safe_iterator.h:195:
In function:
__gnu_debug::_Safe_iterator<_Iterator, _Sequence,
_Category>::_Safe_iterator(__gnu_debug::_Safe_iterator<_Iterator,
_Sequence, _Category>&&) [with _Iterator =
__gnu_cxx::__normal_iterator<int*, std::__cxx1998::vector<int,
std::allocator<int> > >; _Sequence = std::__debug::vector<int>;
_Category = std::forward_iterator_tag]
Error: attempt to copy-construct an iterator from a singular iterator.
Objects involved in the operation:
iterator "this" @ 0x0x7ffea2b7a8c0 {
type = __gnu_cxx::__normal_iterator<int*, std::__cxx1998::vector<int, std::allocator<int> > > (mutable iterator);
state = singular;
}
iterator "other" @ 0x0x7ffea2b7a820 {
type = __gnu_cxx::__normal_iterator<int*, std::__cxx1998::vector<int, std::allocator<int> > > (mutable iterator);
state = singular;
references sequence with type 'std::__debug::vector<int, std::allocator<int> >' @ 0x0x7ffea2b7a8b0
}
*/
Is there anyway to get something like this to work? I basically want to transform / filter / join / etc.. a range and return it (a copy/move of the entire thing gets returned, both the range and whatever modifications get applied to it).
| First, since the std::vector itself is common_range, transform_view will also be common_range, so using views::common here is redundant.
Second and more important, range is a local variable, so it will be destroyed once it leaves test(), which makes test() return a transform_view that holds a dangling pointer.
Is there anyway to get something like this to work?
Thanks to P2415, you can directly return a transform_view applied to a rvalue vector, which will construct an owning_view that transfers ownership of the original vector's contents to itself, which will no longer cause dangling.
#include <ranges>
#include <unordered_set>
#include <vector>
auto to_unordered_set(auto && range) {
using r_type = std::ranges::range_value_t<decltype(range)>;
return std::unordered_set<r_type>(
std::ranges::begin(range), std::ranges::end(range));
}
auto test() {
std::vector<int> range {1,2,3,4,5};
return std::move(range) |
std::ranges::views::transform([](auto x) { return x%2; });
}
int main() {
auto y = to_unordered_set(test());
}
Demo
|
72,253,554 | 72,253,688 | std::array of structures initializater list syntax | Consider the following C++ code:
struct My_Struct
{
int a;
int b;
};
Now I want to declare a constant std::array of these structures:
Option A:
const std::array<My_Struct,2> my_array =
{
{1,2},
{2,3}
};
Option B:
const std::array<My_Struct,2> my_array =
{
My_Struct(1,2),
My_Struct(2,3)
};
Question: why does option A fail to compile and only option B compiles? What's wrong with nested curly braces when initializing std::array?
It seems to me that compiler should have all necessary information to successfully compile option A, yet it produces "too many initializer values" error.
Meanwhile, nested curly braces work really good when initializing plain arrays:
const My_Struct my_array[] =
{
{1,2},
{2,3}
};
Compiler is MSVC 17.2, C++20 mode on.
I can live with option B, but I would like to learn what exactly am I failing to understand in option A in terms of C++ knowledge.
| std::array is a class that contains an actual array. It looks something like this:
template <typename T, size_t N>
struct array
{
T _unspecified_name[N];
// Member functions.
};
Note that std::array has no constructors or private data members, so it is an aggregate.
When you brace-initialize a std::array you're doing aggregate initialization of a class with one member that is itself an aggregate. Normally that would require two sets of braces:
// Braces for std::array
// │ │
// ▼ ▼
std::array<int, 2> arr = { {1, 2} };
// ▲ ▲
// │ │
// Braces for int[2] member
C++ has brace-elision rules to make this situation nicer though. You can omit the inner set of braces, and the initializers will "pass through" to underlying member objects that are themselves aggregates. In this case that's the std::array's int[2] member.
This is the root of your issue. When you initialize an array of My_Struct using braces, the compiler thinks you intended the inner set of braces to initialize the std::array's My_Struct[] member rather than the My_Struct within. Since there are two initializers when it was expecting only one it throws an error:
// Initializer for std::array
// │ │
// ▼ ▼
std::array<My_Struct, 2> my_array = { {1, 2}, {2, 3} };
// ▲ ▲ ▲ ▲
// │ │ │ │
// Initializer for unnamed My_Struct[2] │ │
// What is this initializer for? I only have one member to initialize
To avoid this situation you just need to add another set of braces:
// ┌ Initializer for std::array ┐
// │ │
// ▼ ▼
std::array<My_Struct, 2> my_array = { { {1, 2}, {2, 3} } };
// ▲ ▲ ▲ ▲ ▲ ▲
// | │ │ │ │ │
// | |Initializers│ │
// | For array elements │
// | |
// Initializer for unnamed My_Struct[2]
|
72,253,644 | 72,253,805 | I want to Display all the strings in my queue | This is my code , I want to display all I put on tail and Head in this c++ program. I want the program display all the queue elements when I click displayAll(). I edited the code, by adding the full details of the code. Not idea to show all elements in the queue , I able to see the size of the queue but not the elements with they string like a table. I do not know if that is possible.
class Node {
public:
string name;
string gender;
string birthDate;
string SSN;
Node* next;
Node(string name, string gender,string birthDate,string SSN) {
this->name = name;
this->gender = gender;
this->birthDate = birthDate;
this->SSN = SSN;
next = NULL;
}
};
class Queue {
private:
Node* head;
Node* tail;
int size;
public:
Queue() {
head = NULL;
tail = NULL;
size = 0;
}
int getSize() {
return size;
}
bool isEmpty() {
return size == 0;
}
void addPatient() {
string name;
string gender;
string birthDate;
string SSN;
Node* next;
cout << "Enter Patient name: ";
cin >> name;
cout << "Enter patient gender: ";
cin >> gender;
cout << "Enter patient birth date: ";
cin >> birthDate;
cout << "Enter patient SSN: ";
cin >> SSN;
Node* n = new Node(name, gender, birthDate, SSN);
if (head == NULL) {
head = n;
tail = n;
}
else {
tail->next = n;
tail = n;
}
size++;
}
void showFront() {
if (isEmpty()) {
return;
}
cout << "Name: "+ head->name << "\n" << "Gender: "+ head->gender << "\n" << "Birth Date: " + head->birthDate << " \n" <<"SSN: "+ head->SSN << "\n";
}
void showLast() {
if (isEmpty()) {
return;
}
cout << "Name: " + tail->name << "\n" << "Gender: " + tail->gender << "\n" << "Birth Date: " + tail->birthDate << " \n" << "SSN: " + tail->SSN << "\n";
}
void displayAllPatients() {
cout << "Patients are: " << "\n";
}
| A simple loop like this will do:
void displayAllPatients() {
cout << "Patients are: " << "\n";
auto p = head;
while(p) {
cout << p->name << "\n";
p = p->next;
}
}
or
for(auto p = head; p; p = p->next) {
cout << p->name << "\n";
}
|
72,253,869 | 72,254,000 | Shouldn't there be a copy ctor invocation here? Elision disabled (no named return value optimization) | struct Test {
int field = 30;
Test() { cout << "In ctor" << endl; }
Test(const Test &other) { field = other.field; cout << "In copy ctor" << endl; }
Test(Test &&other) { field = other.field; cout << "In move ctor" << endl; }
Test &operator=(const Test &other) { field = other.field; cout << "In copy assignment" << endl; return *this; }
Test &operator=(Test &&other) { field = other.field; cout << "In move assignment" << endl; return *this; }
~Test() { cout << "In dtor" << endl; }
};
Test get_test() {
Test t;
return t;
}
int main() {
Test t2 = get_test();
}
I think this is the canonical NRVO example. I'm compiling with -fno-elide-constructors and I see that the following are called: ctor, move ctor, dtor, dtor.
So the first ctor call corresponds to the line Test t;, the move ctor is constructing the t2 in main, then the temporary that is returned from get_test is destroyed, then the t2 in main is destroyed.
What I don't understand is: shouldn't there be a copy ctor invocation when returning by value? That is, I thought that get_test should be making a copy of t and then this copy is moved into t2. It seems like t is moved into t2 right away.
| C++17
Starting from C++17, there is mandatory copy elison which says:
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:
(emphasis mine)
This means that t2 is constructed directly from the prvalue that get_test returns. And since a prvalue is used to construct t2, the move constructor is used. Note that in C++17, the flag -fno-elide-constructors have no effect on return value optimization(RVO) and is different from NRVO.
Pre-C++17
But prior to C++17, there was non-mandatory copy elison and since you've provided the -fno-elide-constructors flag, a temporary prvalue is returned by get_test using the move constructor. So you see the first call to the move ctor. Then, that temporary is used to initialize t2 again using the move constructor and hence we get the second call to the move ctor.
|
72,253,901 | 72,253,947 | Member initialization syntax in C++ constructors | Why does the following not compile?
class A {
public:
A(int a) : a_{a} {}
private:
int a_;
};
|
Why does the following not compile?
Because you're most probably compiling the shown code, with Pre-C++11 standard version.
The curly braces around a in your example, is a C++11 feature.
To solve this you can either compile your program with a C++11(or later) version or use parenthesis () as shown below:
Pre-C++11
class A {
public:
//-------------------v-v--------->note the parenethesis which works in all C++ versions
A(int a) : a_(a) {}
private:
int a_;
};
C++11 & Onwards
class A {
public:
//-------------------v-v------->works for C++11 and onwards but not with Pre-C++11
A(int a) : a_{a} {}
private:
int a_;
};
|
72,254,064 | 72,268,522 | C++ Recursive Maze Solver looping infinitely | I am new to C++ and am trying to write a program that reads a file, dynamically creates a 2D array, and fills the array with input from the file. Then it solves the maze using recursion. The text file looks like this:
The first 4 numbers dictate the amount of rows, amount of columns, and starting position (X,Y). "S" is the start, "O" the path, and "E" the end. I have no trouble with creating the array or filling the array, but when running the program, it encounters an error when calling the recursive function to solve the maze. This is the function:
bool mazeSolve(char **maze, int startRow, int startCol){
char test = maze[startRow][startCol];
//If maze finds end stop program (Base Case)
if (test == 'E'){
cout << "End reached" << endl;
return true;
}//End if for base case
//If function can go right
if (maze[startRow][startCol+1] == 'O'){
maze[startRow][startCol] = 'P';
return mazeSolve(maze, startRow, startCol+1);
}
//If function can go left
if (maze[startRow][startCol-1] == 'O'){
maze[startRow][startCol] = 'P';
return mazeSolve(maze, startRow, startCol-1);
}
//If function can go up
if (maze[startRow-1][startCol] == 'O' && startRow-1 >= 0){
maze[startRow][startCol] = 'P';
return mazeSolve(maze, startRow-1, startCol);
}
//If function can go down
if (maze[startRow+1][startCol] == 'O'){
maze[startRow][startCol] = 'P';
return mazeSolve(maze, startRow+1, startCol);
}
//If function cannot find O's then it will backtrack
//If function reaches wall, backtrack down
if (maze[startRow+1][startCol] == 'P'){
maze[startRow][startCol] = 'C';
return mazeSolve(maze, startRow+1, startCol);
}
//If function reaches wall, backtrack up
if (startRow-1 >= 0 && maze[startRow-1][startCol] == 'P'){
maze[startRow][startCol] = 'C';
return mazeSolve(maze, startRow-1, startCol);
}
//If function reaches wall, backtrack left
if (maze[startRow][startCol-1] == 'P'){
maze[startRow][startCol] = 'C';
return mazeSolve(maze, startRow, startCol-1);
}
//If function reaches wall, backtrack right
if (maze[startRow][startCol+1] == 'P'){
maze[startRow][startCol] = 'C';
return mazeSolve(maze, startRow, startCol+1);
}
I have googled and searched this site for similar problems but I seem to have a fundamental misunderstanding of recursion as I can't follow the solutions. I thought the bottom half would allow the function to backtrack until it found a new "O" and eventually an "E", but it is looping infinitely. My professor is asking for this to be done with if statements. Where did my logic go wrong? Any help would be greatly appreciated.
| I figured it out after some debugging. Rewrote the function from scratch. Thank you for everyone for your help. I added an out of bounds check and added a condition for the if statements to check for both 'O' and 'E'. Weirdly the backtracking if statements remained the same, even though I thought they were the issue.:
bool mazeSolve(char **maze, int startRow, int startCol){
//Output test message
char test = maze[startRow][startCol];
//cout << test << endl;
//If maze finds end stop program (Base Case)
if (test == 'E'){
cout << "End reached" << endl;
return true;
}//End if for base case
//Out of bounds check
if (startRow < 0 || startCol < 0 || startRow >= arrayRowSize ||
startCol >= arrayColSize){
cout << "bounds error";
return false;
}//End out of bounds if
//If function can go down
if (maze[startRow+1][startCol] == 'O' || maze[startRow+1][startCol] == 'E'){
maze[startRow][startCol] = 'P';
//cout << "down" << endl;
return mazeSolve(maze, startRow+1, startCol);
} //End down if
//If function can go right
if (maze[startRow][startCol+1] == 'O' || maze[startRow][startCol+1] == 'E'){
maze[startRow][startCol] = 'P';
//cout << "right" << endl;
return mazeSolve(maze, startRow, startCol+1);
} //End right if
//If function can go left
if (maze[startRow][startCol-1] == 'O' || maze[startRow][startCol-1] == 'E'){
maze[startRow][startCol] = 'P';
//cout << "left" << endl;
return mazeSolve(maze, startRow, startCol-1);
} //End left if
//If function can go up
if (maze[startRow-1][startCol] == 'O' || maze[startRow-1][startCol] == 'E'){
maze[startRow][startCol] = 'P';
//cout << "right" << endl;
return mazeSolve(maze, startRow-1, startCol);
} //End up if
//If function cannot find O's then it will backtrack
//If function reaches wall, backtrack down
if (maze[startRow+1][startCol] == 'P'){
maze[startRow][startCol] = '*';
return mazeSolve(maze, startRow+1, startCol);
} //End backtrack down if
//If function reaches wall, backtrack up
if (maze[startRow-1][startCol] == 'P'){
maze[startRow][startCol] = '^';
return mazeSolve(maze, startRow-1, startCol);
} //End backtrack up if
//If function reaches wall, backtrack left
if (maze[startRow][startCol-1] == 'P'){
maze[startRow][startCol] = '<';
return mazeSolve(maze, startRow, startCol-1);
} //End backtrack left if
//If function reaches wall, backtrack right
if (maze[startRow][startCol+1] == 'P'){
maze[startRow][startCol] = '>';
return mazeSolve(maze, startRow, startCol+1);
//End backtrack right if
} else
return false;//If all else fails, maze is unsolvable
}
This solves the maze. My only issue now is error handling if the maze does not have an end. I edited the txt file to have no "E", and the function loops infinitely. I thought the final "else" statement would cover this, but it doesn't. What should I have done to handle the case of an unsolvable maze?
|
72,254,293 | 72,254,361 | How can I solve this weird error while using map in c++ | I'm getting stuck in a weird infinite loop while using map in c++.
The first code works good and outputs numbers.
The test cases are:
5 2
1 2 3 4 5
long long N, K, count = 0;
cin>>N>>K;
long long l;
map<long long, long long> mp;
for(int i = 0; i<N; i++){
cin>>l;
++mp[l];
}
for(auto a:mp){
cout<<a.first + K<<" "<<a.first - K;
}
For the next code I'm getting stuck into an infinite loop, for the same test case, don't know why?
long long N, K, count = 0;
cin>>N>>K;
long long l;
map<long long, long long> mp;
for(int i = 0; i<N; i++){
cin>>l;
++mp[l];
}
for(auto a:mp){
cout<<mp[a.first + K]<<" "<<mp[a.first - K];
}
The last code keeps on printing 0 till an infinite loop. Any idea why?
| The problem is that if the key is not found inside the map, a key-value pair will automatically be created and inserted into the map and so you're changing the size of the map while iterating it leading to undefined behavior.
Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash.
You can use std::map::at member function which will throw std::out_of_range exception when the key is not already inside the map, to confirm that some keys whose corresponding value you're looking for are not inside the map.
How can I solve this weird error while using map
To solve this make sure, that you don't change the size of the map while iterating it.
|
72,255,074 | 72,255,209 | Question marks in wildcard search in Windows | I am using wildcard characters (? and *) to search for files in Windows in a c++ program with _tfindfirst64 and _tfindnext64. I observed the following code
TCHAR root[1024] = L"C:/testData/?????_?????.jpg";
_tfinddata64_t c_file;
intptr_t hFile = _tfindfirst64(root, &c_file);
do
{
wcout << c_file.name << endl;
} while (_tfindnext64(hFile, &c_file) == 0);
_findclose(hFile);
picks up the following files:
12345_---.jpg
12345_12.jpg
12345_12345.jpg
But I was expected the filter would accept only the last one as it means: "5 arbitrary chars followed by '_' followed by another chars with '.jpg'" as described. What would be the correct way to do it?
| As you've found, a ? in a file search doesn't require a character to be present, but matching will fail if a character is present that your search string doesn't account for. For example, foo?.txt will match foo.txt, foo1.txt, fooa.txt, and so on, but will not match foo10.txt or foo_abc.txt.
About the only way I know of to work around this is to re-check the result afterward to assure you eliminate any unwanted matches. In this case, it sounds like just comparing the length of the filename with what you expect will suffice.
|
72,255,609 | 72,255,924 | std::unordered_map insert invalidates only iterators but not references and pointers to the element node | Can somebody explain why insertion into std::unordered_map container only invalidates iterators but not references and pointers. Also I am not able to understand what the below statement from https://en.cppreference.com/w/cpp/container/unordered_map/insert mean
If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid.
| Insertion of unordered_map doesn't invalidate references because it doesn't move the data, however the underlying data structure might change rather significantly. Details of how exactly it is implemented aren't specified and different compilers do it differently. For instance, MSVC has a linked list for data storage and, I believe, a vector for the look-up. And insert can cause rehash, meaning look-up gets changed completely and the linked list gets reorded significantly - but original data is not moved.
The iterators refer to this underlying structure and any changes to it can cause iterators to invalidate. Basically, they contain more info than pointers and references and subsequently can get invalidated.
The confusing passage is about insert of a node_type - nodes that were previously extracted. Checkout the method unordered_map::extract
https://en.cppreference.com/w/cpp/container/unordered_map/extract
For some reason it is forbidden to use pointers/references while the node is extracted. After inserting it is allowed to use them again. I don't know why it is so.
|
72,255,969 | 72,328,088 | Fastest way of resizing (rescaling) a 1D vector by an arbitrary factor | I have the following code that does the resizing of a 1D vector with nearest neighbor interpolation in a similar fashion you'd also resize an image. Another term would be resampling, but there seems to be a lot of confusion around these terms (resampling is also a technique in statistics), so I prefer to be more descriptive.
Currently the code looks like this and I need to optimize it:
inline void resizeNearestNeighbor(const int16_t* current, uint32_t currentSize, int16_t* out, uint32_t newSize, uint32_t offset = 0u)
{
if(currentSize == newSize)
{
return;
}
const float scaleFactor = static_cast<float>(currentSize) / static_cast<float>(newSize);
for(uint32_t outIdx = 0; outIdx<newSize; ++outIdx)
{
const int currentIdx = static_cast<uint32_t>(outIdx * scaleFactor);
out[outIdx] = current[(currentIdx + offset)%currentSize];
}
}
This of course is not hugely efficient because the operation to take the integer part of a float by downcasting is expensive and I don't think it can take any benefit of vectorization in this case. The platform is Cortex M7, so if you're familiar with any vectorization techniques on this platform, it would be also very helpful.
The use case of this code is a sound effect that allows for smoothly changing the length of a delay line (hence the additional offset parameter, since it's a ring buffer). Being able to smoothly change the length of a delay line sounds like slowing down or speeding up playback in a tape recorder, only it's in a loop. Without this scaling, there are lots of clicking noises and artifacts. Currently the hardware struggles with all the DSP and this code on top of that and it can't rescale long delay lines in real time.
| Since the Cortex-M series is quite limited (even floating point in M7 is optional), I would estimate a reasonable speed-up coming from using Bresenham's mid point line drawing algorithm.
This algorithm always advances either N or N+1 elements based on the sign of the error term. The modulus does not need full length division: it suffices to compute currentIdx += N + (delta < 0); if (currentIdx >= currentSize) currentIdx -= currentSize;
One can also make a "trial divisions" in form of if (currentIdx + 64 * (N+1) < currentSize) to ensure that the next 64 elements do not need modular reduction. M7 has a multiplication unit, but multiplying by shifting is still likely a faster micro-optimisation.
The Bresenham's algorithm for line drawing is of form
plotLine(x0, y0, x1, y1)
dx = x1 - x0
dy = y1 - y0
D = 2*dy - dx
y = y0
for x from x0 to x1
plot(x,y)
if D > 0
y = y + 1
D = D - 2*dx
end if
D = D + 2*dy
Your application does not have x0,x1,y0,y1, but instead it has directly dy = input_size, dx = output_size.
resample(dx, dy)
N = dy/dx
dy = dy % dx
D = 2*dy - dx;
y = offset;
for x from 0 to dx-1
out[x] = in[y]
y += N
if D > 0
y = y + 1
D = D - 2*dx
end if
D = D + 2*dy
if (y >= currentSize)
y -= currentSize
The crucial modification to advance y by N>0 steps is to dy = dy % dx to get the error computation correct.
One can also use slightly less accurate fixed point DDA algorithm with
int scale = 65536 * newSize / currentSize;
int y = offset << 16;
for (int x = 0; x < newSize; x++) {
out[x] = in[y >> 16];
y += scale;
if (y >= (currentSize << 16))
y -= (currentSize << 16);
}
|
72,256,050 | 72,256,571 | Does std::mutex enforce cache cohesion? | I have a non-atomic variable my_var and an std::mutex my_mut. I assume up to this point in the code, the programmer has followed this rule:
Each time the programmer modifies or writes to my_var, he locks
and unlocks my_mut.
Assuming this, Thread1 performs the following:
my_mut.lock();
my_var.modify();
my_mut.unlock();
Here is the sequence of events I imagine in my mind:
Prior to my_mut.lock();, there were possibly multiple copies of my_var in main memory and some local caches. These values do not necessarily agree, even if the programmer followed the rule.
By the instruction my_mut.lock();, all writes from the previously executed my_mut critical section are visible in memory to this thread.
my_var.modify(); executes.
After my_mut.unlock();, there are possibly multiple copies of my_var in main memory and some local caches. These values do not necessarily agree, even if the programmer followed the rule. The value of my_var at the end of this thread will be visible to the next thread that locks my_mut, by the time it locks my_mut.
I have been having trouble finding a source that verifies that this is exactly how std::mutex should work. I consulted the C++ standard. From ISO 2013, I found this section:
[ Note: For example, a call that acquires a mutex will perform an
acquire operation on the locations comprising the mutex.
Correspondingly, a call that releases the same mutex will perform a
release operation on those same locations. Informally, performing a
release operation on A forces prior side effects on other memory
locations to become visible to other threads that later perform a
consume or an acquire operation on A.
Is my understanding of std::mutex correct?
| C++ operates on the relations between operations not some particular hardware terms (like cache cohesion). So C++ Standard has a happens-before relationship which roughly means that whatever happened before completed all its side-effects and therefore is visible at the moment that happened after.
And given you have an exclusive critical session to which you have entered means that whatever happens within it, happens before the next time this critical section is entered. So any consequential entering to it will see everything happened before. That's what the Standard mandates. Everything else (including the cache cohesion) is the implementation's duty: it has to make sure that the described behavior is coherent with what actually happens.
|
72,256,233 | 72,413,140 | C++ Drogon framework model-based ORM | I've began to learning C++ Drogon framework. I read the official and unofficial documents about the Drogon ORM. But I couldn't realized how can I create a model-based ORM database.
I want to create my models then run a migration command to map models to database tables.
If there is any document and guide about Drogon model-based ORM please let me know.
Thank you.
| You can use
drogon::app().loadConfigFile("../config-name.json");
then run your sql command under drogon plugins after the program run. It's also will shutdown your custom plugin after the program exit.
It's require config files, where you can add your plugin on config-name.json.
steps:
1. create plugins
You can run from drogon_ctl create plugin <[namespace::]class_name> or create it manually.
Assume that your project root name is MyProject and says that your plugin class_name is my_plugin_01.
Do note that you also need to add both files to cmake add_executable.
add_executable(${PROJECT_NAME} "main.h" "main.cc"
...
"controllers/foo.h" "controllers/foo.cc"
"filters/bar.h" "filters/bar.cc"
...
"plugins/my_plugin_01.h" "plugins/my_plugin_01.cc")
2. add your plugin name to drogon loadConfigFile, which is config-name.json
{
"listeners": [
// your list of addresses and ports
],
...
// some of your config and so on
...
"plugins": [
{
"name": "MyProject::plugins::my_plugin_01",
"dependencies": [],
"config":
{
}
}
]
}
3. inside of my_plugin_01
my_plugin_01.h
#pragma once
#include <main.h>
#include <drogon/plugins/Plugin.h>
namespace MyProject
{
namespace plugins
{
class my_plugin_01 : public drogon::Plugin<my_plugin_01>
{
public:
my_plugin_01() {}
// This method must be called by drogon to initialize and start the plugin.
// It must be implemented by the user.
virtual void initAndStart(const Json::Value &config) override;
// This method must be called by drogon to shutdown the plugin.
// It must be implemented by the user.
virtual void shutdown() override;
};
} // namespace plugins
} // namespace MyProject
my_plugin_01.cc
#include "my_plugin_01.h"
using namespace drogon;
void MyProject::plugins::my_plugin_01::initAndStart(const Json::Value &config)
{
// Initialize and start the plugin
// Do your sql logic.
// Help: https://drogon.docsforge.com/master/database-general/database-dbclient/#execsqlasyncfuture
// log to console when DEBUG is true
if (MyProject::main::DEBUG)
{
std::cout << "\nPLUGIN INITIALIZE: my_plugin_01::initAndStart()\n\n";
}
}
void MyProject::plugins::my_plugin_01::shutdown()
{
// Shutdown the plugin
// Do your logic.
// log to console when DEBUG is true
if (MyProject::main::DEBUG)
{
std::cout << "\nPLUGIN SHUTDOWN: my_plugin_01::shutdown()\n\n";
}
}
Each time drogon::app().run(); your plugin/s will be initialze and terminate when program exit.
Another solution is use another framework/library from another programming language (e.g. dotnet, django and etc.)
You can do migration, create table and more from that framework/library.
This approach kinda neat but a bit complicated. Just be aware with your hardware resources.
Do this if you want to extend your logic, where heavy/intense workload use c++ and when some logic can not be achieved with c++, use another one.
|
72,256,636 | 72,275,688 | Connect QTimer with a Slot with parameters | I tried the following:
connext(&timer, &QTimer::timeout, this, &myClass::myMethod(_param1, _param2)); // does not work
timer.setSingleShot(true);
timer.start(100);
The timer of type QTimer is a member element of the class.
Is there a way to connect the timeout() signal of a timer to a method with multiple parameters?
| The QTimer's timeout signal void timeout() does - on its own - not have enough parameters to call myClass::myMethod(_param1, _param2); (where exactly should timeout take _param1 & _param2 from?)
You can either use a lambda function:
//assuming you have _param1 & _param2 as variables before this point
connect(&timer, &QTimer::timeout, this, [=]() { myMethod(_param1, _param2); });
timer.setSingleShot(true);
timer.start(100);
One thing to note is that by using this as the receiver object for connect() you tie the lifetime of the connection to both the lifetime of the timer AND of the currect object (this), which should ensure that the connection is properly destroyed if one of the two objects dies and the lambda (with its implicit call to this->myMethod()) is not executed after this is deallocated.
Or you could create a void myClass::handleTimeout() function in your class, connect the timeout of the time to it as slot and there call myMethod(_param1, _param2)
void myClass::handleTimeout()
{
//assuming _param1 & _param2 are variables accessible in handleTimeout()
myMethod(_param1, _param2));
}
//Your original function...
void myClass::someFunction()
{
//...
connect(&timer, &QTimer::timeout, this, &myClass::handleTimeout);
timer.setSingleShot(true);
timer.start(100);
//...
}
|
72,256,657 | 72,257,172 | Do I pass the wrong data to glTexImage2D? | I'm trying to make an OpenGL texture by populating a pixel buffer with data from a baked font. I'm taking each value from the font array and making a bitmap essentially.
The problem is when I'm displaying the full texture I get noise. However by creating an 8x8 texture of one glyph the texture is displayed correctly.
The pixel buffer is 8bit monochrome, so I pass GL_ALPHA as buffer format.
I tried using 32bpp GL_RGBA format as well and it yields the same result.
DebugFont
LoadBakedFont(void)
{
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
unsigned char baked_font[128][8] = {} //In my source code this is not empty :)
unsigned char *pixels = (unsigned char*)malloc(sizeof(unsigned char) * 128 * 8 * 8);
memset(pixels, 0, sizeof(unsigned char) * 128 * 8 * 8);
int counter = 0;
for(int i = 0; i < 128; ++i)
{
for(int j = 0; j < 8; ++j)
{
for(int k = 0; k < 8; ++k)
{
unsigned char val = (baked_font[i][j] >> k & 1);
pixels[counter++] = val == 1 ? 0xff : 0x00;
}
}
}
//Renders the exlamation mark perfectly
for(int y = 0; y < 8; ++y)
{
for(int x = 0; x < 8; ++x)
{
unsigned char *test = pixels + (0x21 * 64);
if(test[y * 8 + x])
printf("@");
else
printf(".");
}
printf("\n");
}
//POD struct
DebugFont font;
glGenTextures(1, &font.tex);
glBindTexture(GL_TEXTURE_2D, font.tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 8 * 128, 8, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
glBindTexture(GL_TEXTURE_2D, 0);
free(pixels);
return font;
}
void
DrawTexture(DebugFont font)
{
glBindTexture(GL_TEXTURE_2D, font.tex);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(0,0);
glTexCoord2f(1.0f, 0.0f); glVertex2f(8 * 128,0);
glTexCoord2f(1.0f, 1.0f); glVertex2f(8 * 128, 8);
glTexCoord2f(0.0f, 1.0f); glVertex2f(0, 8);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
}
Random noise?
Exclamation Mark
| The way you arrange the data makes sense for a tall 8x1024 image where each 8x8 makes up a character.
But you load it as a 1024x8 image instead, putting all the pixels in the wrong places.
|
72,256,729 | 72,256,803 | MSVC - expression must have pointer-to-object type but it has type "float" on generic array? | MSVC on Visual Studio 2019 says "expression must have pointer-to-object type but it has type "float" on generic array" here:
void _stdcall sample::Eff_Render(PWAV32FS SourceBuffer, PWAV32FS DestBuffer, int Length)
{
float gain = _gain;
for (int ii = 0; ii < Length; ii++)
{
(*DestBuffer)[ii][0] = (*SourceBuffer)[ii][0] * gain;
(*DestBuffer)[ii][1] = (*SourceBuffer)[ii][1] * gain;
}
}
the problem seems here:
(*DestBuffer)[ii][0] = (*SourceBuffer)[ii][0] * gain;
(*DestBuffer)[ii][1] = (*SourceBuffer)[ii][1] * gain;
Not sure why:
typedef float TWAV32FS[2];
typedef TWAV32FS *PWAV32FS;
Some flag to be disabled? On gcc this kind of "cast" seems auto-manage by the compiler.
What's the correct way to manage this? (maybe I'm wrong on gcc and didn't know...)
| Change this:
(*DestBuffer)[ii][0] = (*SourceBuffer)[ii][0] * gain;
(*DestBuffer)[ii][1] = (*SourceBuffer)[ii][1] * gain;
To this:
DestBuffer[ii][0] = (SourceBuffer[ii][0]) * gain;
DestBuffer[ii][1] = (SourceBuffer[ii][1]) * gain;
Explanation:
(I'm guessing you are doing audio processing of a stereo signal in floating point).
DestBuffer and SourceBuffer are both arrays of samples. Each sample is a pair of floats.
Each sample is referenced like this:
DestBuffer[ii]
Each individual channel on a sample is referenced like this:
DestBuffer[ii][0]
DestBuffer[ii][1]
The error you have with this syntax:
(*DestBuffer)[ii][0]
Is that *DestBuffer is really the same as DestBuffer[0], or the first sample in the array. So (*DestBuffer)[ii] is the same as DestBuffer[0][ii] which is not what you want anyway. But (*DestBuffer)[ii][0] is the same as DestBuffer[0][ii][0] - which triggers the compiler error because that third dimension does not exist.
Having done some audio processing code before - don't forget to clamp the result of your multiplication with gain as appropriate.
|
72,256,841 | 72,257,071 | Are constraints in overload resolution affected by difference it type qualifiers? | Having the following simple code:
#include <concepts>
auto f(const auto&) { }
auto f(std::integral auto) {}
int main()
{
f(5);
}
We have an ambiguous call with clang & gcc but MSVC chooses the more constrained one. So far I found nothing that would support the clang's & gcc's behavior. So is it a bug in both compilers or there is something that makes this call ambiguous?
| Without considering constraints, the call is ambiguous because the first overload is deduced to a function parameter type const int& and the second to int. Neither will be considered better than the other when called with a prvalue of type int and neither const auto& or auto are more specialized in usual partial ordering of templates either.
According to [temp.func.order]/6.2.2 constraints on function templates are not taken into account if the types of the function parameters after substitution from template argument deduction do not correspond.
Here the first overload deduced the function parameter to const int& and the second to int. These are not equal. And so partial ordering of the templates will not consider either more specialized than the other based on any constraints either.
|
72,256,844 | 72,257,083 | Rotation of square by center using rotation matrix | I'm trying to rotate a square using rotation matrix with this implementation.
void Square::rotateVertices(std::vector<float> &vertices)
{
float px = (vertices[0]+vertices[2])/2;
float py = (vertices[1]+vertices[5])/2;
for (int i = 0; i < 4; i++)
{
float x1 = vertices[i*2];
float y1 = vertices[i*2+1];
vertices[i * 2] = px + (x1 -px)*cos(angle) - (y1 -py)*sin(angle);
vertices[(i * 2) + 1] = py + (x1 -px)*sin(angle) + (y1 -py)*cos(angle);
}
}
Vertices are calculated using code below:
float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);
std::vector<float> vertices = {
2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height)) - ay + 1.0f,
2 * (((x) - float(width) / 2) / float(width)) + ax, 2 * ((y - float(height)) / float(height)) - ay + 1.0f,
2 * (((x) - float(width) / 2) / float(width)) + ax, 2 * ((y - float(height)) / float(height)) + ay + 1.0f,
2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height)) + ay + 1.0f};
rotateVertices(vertices);
where:
width - window width
height - window height
size - size of square
After calculation square looks normal for angle=0, but when I've checked ie. angle=M_PI/4 which should rotate square 45 degrees, rotation applies with strange transformation of square to rectangle.(as shown in pictures)
Of course I would love to have the proportions kept, but I cannot think of the solution at the moment. If anybody could think of fast fix, or could point me in the correct direction I would be pleased.
| That's because your square is a rectangle. My crystal ball knows this because its width and height are calculated separately, and therefore, you meant for them to be different:
// if you wanted these to be the same you wouldn't calculate them separately
float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);
The only reason it looks like a square is because the screen projection is also distorted to cancel it out.
When you rotate the rectangle they no longer cancel out.
You should draw a square with the same width and height, and then fix the matrices that convert the square into screen coordinates, so that when you render something with the same width and height it does get the same width and height on the screen.
|
72,257,744 | 72,265,498 | dx12) It takes too long to compile Shader |
When profiling, it took about 14 seconds only for shader compile. (Although it took only 7 seconds to load all that obj files.)
how can I optimize this? do I have any option to pre-compile hlsl shaders?
| The recommendation is in fact to compile the shaders off-line (at build time) and then load the resulting binary shader blob at runtime.
You can use the built-in Visual Studio HLSL integration which will generate .cso files (Compiled Shader Object). See Microsoft Docs for details. For notes on using Shader Model 6 DXC with VS, see this page.
You can use a batch script to invoke FXC or DXC from the command-line, and use that as part of a VS custom build or CMake custom targets. See DirectX Tool Kit's CompileShaders.cmd and this tutorial.
You will need a new ctor for your shader classes listed in the code snippet above that take the shader binary blob directly instead of a string to the HLSL source to compile.
For Win32 desktop applications, you need to handle the fact that your .cso files will end up next to your built EXE instead of where you have your project CWD set. See ReadData for an example of this. For UWP and Xbox apps, the .cso files are placed into the appx package automatically.
From your question, it's not clear if you are using the legacy FXC.EXE compiler with Shader Model 5.1 or the current DirectX 12 shader DXC.EXE for Shader Model 6. Still the same advice applies here. FWIW, the DXC compiler is LLVM based so it's a bit more complex and therefore does more analysis than the legacy FXC compiler did.
|
72,257,925 | 72,258,036 | using a class n times with a for loop c++ | I'm trying to learn classes, so here I want to create n-number Triangle and Rectangle types, input a,b,c, also input from user and then cout them.. im trying to get n-number of Triangle and Rectangle with for loop but at the end I get print only the biggest S() and P() which user had entered.. for example if I user says n=2 so there will be 2 Triangles and 2 Rectangles .. Rectangle a1 = 1, b1 = 2; Rectangle a2 = 3, b2 = 4.. ill get s() output s = 12 and again s = 12 instead of s = 2 and s = 12
enter image description here
Im sorry for the worst description ever ..
class Rectangle
{
protected:
int a, b;
virtual double S()
{
return a*b;
}
virtual double P()
{
return (2*a) + (2*b);
}
public:
Rectangle (int aa, int bb) {a = aa; b = bb;}
virtual void Input()
{
cout << " enter a: "; cin >> a;
cout << " enter b: "; cin >> b;
cout << endl;
}
virtual void Print()
{
cout << " Rectangle S = " << S() << endl;
cout << " Rectangle P = " << P() << endl;
cout << endl;
}
};
int main()
{
int n;
cout << " enter number of triangles and rectangles... "; cin >> n;
cout << endl;
Rectangle rectangle(1, 1);
Triangle triangle(1,1,1);
for (int i=0; i<n; i++)
{
rectangle.Input();
}
for (int i=0; i<n; i++)
{
rectangle.Print();
}
| You are overwriting the same variable every time you call Input(). Instead, create a vector of rectangles.
#include <vector>
class Rectangle {
// ...
};
int main()
{
// ...
std::vector<Rectangle> rectangles(n);
for (int i=0; i<n; i++)
{
rectangles[i].Input();
}
for (int i=0; i<n; i++)
{
rectangles[i].Print();
}
}
You need to add a default constructor for Rectangle so that you can use it with vector.
For example:
Rectangle() { a = 0; b = 0; }
Rectangle(int aa, int bb) {a = aa; b = bb;}
|
72,258,278 | 72,259,561 | Catch dll function that does not return | i do have to use a .dll library in order to have access to hardware i want to control.
The problem is, that some functions of that dll sometimes do not return. They seem to be stuck in an infinite loop or something.
My idea was to run the function calls in a different thread and kill the thread if it is stuck/does not return after some time.
In Order to do that i wrote something like that:
template<typename... multiple>
void MyClass::genericCommandHandler(void *function, multiple... args)
{
//timer start --> check somewhere else
std::thread t{&MyClass::threadWorker<void(*)(...)>, function, args...};
t.join();
}
But it does not compile: error C2672: 'std::invoke': no matching overloaded function found
And another Problem is that std::thread does not have a kill or stop function.
Does anyone have a good idea on how to deal with a dll that does not return?
| Isolating the DLL in its own thread does not really help a lot, but the idea makes sense. It might be better to isolate the DLL in its own helper process. You would then terminate the entire helper process.
This is by necessity not a clean exit. That is inherent in the problem. You don't know how the DLL corrupted internal state. That is why the helper process exists: to avoid mingling DLL state and your state.
The C++ Standard way to mange subprocesses is std::system, but that has the same problem with control. You'll need the native CreateProcess.
As a shotgun method, you could try CancelSynchronousIo on the DLL's thread.
|
72,258,758 | 72,258,912 | Anyone can tell me why it is giving runtime error | Question Link: LeetCode, I am getting runtime error but not found where it is causing. why it is giving runtime error any one can explain me. Thanks in advance.
class Solution {
public:
bool dfs(vector<vector<int>>& grid, int row, int col, int color)
{
if(row<0 || col<0 || row>=grid.size() || col>=grid[0].size() || abs(grid[row][col])!=color)
return false;
grid[row][col]=-color;
bool first = dfs(grid, row-1, col, color);
bool second = dfs(grid, row, col+1, color);
bool third = dfs(grid, row+1, col, color);
bool fourth = dfs(grid, row, col-1, color);
if(first && second && third && fourth)
{
grid[row][col]=color;
}
return true;
}
vector<vector<int>> colorBorder(vector<vector<int>>& grid, int row, int col, int color) {
dfs(grid, row, col, grid[row][col]);
for(int i=0; i<grid.size(); i++)
{
for(int j=0; j<grid[0].size(); j++)
{
if(grid[i][j]<0)
grid[i][j]=color;
}
}
return grid;
}
};
| I've wrote test for your code: https://godbolt.org/z/TazozK8xe and enabled address sanitizer.
Without reading your code and just by reading sanitizer logs you can see you have infinitive recursion (note number of stack frames is more then 178, when problem is simple to do it in maximum 4 steps). Basically your condition to stop recursion is wrong or incomplete.
I recommend you to learn how to use debugger so you can easier understand this issue.
|
72,258,791 | 72,258,873 | How to pass vector of vector as default argument in functions, C++ | IDE showing error at last argument. I am new in C++ and unable to figure it out.
Please help. Thanks in advance.
void Box_2(vector<vector<int>> &v,
string text1 = "",
string text2 = "",
vector<vector<int>> &trace = {}
)
| The problem is that we cannot bind an lvalue reference to a non-const object to a temporary of the corresponding type.
For instance,
int &ref = 5; //THIS WILL NOT WORK
const int &REF = 5; //THIS WILL WORK
To solve this error you can make the last parameter name to be an lvalue reference to a const object which is allowed to bound to a temporary as shown below:
void Box_2(vector<vector<int>> &v,
string text1 = "",
string text2 ="",
//---------vvvvv------------------------------------->low level const added here
const vector<vector<int>> &trace = {}
);
Note that with above you won't be able to change name. This is a consequence of adding the low-level const.
You can also just leave off the default arguments altogether as shown below:
void Box_2(vector<vector<int>> &v, string text1, string text2, vector<vector<int>> &trace);
Now you will be able to change the underlying vector to which name is bound.
|
72,259,778 | 72,259,970 | how to store sentences (words) wit h spaces in an single array in cpp dynamically | int main()
{
key[100];
int i = 0, t = 0;
cout << "Enter the Keyword :";
while (t < 3)
{
cin.getline(key, 100);
i++;
t++;
}
cout << key[0] << endl;
}
I used this code. But it returns only a character of the word.Please say how to get a single word in array one by one.
| #include <iostream>
int main()
{
// 3 strings of 100 char max (+1 nullchar)
char key[3][101];
int i = 0;
std::cout << "Enter the Keyword :\n";
while(i < 3) {
std::cin.getline(key[i],100);
i++;
}
for(i = 0; i < 3; ++i) {
std::cout << key[i] << std::endl;
}
return 0;
}
Alternative anwser using C++ vector and string
#include <iostream>
#include <string>
#include <vector>
int main()
{
// array of strings
std::vector<std::string> keyw_list;
// string for temporary operations
std::string keyw;
std::cout << "Enter the Keyword :\n";
while(key_list.size() < 3) {
std::cin >> keyw;
keyw_list.push_back(keyw);
}
for(size_t i = 0; i < keyw_list.size(); ++i) {
std::cout << keyw_list[i] << std::endl;
}
return 0;
}
|
72,260,456 | 72,265,274 | C++ STD libraries in C | as the title suggests I am attempting to mix C and C++ source files in a project.
My project has the following files
.
├── comms
│ ├── can.c
├── config_parsing
│ ├── config_parser.c
│ ├── file_operations.c
├── main.cpp
├── scheduler.c
├── signal_handler.c
├── thread_health.c
└── utilities
├── logger.c
├── ring_buffer.c
├── string_operations.c
├── time_conversions.c
In eclipse this compiles, builds and deploys. I am adding code from a vendor that I cannot share as it is purchased code. They have code for SSL which has .h and .c files. In the header file we have
#include <openssl/err.h>
#include <string>
#include <vector>
In the C file we have many instances of std::vector<unsigned char>, std::string. This does not compile.
I am using a Yocto generated SDK to build my application and I can confirm the appropriate files exist in my include paths
/opt/fsl-imx-fb/5.10-hardknott/sysroots/cortexa7t2hf-neon-poky-linux-gnueabi/usr/include/c++/10.2.0
When looking online I see how to properly include C header files in a C++ application but I cannot seem to find out how to use std::vector in a C file. If needed I can share images of the eclipse compiler/build settings.
The application builds in Ubuntu.
Image to show
|
if you want to provide an answer, I will gladly accept it! The -c c++ option has worked! –
Michael
It is pretty clear that the code in the .c files is C++ code and not C code. This is evidenced by the #include directives you found:
#include <string>
#include <vector>
The compiler front end (e.g. gcc or g++) will try to determine the language to use based on the file extension (e.g. .c --> C and .cpp --> C++).
So, even if we compile with g++ it will still compile as C because of the .c extension (vs. prescanning the content of the file).
So, there are a few remedies:
Rename all .c files that are actually C++ code to .cpp
Add -x c++ to the compiler command line for the affected files to force it to interpret the files as C++ code. This works for either front end: gcc or g++
Ordinarily, (1) would be the chosen method if the files were "owned" by you. That is, fix it the right way once.
If we could convince the 3rd party vendor to do this, that would be best (i.e.) the vendor applies (1).
However, if the vendor won't/can't do this and you/your company renames the files, the problem returns anytime you take in a new version from the vendor.
So, a cleaner (i.e. one time fix) is to do (2) and modify your build/Makefile to add the -x c++
|
72,260,569 | 72,261,477 | Minimal mutexes for std::queue producer/consumer | I have two threads that work the producer and consumer sides of a std::queue. The queue isn't often full, so I'd like to avoid the consumer grabbing the mutex that is guarding mutating the queue.
Is it okay to call empty() outside the mutex then only grab the mutex if there is something in the queue?
For example:
struct MyData{
int a;
int b;
};
class SpeedyAccess{
public:
void AddDataFromThread1(MyData data){
const std::lock_guard<std::mutex> queueMutexLock(queueAccess);
workQueue.push(data);
}
void CheckFromThread2(){
if(!workQueue.empty()) // Un-protected access...is this dangerous?
{
queueAccess.lock();
MyData data = workQueue.front();
workQueue.pop();
queueAccess.unlock();
ExpensiveComputation(data);
}
}
private:
void ExpensiveComputation(MyData& data);
std::queue<MyData> workQueue;
std::mutex queueAccess;
}
Thread 2 does the check and isn't particularly time-critical, but will get called a lot (500/sec?). Thread 1 is very time critical, a lot of stuff needs to run there, but isn't called as frequently (max 20/sec).
If I add a mutex guard around empty(), if the queue is empty when thread 2 comes, it won't hold the mutex for long, so might not be a big hit. However, since it gets called so frequently, it might occasionally happen at the same time something is trying to get put on the back....will this cause a substantial amount of waiting in thread 1?
| As written in the comments above, you should call empty() only under a lock.
But I believe there is a better way to do it.
You can use a std::condition_variable together with a std::mutex, to achieve synchronization of access to the queue, without locking the mutex more than you must.
However - when using std::condition_variable, you must be aware that it suffers from spurious wakeups. You can read about it here: Spurious wakeup - Wikipedia.
You can see some code examples here:
Condition variable examples.
The correct way to use a std::condition_variable is demonstrated below (with some comments).
This is just a minimal example to show the principle.
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <iostream>
using MyData = int;
std::mutex mtx;
std::condition_variable cond_var;
std::queue<MyData> q;
void producer()
{
MyData produced_val = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // simulate some pause between productions
++produced_val;
std::cout << "produced: " << produced_val << std::endl;
{
// Access the Q under the lock:
std::unique_lock<std::mutex> lck(mtx);
q.push(produced_val);
cond_var.notify_all(); // It's not a must to nofity under the lock but it might be more efficient (see @DavidSchwartz's comment below).
}
}
}
void consumer()
{
while (true)
{
MyData consumed_val;
{
// Access the Q under the lock:
std::unique_lock<std::mutex> lck(mtx);
// NOTE: The following call will lock the mutex only when the the condition_varible will cause wakeup
// (due to `notify` or spurious wakeup).
// Then it will check if the Q is empty.
// If empty it will release the lock and continue to wait.
// If not empty, the lock will be kept until out of scope.
// See the documentation for std::condition_variable.
cond_var.wait(lck, []() { return !q.empty(); }); // will loop internally to handle spurious wakeups
consumed_val = q.front();
q.pop();
}
std::cout << "consumed: " << consumed_val << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200)); // simulate some calculation
}
}
int main()
{
std::thread p(producer);
std::thread c(consumer);
while(true) {}
p.join(); c.join(); // will never happen in our case but to remind us what is needed.
return 0;
}
Some notes:
In your real code, none of the threads should run forever. You should have some mechanism to notify them to gracefully exit.
The global variables (mtx,q etc.) are better to be members of some context class, or passed to the producer() and consumer() as parameters.
This example assumes for simplicity that the producer's production rate is always low relatively to the consumer's rate. In your real code you can make it more general, by making the consumer extract all elements in the Q each time the condition_variable is signaled.
You can "play" with the sleep_for times for the producer and consumer to test varios timing cases.
|
72,260,589 | 72,277,992 | If the application has two services to send data messages, How will the messages be casted in onWSM function to obtain message content? | I tried to cast two messages in the onWSM function, one of the message is the accident message from TraCIDemo11p example see link; https://github.com/sommer/veins/blob/master/src/veins/modules/application/traci/TraCIDemo11p.cc and the other message I created myself.Simulation stops when handling of the accident message begins.
void MyClusterApp::onWSM(BaseFrame1609_4* frame)
{
// Your application has received a data message from another car or RSU
// code for handling the message goes here, see TraciDemo11p.cc for examples
joinMessage* wsm = check_and_cast<joinMessage*>(frame);
if (currentSubscribedServiceId == 7)
{
if(wsm->getRecipientAddress() == myId)
{
mClusterMembers.insert(wsm->getSenderId());
}
}
}
void MyClusterApp::onWSM_B(BaseFrame1609_4* frame)
{
accident* wsm = check_and_cast<accident*>(frame);
if (currentSubscribedServiceId == 8)
{
findHost()->getDisplayString().setTagArg("i", 1, "green");
if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getDemoData(), 9999);
if (!sentMessage) {
sentMessage = true;
wsm->setSenderAddress(myId);
wsm->setSerial(3);
for( NodeIdSetIterator it = mClusterMembers.begin(); it != mClusterMembers.end(); it++)
{
wsm->setRecipientAddress((*it));
scheduleAt(simTime() + 2 + uniform(0.01, 0.2), wsm->dup());
}
}
}
}
A runtime error occurred:
check_and_cast(): Cannot cast (veins::accident*) to type 'veins::joinMessage *' -- in module (veins::MyClusterApp) VANETScenario.node[1].appl (id=15), at t=74.797089255834s, event #711255
Launch a debugger with the following command?
nemiver --attach=4377 &
| It seems that MyClusterApp::onWSM() may handle various types of messages. Therefore, I suggest use dynamic_cast to recognize the type of message - it is safe and returns nullptr when a message cannot be cast.
An example of modification:
void MyClusterApp::onWSM(BaseFrame1609_4* frame) {
joinMessage* wsm = dynamic_cast<joinMessage*>(frame);
if (wsm) {
if (currentSubscribedServiceId == 7) {
if(wsm->getRecipientAddress() == myId) {
mClusterMembers.insert(wsm->getSenderId());
}
}
} else {
// frame is not a pointer to joinMessage
}
}
|
72,260,594 | 72,260,714 | c++20 concepts: How can I use a type that may or may not exist? | I have begun a project that makes heavy use of c++20 concepts as a way of learning some of the new c++20 features. As part of it, I have a function template that takes a single argument and operates on it. I wish to have the flexibility to pass types to this function that specify another type that they operate on, but that defaults to something else if that specification doesn't exist.
For example, here is a type that specifies a type that it operates on:
struct has_typedef_t
{
typedef int my_type; //operates on this type
void use_data(const my_type& data) const
{
//do something else
}
};
and one that does not specify a type, but operates on a default type specified elsewhere:
typedef std::string default_type;
struct has_no_typedef_t
{
void use_data(const default_type& data) const
{
//do something
}
};
I have a simple concept that can tell me if any given type has this specification:
template <class T> concept has_type = requires(T t) {typename T::my_type;};
And the function might look something like the following:
template <class T> void my_function(const T& t)
{
//Here I want a default-constructed value of the default
//type if the argument doesn't have a typedef
typename std::conditional<has_type<T>, typename T::my_type, default_type>::type input_data;
t.use_data(input_data);
}
The problem here is that the second template argument is invalid for anything that doesn't specify a type, e.g. has_no_typedef_t. An example program:
int main(int argc, char** argv)
{
has_no_typedef_t s1;
has_typedef_t s2;
// my_function(s1); // doesn't compile:
//'has_no_typedef_t has no type named 'my_type'
my_function(s2); //compiles
return 0;
}
What I am looking for is a replacement for the following line:
typename std::conditional<has_type<T>, typename T::my_type, default_type>::type input_data;
as this is causing the problem. I am aware that I can pull of some tricks using an overloaded function using the concept above and combining decltype and declval, but I am looking for something clean and have not been able to come up with anything. How can I achieve this behavior cleanly?
Below is the full code for the full picture (c++20):
#include <iostream>
#include <type_traits>
#include <concepts>
#include <string>
template <class T> concept has_type = requires(T t) {typename T::my_type;};
struct has_typedef_t
{
typedef int my_type;
void use_data(const my_type& data) const
{
//do something
}
};
typedef std::string default_type;
struct has_no_typedef_t
{
void use_data(const default_type& data) const
{
//do something else
}
};
template <class T> void my_function(const T& t)
{
//Here I want a default-constructed value of the default
//type if the argument doesn't have a typedef
typename std::conditional<has_type<T>, typename T::my_type, default_type>::type input_data;
t.use_data(input_data);
}
int main(int argc, char** argv)
{
has_no_typedef_t s1;
has_typedef_t s2;
// my_function(s1); // doesn't compile:
//'has_no_typedef_t has no type named 'my_type'
my_function(s2); //compiles
return 0;
}
| This has had a solution since C++98: a traits class. Concepts just makes it a bit easier to implement:
template<typename T>
struct traits
{
using type = default_type;
};
template<has_type T>
struct traits<T>
{
using type = T::my_type;
};
Without concepts, you'd need to use SFINAE to turn on/off the specializations based on whether the type has the trait or not.
|
72,261,075 | 72,261,155 | How to create const reference to pointer on const? | I want to create the following class, but the compiler gives an error (it tells that the signatures of the methods are the same):
struct entities_set_less
{
constexpr bool operator()(const ContentEntity*& _Left, const ContentEntity*& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
constexpr bool operator()( const const ContentEntity*& _Left, const const ContentEntity*&_Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
From my point of view, an expression like const const ContentEntity*& means "const reference to pointer on const ContentEntity". It should be different from const ContentEntity*&, which is just "const reference to pointer on non const type".
| First, let's clarify (or attempt to) what you actually want. You say you want a "const reference" … but references are (effectively) const, anyway (i.e., once a reference variable is bound to its target, it cannot subsequently be bound to a different target).
So, what you may have meant is that you want the arguments in the second overload to be references to constant pointers to constant objects; that is, neither the pointers nor the objects can be modified (in your first overload, the pointed-to objects cannot be modified but the referred-to pointers can be.
To make the pointers const, you need to add that keyword immediately after the pointer indicator (*). Like this:
struct entities_set_less {
constexpr bool operator()(const ContentEntity*& _left, const ContentEntity*& _light) const
{ // references to non-const pointers to const objects
return (_left < _light);
}
constexpr bool operator()(const ContentEntity* const& _left, const ContentEntity* const& _right) const
{ // references to CONST pointers to const objects
return (_left < _right);
}
};
Note that I have also changed your _Left and _Right identifiers to _left and _right, because IDs starting with an underscore followed by an uppercase letter are reserved. From this C++17 Draft Standard:
5.10 Identifiers [lex.name]
…
(3.1) — Each
identifier that contains a double underscore __ or begins with an
underscore followed by an uppercase letter is reserved to the
implementation for any use.
|
72,261,388 | 72,261,576 | Why pass input/output stream in a function? | Why would we want to do this:
#include <iostream>
void print(std::ostream& os) {
os << "Hi";
}
int main() {
print(std::cout);
return 0;
}
instead of this:
#include <iostream>
void print() {
std::cout << "Hi";
}
int main() {
print();
return 0;
}
Is there some certain advantage or functionality that is obtained only with the first version?
| Yes, the first version is significantly better. Like already mentioned in the comments, it allows you to use any kind of std::ostream, not just std::cout. Some of the most important consequences of this architectural choice are:
You can use your function to print the required data to standard output, a file, a custom class written by your colleagues (e.g. database adapter, logger).
It is possible to test your void print function. E.g.:
TEST(MyFunctionShould, printHello)
{
std::string expectedResult("Hello");
std::ostringstream oss;
print(oss);
ASSERT_EQ(expectedResult, oss.str());
}
|
72,261,511 | 72,261,872 | Access violation executing in classes with inheritance/ c++ | I have a base class Participant and I need to sort object in array of participant by quantity of their prizes or diplomas. The virtual function get_data return this number. But whileI try to sort, i've got error Access violation executing in row with comparing 2 numbers.
if (p[j].Get_Data() < p[i].Get_Data()) {
This is my full code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Participant {
protected:
string name;
string surname;
vector <string> type;
int age;
public:
Participant() : name(""), surname(""), type(), age(0)
{}
Participant(string name, string surname, vector <string> type, int age) {
this->name = name;
this->surname = surname;
this->type = type;
this->age = age;
};
Participant(const Participant& other) : name(other.name), surname(other.surname), type(other.type), age(other.age)
{
}
Participant& operator=(const Participant& other)
{
name = other.name;
surname = other.surname;
type = other.type;
age = other.age;
return *this;
}
virtual int Get_Data() {
return 0;
}
friend void Sort(Participant* p);
};
class Diploma : public Participant {
protected:
vector<int> places;
vector <string> type_d;
public:
Diploma() : places(), type_d{}
{}
Diploma(string name, string surname, vector <string> type, int age, vector<int> places, vector <string> type_d);
int Get_Data() override {
cout << "diplom prize" << endl;
cout << type_d.size() << endl;
return type_d.size();
}
};
class Prize : public Participant {
protected:
vector <int> places;
vector<string> prize;
public:
Prize(string name, string surname, vector <string> type, int age, vector<int> places, vector<string> prize);
int Get_Data() override{
cout << "Cont prize" << endl;
cout << prize.size() << endl;
return prize.size();
}
};
Prize::Prize(string name, string surname, vector <string> type, int age, vector<int> places, vector<string> prize) {
this->name = name;
this->surname = surname;
this->type = type;
this->age = age;
this->places = places;
this->prize = prize;
}
Diploma::Diploma(string name, string surname, vector <string> type, int age, vector<int> places, vector <string> type_d){
this->name = name;
this->surname = surname;
this->type = type;
this->age = age;
this->places = places;
this->type_d = type_d;
}
void Sort(Participant* p) {
Participant temp;
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++)
{
if (p[j].Get_Data() < p[i].Get_Data()) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
int main() {
Participant* pa[3];
pa[0] = new Diploma("Alex", "Smith", { "Geo","Math" }, 17, { 1,6 }, { "first"});
pa[1] = new Prize("Helen", "Blink", { "IT","Math" }, 18, { 2,2 }, {"Golden medal", "medal"});
pa[2] = new Prize("Brandon", "Brown", { "IT","Math" }, 18, { 2,2 }, { "Golden medal", "medal","gold"});
Sort(*pa);
for (int i = 0; i < 3; i++) {
pa[i]->Get_Data();
cout << endl;
}
}
| The issue here is that when you are passing *pa, only the first element is accessible. If you run it in debug mode you will be able to see that inside sort function, p[1] is not a valid object. Basically, only p[0] is passed to the function. You should pass the reference to the array i.e. **pa to the sort function
void Sort(Participant **p)
{
Participant *temp;
for (int i = 0; i < 3; i++)
{
for (int j = i + 1; j < 3; j++)
{
if (p[j]->Get_Data() < p[i]->Get_Data())
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
int main()
{
Participant *pa[3];
pa[0] = new Diploma("Alex", "Smith", {"Geo", "Math"}, 17, {1, 6}, {"first"});
pa[1] = new Prize("Helen", "Blink", {"IT", "Math"}, 18, {2, 2}, {"Golden medal", "medal"});
pa[2] = new Prize("Brandon", "Brown", {"IT", "Math"}, 18, {2, 2}, {"Golden medal", "medal", "gold"});
Sort(pa);
for (int i = 0; i < 3; i++)
{
pa[i]->Get_Data();
cout << endl;
}
}
|
72,261,567 | 72,261,958 | C++20 pre-allocate array to store multiple types | I have a Linux code.
I would like to pre-allocate 10000 items of different types as circular array. I always know which object type it is.
Since biggest object takes 54 bytes - I want to allocate 10000 x 54 chunk of memory.
Whats the correct pointer arithmetic to retrieve reference to an object with index i ?
x64 architecture
uint8_t cache[10000 * 54];
MyType* o = static_cast<MyType*>(cache + i * 54);
o.Prop1 = 10;
is this right?
EDIT: I need most efficient solution
EDIT2: these are instances of classes not structs (if that makes difference for aligning)
EDIT3: 54 byte is red herring, consider any "appropriate" aligned size, also I compile it with g++ as C++20 on CentOS9
| Use std::array<std::variant<Type1, Type2, Type3, ...>, 100000> cache;
|
72,261,977 | 72,263,350 | c++ IPC Boost::Interprocess vector of classes containing map | I like to create a boost interprocess vector of classes containing maps.
The following code is based on the Container of Container and Creating Vectors in shared memory example, but I feel very overwhelmed by combining these two tutorials. I think im stuck constructing "MyVec" in memory. After that, the code does not compile.
The reason behind this is, to load data in memory once and access it from different processes on demand.
Thank you! Simon
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
using namespace boost::interprocess;
// this is my original object
// goal: create a named shared memory object of std::vector<obj>
/*
class obj {
public:
int id = 0;
std::string string = "NA"; //will switch to "char_string"
std::map<int, std::string> map;
bool equalsType(const int &input, const bool &inverse){
if (id == -1)
{
return !inverse;
}
return id == input ? !inverse : inverse;
};
}
*/
// Typedefs of allocators and containers
typedef managed_shared_memory::segment_manager segment_manager_t;
typedef allocator<void, segment_manager_t> void_allocator;
typedef allocator<int, segment_manager_t> int_allocator;
typedef allocator<char, segment_manager_t> char_allocator;
typedef basic_string<char, std::char_traits<char>, char_allocator> char_string;
// Definition of the map holding a int as key and string as mapped type
typedef std::pair<const int, char_string> map_value_type;
typedef allocator<map_value_type, segment_manager_t> map_value_type_allocator;
typedef map<int, char_string, std::less<int>, map_value_type_allocator> map_type;
class complex_data // "boost version" of obj class
{
int id_;
char_string char_string_;
map_type map_type_;
public:
// Since void_allocator is convertible to any other allocator<T>, we can simplify
// the initialization taking just one allocator for all inner containers.
complex_data(int id, const char *name, const void_allocator &void_alloc)
: id_(id), char_string_(name, void_alloc), map_type_(void_alloc)
{
}
};
// Definition of the vector holding complex_data objects
typedef allocator<complex_data, segment_manager_t> complex_data_vector_allocator;
typedef vector<complex_data, complex_data_vector_allocator> complex_data_vector;
typedef vector<complex_data_vector, complex_data_vector_allocator> complex_data_vector_vector;
int main()
{
// Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove() { shared_memory_object::remove("MySharedMemory"); }
} remover;
// Create shared memory
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
// An allocator convertible to any allocator<T, segment_manager_t> type
void_allocator alloc_inst(segment.get_segment_manager());
// Starting from here I'm completely lost
// Construct the shared vector and fill it
complex_data_vector_vector *myVec = segment.construct<complex_data_vector_vector>("MyVector")(alloc_inst);
for (int i = 0; i < 100; ++i)
{
// Both key(string) and value(complex_data) need an allocator in their constructors
int key_object(i);
map_value_type mapped_object(i, "test", alloc_inst);
map_value_type value(key_object, mapped_object);
// Modify values and insert them in the map
myVec->push_back(value)
}
}
| You want to create a vector of classes but creating a vector of vector of classes.
All you need is complex_data_vector, your complex_data_vector_vector is not needed.
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
using namespace boost::interprocess;
typedef managed_shared_memory::segment_manager segment_manager_t;
typedef allocator<void, segment_manager_t> void_allocator;
typedef allocator<int, segment_manager_t> int_allocator;
typedef allocator<char, segment_manager_t> char_allocator;
typedef basic_string<char, std::char_traits<char>, char_allocator> char_string;
typedef std::pair<const int, char_string> map_value_type;
typedef allocator<map_value_type, segment_manager_t> map_value_type_allocator;
typedef map<int, char_string, std::less<int>, map_value_type_allocator> map_type;
class complex_data
{
int id_;
char_string char_string_;
map_type map_type_;
public:
complex_data(int id, const char* name, const void_allocator& void_alloc)
: id_(id)
, char_string_(name, void_alloc)
, map_type_(void_alloc)
{
}
void set(int key, const char* value) {
map_type_.insert(map_value_type{key, {value, map_type_.get_allocator()}});
}
};
// Definition of the vector holding complex_data objects
typedef allocator<complex_data, segment_manager_t> complex_data_allocator;
typedef vector<complex_data, complex_data_allocator> complex_data_vector;
int main()
{
// Remove shared memory on construction and destruction
struct shm_remove {
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove() { shared_memory_object::remove("MySharedMemory"); }
} remover;
// Create shared memory
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
// An allocator convertible to any allocator<T, segment_manager_t> type
void_allocator alloc_inst(segment.get_segment_manager());
complex_data_vector* myVec = segment.construct<complex_data_vector>("MyVector")(alloc_inst);
for (int i = 0; i < 100; ++i) {
myVec->emplace_back(i, "test", alloc_inst);
complex_data& data = myVec->back();
data.set(42, "Test");
}
}
|
72,262,307 | 72,262,422 | How to get out of "std::thread::id" the same id as the "WinAPI thread-id" (on Windows)? | How to get out of std::thread::id the same id as the "Win API thread-id" (on Windows)?
The thread-id is 9120 (id and this_id). I tried a few ANSI C++ ways, but they resulted in a different id:
Code:
int main()
{
// Win API:
const auto id = Concurrency::details::platform::GetCurrentThreadId(); // OK
// ANSI C++:
const std::thread::id this_id = std::this_thread::get_id(); // OK (but internal only: _id)
constexpr std::hash<std::thread::id> myHashObject{};
const auto threadId1 = myHashObject(std::this_thread::get_id());
const auto threadId2 = std::hash<std::thread::id>{}(std::this_thread::get_id());
const auto threadId3 = std::hash<std::thread::id>()(std::this_thread::get_id());
}
Update:
@Chnossos suggestion works as expected:
| You shouldn't rely on the format or value (see comments below). That being said, you can play with the operator<<:
#include <iostream>
#include <sstream>
#include <thread>
int main()
{
std::stringstream ss;
ss << std::this_thread::get_id();
std::size_t sz;
ss >> sz;
std::cout << std::this_thread::get_id() << " vs. " << sz << std::endl;
}
Try it online
Output is not portable and there are no guarantees around the conversion or format of the conversion. Do not use this in production code.
|
72,262,650 | 72,262,739 | Will std::unordered_map::clear() be slower than std::map::clear() because clear operations are "carried on" in the former? | I was reading this and from what I can get is that unordered_map practically works linear in number of elements + number of buckets.
So, let's say, I have code, which
adds arbitrary number of elements to std::unordered_map
then clear() the std::unordered_map
repeat this multiple times.
If I had lot of elements at any point of the total execution (in step 1), the clear time will carry-on in future also, making code slow.
But, is this same issue also with std::map?
Thanks
|
When will std::map::clear() going to be faster that std::unordered_map::clear()?
Both have linear asymptotic complexity. You can time your code using both to see if either is measurably faster.
Note that if the destructor of the element is non-trivial, then clear of all containers has linear complexity. If the destructor is trivial, then the only standard containers that have less than linear complexity of clear are std::vector and std::basic_string.
Regarding the case of:
grow container large
clear
insert few
clear
The cost of latter clear being high that applies to std::unordered_map is not a problem that reproduces with std::map.
|
72,262,700 | 72,262,748 | How do I define a member function of a specialized template class? | I have a template class ProcessPromise<T> and its specialization ProcessPromise<void> that depends on ProcessTask<T>:
template<typename T>
struct ProcessTask;
template<typename T>
class ProcessPromise
{
public:
ProcessTask<T> get_return_object();
};
template<>
class ProcessPromise<void>
{
public:
ProcessTask<void> get_return_object();
};
template<typename T>
struct ProcessTask
{
};
template<typename T>
ProcessTask<T> ProcessPromise<T>::get_return_object()
{
return { };
}
Can't figure out how do I define ProcessPromise<void>::get_return_object()?
Tried the code below:
template<>
ProcessTask<void> ProcessPromise<void>::get_return_object()
{
return { };
}
but it does not compile, GCC error:
prog.cc:30:23: error: template-id 'get_return_object<>' for 'ProcessTask<void> ProcessPromise<void>::get_return_object()' does not match any template declaration
30 | ProcessTask<void> ProcessPromise<void>::get_return_object()
| ^~~~~~~~~~~~~~~~~~~~
prog.cc:15:27: note: candidate is: 'ProcessTask<void> ProcessPromise<void>::get_return_object()'
15 | ProcessTask<void> get_return_object();
| ^~~~~~~~~~~~~~~~~
MSVC error:
error C2910: 'awl::ProcessPromise<void>::get_return_object': cannot be explicitly specialized
| Just remove the template<> prefix as shown below:
//no prefix template<> needed here
inline ProcessTask<void> ProcessPromise<void>::get_return_object()
{
return { };
}
Working demo
Note that the inline keyword is added so that we don't get multiple definition error.
Explanation>
The reason we don't need the prefix template<> is that we're providing an ordinary out-of-class definition for the member function of a full class template specialization. That is, we're not actually specializing the member function but instead providing an ordinary(non-template) out of class definition for that member function.
|
72,263,065 | 72,264,562 | QStyledItemDelegate / QAbstractItemDelegate for QListView | My aim is to create something like contact app, where I can list contacts and choose it to see information about person. I figure out that one of the possible solution is to use QListView + QStyledItemDelegate / QAbstractItemDelegate. The information about it is very difficult so I don't understand it clearly;
(Contact should look something like https://www.sketchappsources.com/free-source/4395-ios-contacts-screen-app-sketch-freebie-resource.html)
So how should I use QAbstractItemDelegate ( I heard that I must reimplement paintEvent )?
| I suggest you to start with a data model.
Use QStandardItemModel class for beginning and populate it with QStandardItem class instances. It would allow you to set icon, text, font, background, size and other properties for items. Refer to https://doc.qt.io/qt-5/qstandarditemmodel.html#details
Set your model to QListView using setModel
To handle items clicked connect to QListView's clicked signal.
To render items in more complex way you should
Override QStyledItemDelegate class and it's paint and sizeHint methods. In the paint method you should implement rendering and your sizeHint method should return a valid size for items. Refer to https://doc.qt.io/qt-5/qabstractitemdelegate.html#details
To get item data to render use data method of QModelIndex reference that is passed to paint method. Use different roles to get appropriate data. Refer to https://doc.qt.io/qt-5/qt.html#ItemDataRole-enum
Use your delegate class by setting it to QListView by setItemDelegate.
Model should be set to QListView and item clicks are handled in same way.
|
72,263,196 | 72,263,654 | parameterized C++ nested struct array initialization | I've checked posts here that I can use template for nested struct. But when I'm trying to initialize an array inside a nested struct, there seems problem during initialization. In the following example, the array size is one of the parameters of the nested struct so Visual Studio complained that the array size is illegal. Here is the definition:
//template<typename U, typename T>
template<typename U, size_t T> // this line also not work
struct A {
struct B {
struct C {
vector<U> count[T]; // count needs to have variable size
C() {
count = new U[T]; // allocate size. Not work
}
C c;
};
B b;
};
Did I do anything wrong when using the template and initialize the array?
Thanks
|
Did I do anything wrong when using the template and initialize the array?
Yes, you do count = new U[T];, but count is not a pointer.
If you want the vector to be initialized to have the size T, provide T to the vector's constructor in the member initializer list:
template<typename U, size_t T>
struct A {
struct B {
struct C {
std::vector<U> count;
C() : count(T) {} // now `count´ is constructed with `T` elements
}; // <- you are also missing this line
C c;
};
B b;
};
If you really want a fixed size array of T vector<U>s:
#include <array>
template<typename U, size_t T>
struct A {
struct B {
struct C {
std::array<std::vector<U>, T> count;
};
C c;
};
B b;
};
|
72,263,202 | 72,269,853 | How can I show a comment block inside a code block inside a doxygen block? | Let's say I want to show a /* - */ delimited comment block inside a code block in a
Doxygen documentation block in C++ code. If the Doxygen block, is itself /* - */
delimited, like this,
/**
documentation
\code
/*
comment
*/
\endcode
*/
that's clearly going to be a problem: Doxygen will do the right thing, but a C++ compiler
won't know that it should ignore the inner */. An alternative is to use a
///-delimited Doxygen block:
/// documentation
/// \code
/// /*
/// comment
/// */
/// \endcode
This version won't confuse the C++ compiler, but now Doxygen adds an extra star. How can I make both Doxygen and C++ happy?
It was suggested in comments that I could at least align the extra asterisk with the ones that are supposed to be there, making the output look better. In some cases that might be acceptable, but I think that would be a problem for me, so let me explain why. The documentation is discussing a renderer shading language that understands #include and single-line comments but not block comments, and wants to say:
Block comment lines are not supported, but may not matter if the included file does not close the block:
/*
#include "MyFile.h" --> file will be included anyway.
*/
If that gets changed to
/*
* #include "MyFile.h" --> file will be included anyway.
*/
then it may look fine, but I don't know if it will be semantically correct any more, because I don't know what that extra asterisk would do.
| As it is not possible to have a code block in a comment and I suggested to maybe use the \snippet command I give an example of it usage here:
/// documentation
/// \snippet this S1
void fie();
// [S1]
/*
comment
*/
// [S1]
resulting in:
Note: you can also use e.g.:
/// documentation
/// \snippet this S1
// [S1]
/*
comment
*/
// [S1]
void fie();
|
72,263,705 | 72,264,024 | Requires clause positioning in C++20 function templates | In C++20, you can write a constrained function template in a couple of different ways:
template <typename T>
concept Fooable = true;
template <typename T>
requires Fooable<T>
void do_something(T&); // (1)
template <typename T>
void do_something(T&) requires Fooable<T>; // (2)
According to the accepted answer in this question, these two forms are equivalent (which has always been my understanding).
However, I notice that GCC 12.1 considers (1) and (2) to be two different functions, rather than (2) being a redeclaration: it's possible to provide definitions for both, and attempting to call do_something() is then ambiguous (example).
Is GCC correct, and these are two different functions?
If so, are there any technical differences in meaning between the two styles?
EDIT:
As pointed out in the comments, the linked questions states that a function template declaration and definition must use the same "requires style". What is the reason for this restriction?
(I vaguely recall from the Concepts TS days that requirements underwent "normalisation" to decide when they were equivalent -- I guess this is no longer the case in C++20?)
| The wording in this area has moved around a bit. In C++20, we had this rule in [temp.over.link]/7:
Two function templates are equivalent if they are declared in the same scope, have the same name, have equivalent template-heads, and have return types, parameter lists, and trailing requires-clauses (if any) that are equivalent using the rules described above to compare expressions involving template parameters. Two function templates are functionally equivalent if they are declared in the same scope, have the same name, accept and are satisfied by the same set of template argument lists, and have return types and parameter lists that are functionally equivalent using the rules described above to compare expressions involving template parameters. If the validity or meaning of the program depends on whether two constructs are equivalent, and they are functionally equivalent but not equivalent, the program is ill-formed, no diagnostic required.
[Note 7: This rule guarantees that equivalent declarations will be linked with one another, while not requiring implementations to use heroic efforts to guarantee that functionally equivalent declarations will be treated as distinct.
// guaranteed to be the same
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+10>);
// guaranteed to be different
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+11>);
// ill-formed, no diagnostic required
template <int I> void f(A<I>, A<I+10>);
template <int I> void f(A<I>, A<I+1+2+3+4>);
-end note]
In your example:
template <typename T>
requires Fooable<T>
void do_something(T&); // (1)
template <typename T>
void do_something(T&) requires Fooable<T>; // (2)
These are functionally equivalent (they have the same constraints, basically) but not equivalent (they have different template-heads - the requires clause after the template parameters is part of the template-head), which makes this ill-formed no diagnostic required. In practice, because they're not equivalent, they're different overloads - but because they're functionally equivalent, any attempt to call would be ambiguous between them.
As I point out in the other answer, these have the same meaning - it's just that you have to stick with one form for the declaration and the definition if you split them.
The current wording, after Davis Herring's omnibus paper P1787, involves going up to [basic.scope.scope]/4:
Two declarations correspond if they (re)introduce the same name, both declare constructors, or both declare destructors, unless [...] each declares a function or function template, except when [...] both declare function templates with equivalent non-object-parameter-type-lists, return types (if any), template-heads, and trailing requires-clauses (if any), and, if both are non-static members, they have corresponding object parameters.
This makes the two do_somethings not correspond, which makes them different function templates. We don't run into the new functionally equivalent but not equivalent rule (so we're not ill-formed, no diagnostic required), but we just have two function templates that are necessarily ambiguous in all cases. So... not the most useful thing in the world.
|
72,263,838 | 72,266,972 | ROOT(CERN): Plot an figure with error bars using data from an csv file | I'm trying to read data from a .csv file, which contains 4 columns: "x","y","Standard Deviation" and "Uncertainty". I want to plot a scatter diagram with error bars, which represent the uncertainty red from the .csv file. I run the following codes in root's REPL:
auto rdf = ROOT::RDF::MakeCsvDataFrame("./file.csv")
auto g1 = rdf.GraphAsymmErrors("x","y","","","Uncertainty","Uncertainty");
but I get an error:
ROOT_prompt_1:1:15: error: no member named 'GraphAsymmErrors' in 'ROOT::RDataFrame'
Meanwhile I can run the code below correctly:
auto g2=rdf.Graph("x","y");
g2->SetMarkerStyle(6);
g2->Draw();
, which confuses me because in the document of ROOT, the Graph() method and GraphAsymmErrors() method both seem to be the method of RDataFrame, so I think it should not show the error above.
Also, my root's version is 6.26, installed on Ubuntu 22.04 via snap.
| GraphAsymmErrors doesn't seem to exist in the v6.26 documentation. The documentation you linked was for the master branch. You'll probably have to update to a nightly-build or wait for the next release in order to use that function.
In the meantime I would recommend you use RDataFrame::Take() on the respective branches to get them as std::vectors, and use the TGraphAsymmErrors constructor directly.
|
72,264,122 | 72,265,312 | Binding rvalue ref to string literal in constructor vs construct in-place | I'm a bit confused about C++ temporaries in regards to string literals and move semantics.
Which one of the following is better, in terms of performance and readability.
Usage: Constructor("string_literal")
Option 1: s is created from the string literal, then it is moved into the member variable.
Constructor(
string s
) : s_(std::move(s)) {}
Option 2: The string literal is created as a temporary, then bound to s, then moved into the member s_.
Constructor(
string&& s
) : s_(std::move(s)) {}
Option 3: Pass lvalue ref to temporary, then copy-construct s_
Constructor(
const string& s
) : s_(s)
In the case that caller passes a string literal to the constructor, seems like option 1 is slightly more efficient, since we skip rvalue ref binding and lvalue ref binding, respectively.
If caller passes a string to the constructor, then option 1 will do a copy-and-move, but option 2 forces the user to create a copy, which is then moved. The performance is identical, but the user has a slightly less friendly API for 2.
Which is the best option to go with? Thanks.
| Option 1 will copy when you have a movable string and construct and move from a literal.
Option 2 will move when you have a movable string and construct and move when you have a literal.
Option 3 is the worst as it will always copy.
As you can see Option 2 <= 1 <= 3.
Also consider
Constructor("string_literal"s)
This is a std::string literal. So Option 2 will just move that right in.
Note: The compiler can optimize copies away as well in many cases.
|
72,264,228 | 72,264,321 | Including a precompiled header and a non-precompiled header in a .cpp file causes the .cpp file to not recognize the non-precompiled header | Visual Studio 2022:
I included a simple header to store basic functions like printing text or executing functions to my .cpp file, but after including a precompiled header that stores Windows.h the .cpp file doesn't recognize the functions/variables inside of the non-precompiled header.
CPP:
#pragma once
#include "basics.h"
#include "precompiled header.h"
int main()
{
Basics::Print("Something"); // C2653 Basics is not a class or namespace name
}
basics.h:
class Basics
{
public:
static void Print(const char* format, ...);
}
precompiled header.h:
#pragma once
#include <Windows.h>
// This header is than #included in a .cpp file.
What is the point of precompiling the headers if some headers need other headers but can't access them since only .cpp files can? Do you really want to precompile headers + Include headers in another headers that need them.
| The precompiled header must come first in the include list, because it erases everything that comes before it.
|
72,264,830 | 72,271,752 | How to insert a record into Microsoft Access using MFC? | How can I insert record in Microsoft Access?
CString SqlString;
CString name="I want to add this variable in Table3";
SqlString = "INSERT INTO Table3 (Name,Numbers) VALUES (name,099)";
When I do it that way gives the following error:
Database error:Too few parameters.Expected 1.
| This is a snippet from my own application:
BOOL CCommunityTalksApp::SetRecordForTalkNumber(int iTalkNumber, UINT uID, CString &rStrError)
{
CDatabase *pDatabase;
CString strSQL, strField;
BOOL bOK;
pDatabase = theApp.GetDatabase();
if(pDatabase != nullptr)
{
if (iTalkNumber == 9999)
strField = _T(" ");
else
strField.LoadString(uID);
strSQL.Format(_T("INSERT INTO [Public Talk Titles] ([Theme], [Category], [Talk Number]) VALUES ('%s', 'NS', %d)"), strField, iTalkNumber);
TRY
{
pDatabase->ExecuteSQL((LPCTSTR)strSQL);
bOK = TRUE;
}
CATCH(CDBException, Except)
{
rStrError = Except->m_strError;
bOK = FALSE;
}
END_CATCH
}
return bOK;
}
As you can see:
Use [ and ] to wrap the table and field names to address any issues with spaces.
Qualify the field names first — particularly if you are only populating certain field values.
Wrap the string values with single quotes.
So:
SqlString = "INSERT INTO Table3 (Name,Numbers) VALUES (name,099)";
Would be something like:
SqlString = "INSERT INTO [Table3] ([Name],[Numbers]) VALUES ('name',099)";
I appreciate that the square brackets are not needed for your table / field names though.
|
72,265,055 | 72,270,604 | How does approxPolyDP and epsilon parameter work? | Could someone give a good explanation about how epsilon works?
This is how I use it.
cv::approxPolyDP(contour, approx, cv::arcLength(contour, true) * precision, true);
As default double precision=0.02.
Somthing that doesn't make sense to me is that the lower precision is the less strict the shape detection gets?
For example if I'm looking for rectangle contours in an image and not all rectangular contours are detected and precision is set to 0.5 (higher) even fewer rectangular contours are detected as rectangles. But if I set precision to 0.01 (lower) more rectangular contours are detected???
Shouldn't it be the other way around? Lower precision = more strict shape detection?
| approxPolyDP implements the Ramer–Douglas–Peucker algorithm
The algorithm does not detect shapes, it simplifies contours.
It removes points that contribute very little (epsilon) to the shape of the contour. Colinear points are a trivial case because they contribute zero to the shape of the contour. The most prominent corners are left standing. The result is an approximation of the input contour.
A tighter epsilon forces a more faithful approximation, leaving more points left standing, down to all points remaining (no action).
Note that in the case of a square/rectangle/quad with even just rounded corners, the locations of the edges of the quad are not maintained. Points on the rounded corners remain. However, the approximation can be used to segment the original contour, discard "corner" points, and work with edge points.
|
72,265,116 | 72,265,200 | Is it safe to call <math.h> functions by reference? | Please, tell me is it safe to call math functions the following way:
map<string,double(*)<double> func_map = { {"sin", &std::sin } ... }
...
double arg = 2.9;
double res = func_map["sin"](arg);
| Taking the addresses of functions in the standard library not on the Designated addressable functions list leads to unspecified behavior (since at least C++20). std::sin and the other <cmath> functions are not on that list so, to be safe, wrap them up in functors, like lambdas:
#include <cmath>
#include <map>
#include <string>
int main() {
std::map<std::string, double(*)(double)> func_map = {
{"sin", [](double x) { return std::sin(x); }},
{"cos", [](double x) { return std::cos(x); }},
};
}
is it safe to call math functions the following way:
double res = func_map["sin"](arg);
No, if the function you aim to call is not present in func_map, using the subscript operator[] would first insert a double(*)(double) pointing at nullptr into the map and then return that nullptr. Calling nullptr(arg) would lead to undefined behavior. To make it safe you can do a couple of things:
Make func_map const. This prevents you from using any functions potentially inserting something in the map, like the subscript operator.
Use func_map.at("sin")(arg); to get an exception (std::out_of_range) if the function doesn't exist in the map. You can safely catch that and print a message to the user:
try {
double res = func_map.at("sin")(arg);
std::cout << res << '\n';
} catch (const std::out_of_range& ex) {
std::cout << "unknown function\n";
}
If you don't want exceptions for unknown functions, you can use the member function find instead:
if(auto fit = func_map.find("sin"); fit != func_map.end()) {
double res = fit->second(arg);
std::cout << res << '\n';
} else {
std::cout << "unknown function\n";
}
|
72,265,202 | 72,265,737 | Can not call function pointer of a struct to a class method | use C++98. I have a struct t_fd which is used inside a class MS. In the struct there are two pointers to function: fct_read, fct_write. I designed that the function pointers are pointing to the two methods of the class. But then I have this error when trying to call them.
expression preceding parentheses of apparent call must have (pointer-to-) function type.
Please advice on the error, also on the design. I need the two functions are methods of that class because I need to use class's attributes (even though it isn't showed here for the shake of simplicity). Thank you for your time, I appreciate your help!
#include <vector>
#include <iostream>
typedef struct s_fd {
void(MS::*fct_read) (int);
void(MS::*fct_write) (int);
} t_fd;
class MS
{
private:
std::vector< t_fd > _fdSet;
void server_accept(int s)
{
if (s % 2 == 0)
_fdSet[cs].fct_read = MS::client_read;
else
_fdSet[cs].fct_write = MS::client_write;
}
void client_read(int fd)
{
std::cout << "I'm reading\n";
}
void client_write(int fd)
{
std::cout << "I'm writing\n";
}
void check_fd()
{
int i = 0;
int size = 10;
while (i < size)
{
if (i < 5)
_fdSet[i].fct_read(i); //Error here!
if (i >= 5)
_fdSet[i].fct_write(i); //Error here!
i++;
}
}
};
| The intent of your code is difficult to understand (in its current form). But I would be happy to solve few issues in your code.
MS class needs to be declared before you reference it the type from s_fd structure definition :
class MS; // forward declaration
typedef struct s_fd {
void(MS::* fct_read) (int);
void(MS::* fct_write) (int);
} t_fd;
class MS
{ ... }
the syntax to assign function pointer is incorrect. You forgot &:
_fdSet[cs].fct_read = &MS::client_read;
fct_read and fct_write are member function pointers. They should be applied on instance of MS class. In case you want to apply them on this object:
if (i < 5) {
auto fptr = _fdSet[i].fct_read;
(this->*fptr)(i);
}
|
72,265,207 | 72,265,257 | error C2679: binary '>>' : no operator found | The full error message reads:
Error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Ar<int>' (or there is no acceptable conversion)
How can I fix it?
#include <iostream>
using namespace std;
template<class T>
class Dun
{
private:
T* array{ nullptr };
public:
Dun(T* _array) : array(_array) {}
T& Get(int index)
{
return this->array[index];
}
};
template<class T>
class Ar
{
private:
Dun<T>* data{nullptr};
public:
Ar(Dun<T>* _data) : data(_data) {}
T& operator[] (int index)
{
return this->data->Get(index);
}
};
int main()
{
int a[4] = { 1, 2, 3, 4 };
auto ar = new Dun<int>(a);
auto ur = new Ar<int>(ar);
cout << ur[1];
return 0;
}
| You don't need pointers here
int main()
{
int a[4] = { 1, 2, 3, 4 };
Dun<int> ar{a};
Ar<int> ur{&ar};
cout << ur[1];
return 0;
}
otherwise you'd have to dereference your pointer before your operator[] can be used
cout << (*ur)[1];
|
72,265,260 | 72,265,716 | Is there a way to 'reset' a functions variables? | I recently made a function to compare an array of numbers to a single value which returns the closest value to the single value out of the array. This works perfectly well when you only use it only once but if I use it again in another instance of the code, It returns an unexpected value (usually the previous single value used before). Here is the function that I am using:
double closestval (double num1, int amountofnums, double *comps){
double storagecomps[amountofnums];
for (int i = 0; i < amountofnums; i++){
storagecomps[i] = {comps[i]};
/* Storing the array of numbers for later as I will be changing them */
}
double smallval = 0.0001; /* tiny value used to increment/decrement
values in the array to the comparison variable.*/
int_fast64_t compi [amountofnums]; /* this variable keeps track of how many times it needs to decrement/increment the values in the array to approach the variable*/
for (int i = 0; i < amountofnums; i++){
compi[i] = 0;
}
for (int i = 0; i <= amountofnums; i++){
while (comps[i] > num1){
comps[i] -= smallval;
compi[i]++;
}
while (comps[i] < num1){
comps[i] += smallval;
compi[i]++;
}
double recholder[3] = {10000000, 0,};
// This area finds the
for (int i = 0; i < amountofnums; i++){
if (compi[i] < recholder[0]){
recholder[0] = compi[i];
recholder [1] = i;
recholder[2] = storagecomps[i]; /* if the amount of iterations to approach the single variable is less than the previous record holder, it becomes the new one.
*/
}
}
return recholder[2];
}
I am relatively sure this is because (in one way or another) the variables in the function are not being redefined properly or at all. Much thanks if you can show me where I've gone wrong!
| The problem isn't resetting the variables. The problem is that you are modifying the arguments passed to the function.
To prevent modifications you should use the const keyword:
double closestval (double num1, int amountofnums, const double *comps){
and then fix the errors the compilers throws at you.
If you do want to modify the comps inside the functions but not have it affect the values outside the functions then you should usestd::vector so you can pass them by value and the compiler will copy them:
double closestval (double num1, int amountofnums, std::vector<double> comps){
You should really do that anyway as you should forget all about C-style arrays till you are an expert.
|
72,265,277 | 72,265,754 | Can I add a different function that is defined in my code in a vector like arrays that include function adress? | In this code, there are 6 different functions. They create 6 different boards for playing a game. But I don't want to create boards with if conditions, I want to create a vector that includes function addresses in it. For example, if the user wants to create board 4 for playing the game, I want to create the board like this:
vector<vector<cell>> a = function_array[3];
cell is an enum type that I declared.
Can I do this, and can somebody help me for this?
vector<vector<cell>> first_table();
vector<vector<cell>> second_table();
vector<vector<cell>> third_table();
vector<vector<cell>> fourth_table();
vector<vector<cell>> fifth_table();
vector<vector<cell>> sixth_table();
int main()
{
int chose,board_type;
vector<vector<vector<cell>>> functions;
functions.push_back(first_table());
functions.push_back(second_table());
functions.push_back(third_table()); //in here I create all boards and print which one the user wants
functions.push_back(fourth_table()); //but I don't want to do this, I want just create the board the user wants
functions.push_back(fifth_table());
functions.push_back(sixth_table());
vector<vector<cell>> b = functions[board_type-1];
print_game(b);
b = functions[0];
cout << "welcomw Game" << endl;
cout << "Please chose board type" << endl;
cin >> board_type;
int game_type;
cout << "1.Personal game " << endl << "Computer game" << endl;
cin >> game_type;
string input;
cout << "Please enter move direction" << endl;
cin >> input;
}
| What you are looking for is std::function
In your case, you'd create a vector of std::function<> for functions that take no parameter and return a vector<vector<cell>>.
#include <functional>
#include <vector>
struct cell {};
//type aliases make code a lot more readable!
using board = std::vector<std::vector<cell>>;
board first_table();
board second_table();
board third_table();
board fourth_table();
board fifth_table();
board sixth_table();
int main() {
std::vector<std::function<board()>> functions;
functions.push_back(first_table);
// etc...
board b = functions[board_type-1]();
}
|
72,265,390 | 72,266,910 | How do I pass the output of a c program which use curses/ncurses to another program? | I have a simple c program which use ncurses to display some text on the screen. When running, it will print out hello, when the user press the arrow key up, it will exit the program printing on screen bye see you soon.
I would like to be able to use the output printed by the program, in this case bye see you soon as input of another program, for instance I would like to pass it to grep or cat, like:
./main.out | grep "bye"
similarly of the result I would get if I could pipe it like echo "bye see you soon" | grep "bye"
or alternatively by using something like command substitution $(...).
With my current solution, if I use ./main.out | grep "bye" I get always a blank screen and I am not able to pipe to grep.
Currently looking to a solution for Linux/macOS only.
I would like to know:
How I could solve this problem? (I would appreciate a snippet of code)
Is atexit the only solution available?
I am learning a bit of c, if you are able to give me a bit more context in the answer I would really appreciate it.
Run the program with:
make all
./main.out
================================== main.c
#include <stdio.h>
#include <curses.h>
#include <stdlib.h>
void print_menu(WINDOW *menu_win);
void bye(void)
{
printf("bye see you soon\n");
}
void print_menu(WINDOW *menu_win)
{
printf("hi");
wrefresh(menu_win);
}
int main()
{
WINDOW *menu_win;
int c;
initscr();
clear();
noecho();
cbreak();
menu_win = newwin(30, 30, 0, 0);
keypad(menu_win, TRUE);
refresh();
print_menu(menu_win);
while (1)
{
c = wgetch(menu_win);
switch (c)
{
case KEY_UP:
endwin();
int i = atexit(bye);
if (i != 0)
{
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
break;
default:
refresh();
break;
}
}
clrtoeol();
refresh();
endwin();
return 0;
}
================================== Makefile
SHELL = /bin/sh
PROGRAM = main
CC = gcc
CFLAGS = -g -O0 -Wall -Werror
LIBS = -lncurses
all:
$(CC) ./${PROGRAM}.c -o ./${PROGRAM}.out $(CFLAGS) $(LIBS)
| initscr does the equivalent of newterm(NULL, stdout, stdin), which pretty well makes it impossible to also pipe output into some other utility. If you want to do both, you can force ncurses to use /dev/tty for both input and output by replacing initscr() with something like:
FILE* tty = fopen("/dev/tty", "r+");
SCREEN* screen = newterm(NULL, tty, tty);
set_term(screen);
If you do that, you'll want to avoid writing to stdout (if it hasn't been redirected) while ncurses is active, since ncurses assumes that no-one else is writing to the console.
It might be useful to change the behaviour of your application, depending on whether stdout has been redirected. You could use isatty() for a fairly conservative test.
I don't really understand why you think it is necessary to use atexit() in your sample program. As soon as you call endwin(), it's safe to write to stdout. (But the printf of Hi in print_menu is problematic.)
It's also possible to use stderr as the ncurses output, on the assumption that it has not been redirected. I prefer the use of /dev/tty because it doesn't interfere with the use of stderr for error logging (invalidating the assumption that it has not been redirected). But if that's not important to you, newterm(NULL, stderr, stdin) is possibly simpler.
In any case, make sure you always check return values for error indications (which I omitted in the above code snippet).
|
72,265,398 | 72,265,489 | Type punning in a const / static initializer (building a float constant from bits) | Some languages (like Rust, Zig, GLSL, HLSL) have built-in methods to build a floating type from bits supplied as an unsigned integer. However C and C++ do not have standard functions for that.
With C99 we can use anonymous unions with member initialization to implement a type punning macro to the same effect:
#define FLOAT_FROM_BITS(U,F,b) (((union{U u; F f;}){.u=(b)}).f)
#define FLOAT32_FROM_BITS(i) FLOAT_FROM_BITS(uint32_t, float, i)
#define FLOAT64_FROM_BITS(i) FLOAT_FROM_BITS(uint64_t, double, i)
which can then subsequently be used to initialize const / static with. What would be the most elegant way to do this in C++, so that it can also be used for static initialization?
| If you can use C++20 or above, then use std::bit_cast like
auto myvar = std::bit_cast<type_to_cast_to>(value_to_cast);
If you want to support older versions, you can do this same thing using std::memcpy to copy the bytes from one type to another. That would give you a function like
template <class To, class From>
To bit_cast(const From& src)
{
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
|
72,265,510 | 72,267,325 | Do not-precompiled headers use precompiled headers if they are Included or are they for .cpp files only? | Visual Studio 2022:
I want to Include Precompiled headers in my .cpp file but I don't know if it's worth it since I'll also need to include a non-precompiled header with almost the same headers that are in the precompiled header.
Will the non-precompiled header use the precompiled headers or will it generate the code again on each compilation?
CPP:
#pragma once
#include "Precompiled.h"
#include "No-Precompiled.h" // Basic Headers: Windows.h, Psapi.h
int main()
{
// Functions that I need from "No-Precompiled.h" but I can't Precompile it since changes in it are made on regular basis
}
No-Precompiled.h:
#pragma once
#include <windows.h>
#include <Psapi.h>
#include <d3d11.h>
class Template
{
public:
//Functions that need many same Headers.
}
Precompiled.h:
#pragma once
#include <windows.h>
#include <Psapi.h>
#include <d3d11.h>
#include <limits>
#include <complex>
#include <filesystem>
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <tchar.h>
#include <wincred.h>
#include <complex>
#include <math.h>
Should I just Precompile the headers that the .cpp file uses (which is not much) or is there a way to allow No-Precompiled headers to use the Precompiled headers?
| Using pre-compiled headers doesn't change that much. In particular, header guards continue to work. The header guard for <windows.h> is also included in the pre-compiled state. Hence, when the compiler sees <windows.h> for the second time, it's immediately skipped.
In your case, the No-Precompiled.h header turns out to be pretty trivial, as all its headers have already been included. You're just compiling the Template.
I'd wonder a bit about the particular set of precompiled headers, though. PSapi and DirectX and IOstream? I can't really imagine a big program where you have many files using all of them. Note that <iostream> is really about std::cout, which doesn't make a lot of sense for DirectX programs.
|
72,266,252 | 72,267,263 | Showing the original index of an element in a vector after bubblesort | I'm new to c++ and i'm having a problem with my code. I need to show the original indexes of a vector before it was sorted, after sorted. I tried it like this:
#include <vector>
using namespace std;
void bubblesort(vector<int> &a, int n) {
for (int j = 0; j < n - 1; j++) {
for (int i = n - 1; i > j; i--) {
if (a.at(i) < a.at(i-1)) {
int aux = a.at(i);
a.at(i) = a.at(i-1);
a.at(i-1) = aux;
}
}
}
}
int main()
{
int n;
cout << "Digite o tamanho do vetor: ";
cin >> n;
vector<int> v;
vector<int> vold;
vector<int> pos;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
vold.push_back(a);
}
bubblesort(v, n);
for (int i = 0; i < n; i++) {
if (vold.at(i) == v.at(i)) {
pos.push_back(i);
}
else {
for (int j = i+1; j < n - 1; j++) {
if (vold.at(i) == v.at(j)) {
pos.at(j) = i;
break;
}
}
}
}
for (const int& i : pos) {
cout << i << " ";
}
system("pause>0");
}
But it didn't worked, if someone could help me to see what I'm doing wrong I would be glad, thanks in advance.
| If your goal is to show the indices of the sorted vector, then another approach is to not sort the original vector, but instead to sort a vector of index values based on the original vector.
The index vector would be initialized to 0, 1, 2, etc. up until the vector's size, minus 1.
Here is an example:
#include <vector>
#include <numeric>
#include <iostream>
void bubblesort(std::vector<int> &a, std::vector<int>& index)
{
// Make sure the index vector is the same size as
// the original
index.resize(a.size());
if ( a.size() <= 1 )
return;
// This is just a shortcut way of setting the values to 0,1,2,etc.
std::iota(index.begin(), index.end(), 0);
size_t n = a.size();
// Here is your sort, but with one difference...
for (size_t j = 0; j < n - 1; j++)
{
for (size_t i = n - 1; i > j; i--)
{
// Look at the comparison being done here using the index array
if (a.at(index[i]) < a.at(index[i-1]))
{
// We swap the index values, not the values
// in the vector
int aux = index.at(i);
index.at(i) = index.at(i-1);
index.at(i-1) = aux;
}
}
}
}
int main()
{
std::vector<int> v = {3, 1, 65, 23, 4};
std::vector<int> index;
bubblesort(v, index);
// Display the index values of the sorted items
for (const int& i : index)
std::cout << i << " ";
}
Output:
1 0 4 3 2
Note that the bubblesort function takes a vector of indices, and not n. There is no need to pass n, since a vector already knows its own size by utilizing the size() function.
The output shows the original index of each of the sorted items.
|
72,266,284 | 72,266,475 | error: expected unqualified-id before ‘{’ token on Linux gcc | i get the following error message when trying to compile the following code on linux with gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5) while it works on windows without problems.
...
#include "DDImage/NoIop.h"
static const char* const CLASS = "RemoveChannels";
// -------------------- Header -------------------- \\
class RemoveChannels : public NoIop
{
public:
//! Default constructor.
RemoveChannels (Node* node) : NoIop(node)
{
this->_message = "\\w+";
this->operation = 1;
}
//! Virtual destructor.
virtual ~RemoveChannels () {}
void _validate(bool) override;
private:
//! Information private for the node.
ChannelSet channels;
std::regex rgx;
const char* _message;
int operation; // 0 = remove, 1 = keep
};
void RemoveChannels::_validate(bool for_real)
{
if (!this->_message) // Fast return if you don't have anything in there.
{
set_out_channels(Mask_None); // Tell Nuke we didn't touch anything.
return;
}
...
}
...
When compiling the above code i get the following error message on linux with gcc (on windows it works fine!).
Compiler error:
RemoveChannels.cpp:28:1: error: expected unqualified-id before ‘{’ token
{
^
RemoveChannels.cpp:65:6: error: ‘RemoveChannels’ has not been declared
void RemoveChannels::_validate(bool for_real)
^~~~~~~~~~~~~~
/RemoveChannels.cpp: In function ‘void _validate(bool)’:
RemoveChannels.cpp:67:8: error: invalid use of ‘this’ in non-member function
if (!this->_message) // Fast return if you don't have anything in there.
^~~~
...
If i remove this-> from the implementing function and just use _message it compiles and works without a problem.
Can anyone explain to me why this is happening and just on linux and not on windows?
| Simple example
// -------------------- Header --------------------\\
class RemoveChannels
{
public:
int operation = 0;
};
int main ()
{
RemoveChannels r;
r.operation++;
}
when a line ends in a backslash, it is continued on the next line. That means class RemoveChannels has accidentally been commented out with a line comment leaking into the next line.
Solution: remove the backslash
// -------------------- Header --------------------
class RemoveChannels
{
public:
int operation = 0;
};
int main ()
{
RemoveChannels r;
r.operation++;
}
|
72,266,480 | 72,266,905 | Can `#ifdef` be used inside a macro? | I only found this related question, which isn't quite what I am looking for.
I used to have macros defined inside an #ifdef statement:
#ifdef DEBUG
# define PRINT_IF_DEBUGGING(format) printf(format);
# define PRINTF_IF_DEBUGGING(format, ...) printf(format, __VA_ARGS__);
#else
# define PRINT_IF_DEBUGGING(...)
# define PRINTF_IF_DEBUGGING(...)
#endif
Now, I want to do the inverse, to have the #ifdef statements inside the macros. Something like this:
#define PRINT_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) print(format); #endif
#define PRINTF_IF_DEBUGGING(format, ...) \
#if defined(DEBUG) printf(format, __VA_ARGS__); #endif
However, I am having an issue using __VA_ARGS__ inside the #ifdef defined.
error: '#' is not followed by a macro parameter
#define PRINT_IF_DEBUGGING(format, ...)
error: '#' is not followed by a macro parameter
#define PRINTF_IF_DEBUGGING(format, ...)
warning: __VA_ARGS__ can only appear in the expansion of a C++11 variadic macro
#if defined(DEBUG) printf(format, __VA_ARGS__); #endif
Is this possible?
| You can't use #ifdef inside of #define , so no, this is not possible. The first code you showed is the correct solution.
|
72,266,674 | 72,266,709 | Visual studio "module unsafe for SAFESEH image" occurring when building release in Assembly/C++ | I've been following this youtube tutorial to begin learning about Assembly: https://www.youtube.com/watch?v=W3roB5sRg4o&list=PLRwVmtr-pp05c1HTBj1no6Fl6C6mlxYDG&index=2
And everything's been going fine until I switch the build from debug to release, returning two errors: "module unsafe for SAFESEH image", and "unable to generate SAFESEH image". The thing is that I've deleted everything except for the External Dependencies folder, meaning that I don't have a vast selection of properties to choose from.
Here's a screenshot to my Visual Studio environment:
And here's another screenshot of my properties:
I'm a bit confused, since some other forums say to just change a setting, but since I deleted those default project folders I don't have it. Or is it something simple that I'm missing?
| I found a comment saying to replace the old build command from ml /c /Cx /coff "%(FullPath)" to ml /c /Cx /coff /safeseh "%(FullPath)" (notice the addition of /safeseh), which resolved the issue.
|
72,266,810 | 72,271,884 | Correcting Node Height for BST in CPP | I just need some help adjusting the height variable of ndoes in a BST, I cannot find out what is wrong with the logic in my code.
void BST<T>::fix_height(Node* node){
Node* current_node = node;
while(current_node !=nullptr){
if(current_node ->right != NULL && current_node ->left !=NULL){
current_node->height = std::max(current_node->left->height, current_node->right->height) + 1;
}else if(current_node ->right == nullptr){
current_node->height = current_node->left->height+1;
}else if(current_node ->left == nullptr){
current_node ->height = current_node->right->height+1;
}else{
current_node->height = 0;
}
current_node = current_node -> parent;
print(current_node);
}
}
| First of all, the code assumes that the children of the node that is passed as argument to fix_height have their heights already set correctly. If this is not guaranteed, then it already goes wrong there. But without seeing the context of the call of this function we must assume the function is only called on leaves or on nodes whose children have their height correctly set.
There is one problem inside the function: if node is a leaf, then the second if block will be entered, where an invalid reference is made to current_node->left.
One way to fix this, is to swap the first and the last case, and so first deal with the leaf case:
void BST<T>::fix_height(Node* node) {
Node* current_node = node;
while (current_node != nullptr) {
if (current_node->right == nullptr && current_node->left == nullptr) {
current_node->height = 0;
} else if(current_node->right == nullptr) {
current_node->height = current_node->left->height + 1;
} else if(current_node->left == nullptr) {
current_node->height = current_node->right->height + 1;
} else {
current_node->height = std::max(current_node->left->height, current_node->right->height) + 1;
}
current_node = current_node->parent;
print(current_node);
}
}
A minor thing: in C++ don't use NULL for null pointers. You had a mix of NULL and nullptr. Only use the latter.
|
72,267,542 | 72,267,606 | error: member access into incomplete type''; note: forward declaration of '' | Here is a struct MAIN which have member struct A and struct B, the code is like below
// a.hpp
#ifndef _A_HPP_
#define _A_HPP_
struct A
{
int mem1;
};
#endif
// b.hpp
#ifndef _B_HPP_
#define _B_HPP_
#include "a.hpp"
#include "main.hpp"
struct MAIN;
struct A;
struct B{
int mem2;
MAIN* main;
A *aptr;
B(){
*aptr=this->main->a;
}
};
#endif
// main.hpp
#ifndef _MAIN_HPP_
#define _MAIN_HPP_
#include "a.hpp"
#include "b.hpp"
struct MAIN{
A a;
B b;
};
#endif
// main.cpp
#include "main.hpp"
int main(){
MAIN m;
return 0;
}
I'd like to use the aptr in struct B to visit A which in the same MAIN, but compile error like
In file included from main.cpp:2:
In file included from ./main.hpp:6:
./b.hpp:15:25: error: member access into incomplete type 'MAIN'
*aptr=this->main->a;
^
./b.hpp:7:8: note: forward declaration of 'MAIN'
struct MAIN;
^
1 error generated.
How the error occured? my code should use struct but not class, and hpp but not h with cpp. Is there anyway to fix it? Hope for help
| The definition of the constructor B::B inside the struct definition references members of MAIN, but the latter hasn't been fully defined yet.
You need to move the body of constructor B::B into a separate file, i.e. b.cpp, and link with main.cpp when building the executable.
|
72,267,845 | 72,267,947 | Data in int* argument of function not returned caller | Compiled with g++ on WSL2, sample output of
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using std::vector;
vector <int> powers_2(const int npow) {
vector <int> v;
int j = 2;
for (int i=0; i<npow; i++) {
v.push_back(j);
j*= 2;
}
return v;
}
void pow_2(const int npow, int *v, int *nv) {
vector <int> w = powers_2(npow);
*nv = w.size();
v = (int*)malloc(*nv * sizeof(int));
for (int i=0; i<*nv; i++) {
v[i] = w[i];
printf("%d %d %d\n",i,v[i],w[i]);
}
}
int main() {
int *y;
int ny;
pow_2(3,y,&ny);
printf("\n in main\n");
for (int i=0; i<ny; i++) {
printf("%d %d\n",i,y[i]);
}
}
is
0 2 2
1 4 4
2 8 8
in main
0 1
1 0
2 1091723517
So the argument int* v is set in pow_2, but the data is not returned to caller. Why?
| There is a difference between passing function arguments by value, by pointer and by reference.
The line
pow_2(3,y,&ny);
will pass the value of y to the function pow_2, which means that a copy of the value of the variable y will be made, which will exist as the local variable v in the function pow_2. This is not what you want, because changing the variable v in the function pow_2 will only change that variable, but it won't change the value of the original variable y in the function main.
What you instead want is to pass the variable y itself to the function pow_2, not its value, so that it can be changed by the function pow_2. There are two ways of doing this. You can pass the variable y
as a reference, or
as a pointer
to the function pow_2.
To make the function pow_2 take a reference to an int * instead of the value of an int *, you can change the line
void pow_2(const int npow, int *v, int *nv) {
to:
void pow_2(const int npow, int * &v, int *nv) {
Alternatively, you can make the function pow_2 take a pointer to an int * instead of the value of an int *. You can change the line
void pow_2(const int npow, int *v, int *nv) {
to
void pow_2(const int npow, int **v, int *nv) {
However, this will require you to rewrite the function pow_2 so that the pointer is deferenced whenever it is used:
void pow_2(const int npow, int **v, int *nv) {
vector <int> w = powers_2(npow);
*nv = w.size();
*v = (int*)malloc(*nv * sizeof(int));
for (int i=0; i<*nv; i++) {
(*v)[i] = w[i];
printf("%d %d %d\n",i,(*v)[i],w[i]);
}
}
Also, you will have to call the function differently. You will have to change the line
pow_2(3,y,&ny);
to:
pow_2(3,&y,&ny);
Therefore, passing the variable as a reference is easier than passing it as a pointer.
|
72,267,948 | 72,268,114 | how to make terminal ask for string then after string is received remove it | hi so I'm making a mini bank and I want to have the user put in the email and then once they put it in it clears and then moves to the password I'm having trouble doing that please help.
#include <iostream>
#include <windows.h>
#include <String>
#include <thread>
#include <stdlib.h>
int main() {
int money = 1000000;
std::string password;
std::string email;
std::string Inpassword;
std::string Inemail;
std::cout << ("Welcome to the bank of jack!\n");
Sleep(2000);
std::cout << ("Enter your email: ");
std::cin >> email;
//the user enters the email and then once the user inputs the email the computer clears the text containing the email
Sleep(3000);
std::cout << ("create your password: ");
std::cin >> password;
//user inputs password and then once its pasted the computer clears it
Sleep(1000);
std::cout << ("Account created\n");
Sleep(1000);
//after that the entire terminal is cleared
std::cout << ("Log in\n");
Sleep(1000);
std::cout << ("enter your email\n");
std::cin >> Inemail;
if (Inemail == email) {
std::cout << ("user ") << email << (" located");
}
else {
std::cout << ("incorrect email");
exit(0);
}
}
| Have you tried using the system function from cstdlib to execute the cls command to clear the console before Asking for Password.
Example Usage:
system("cls");
So Your Code is modified as below to clear the terminal after inputting the email and password.
#include <iostream>
#include <windows.h>
#include <String>
#include <thread>
#include <cstdlib>
int main() {
int money = 1000000;
std::string password;
std::string email;
std::string Inpassword;
std::string Inemail;
std::cout << ("Welcome to the bank of jack!\n");
Sleep(2000);
std::cout << ("Enter your email: ");
std::cin >> email;
//the user enters the email and then once the user inputs the email the computer clears the text containing the email
Sleep(3000);
system("cls");
std::cout << ("create your password: ");
std::cin >> password;
//user inputs password and then once its pasted the computer clears it
Sleep(1000);
system("cls");
std::cout << ("Account created\n");
Sleep(1000);
//after that the entire terminal is cleared
system("cls");
std::cout << ("Log in\n");
Sleep(1000);
std::cout << ("enter your email\n");
std::cin >> Inemail;
if (Inemail == email) {
std::cout << ("user ") << email << (" located");
}
else {
std::cout << ("incorrect email");
exit(0);
}
If you are on a Linux/Mac Environment be sure to replace the cls command with clear.
Hope this Helps
|
72,268,050 | 72,268,172 | Wrong print values while iterating 2d char array | I am trying to run this code in Arduino IDE. It is printing wrong values.
char daysOfTheWeek[7][4] = {"Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"};
for(int i=0;i<7;i++) {
Serial.print(daysOfTheWeek[i]);
Serial.print(" ");
}
Serial.println();
Printed values
Sun Mon TuesWed Wed ThurFri Fri Sat
I see this can be fixed by changing the array allocation as following
char *daysOfTheWeek[7] = {"Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"};
I am fairly new to c++. Can anyone help me understand why this is happening?
| All string literals have an implicit null-terminator at the end. So, the biggest ones of yours, the "Tues" and the "Thur", are actually contain five characters, like so: "Tues\0" and "Thur\0".
Thus, you either need to increase the dimension of the character array to [5] (resulting in char daysOfTheWeek[7][5]), or you need to use "Tue" and "Thu" as initializers instead.
It may be graphical for you to use the fact that Serial.print() returns the number of bytes written, when you try to print the contents of the daysOfTheWeek in this way.
Meanwhile, for example, in the g++ compiler your code should give you the error: error: initializer-string for array of chars is too long, pointing to the two problematic string literals mentioned above.
As for the Arduino part, you may want to consider using the String library type.
|
72,268,327 | 72,268,525 | I have compiled my cpp code to generate a dll file in visual studio, but I cannot find the generated dll file. Is there any default name for dll in vs | The code compiled:
#include <jni.h> // JNI header provided by JDK
#include <iostream> // C++ standard IO header
#include "HelloJNI.h" // Generated
#include <string>
using namespace std;
// Implementation of the native method sayHello()
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv* env, jobject thisObj)
{
cout << "Narain C A";
}
int main() {
JNIEXPORT void Java_HelloJNI_sayHello();
}
How to find the generated dll file in visual studio?
| You can check the output directory macros in Properties.
|
72,268,800 | 72,270,859 | Rotate right in a BST using void | I am not implementing an AVL tree but I need to create a method that would rotate the binary search tree to right, However, I used the following code and the solution is not working.
How do I implement the rotate right method including rotating the root node and the non-root node?
void BST<T>::rotate_right(Node* node)
{
//Node * current = node;
Node * move_up_node = node->left;
if(node == nullptr || move_up_node == nullptr)
{
return;
}
else
{
node->left = move_up_node->right;
if(node->left != nullptr)
{
node->left->parent = node;
}
//set parent edge
move_up_node->parent = node->parent;
if(node == root_)
{
root_ = move_up_node;
}
else if(node == node->parent->right)
{
node->parent->right = move_up_node;
}
else if (node == node->parent->left)
{
node->parent->left = move_up_node;
}
node->parent = move_up_node;
move_up_node->right = node;
//node = move_up_node;
}
// Correct height of ancestors of node
fix_height(root_);
}
The rotate node input is 21
When I output it, it does not do anything.
Before I tested the function, the output was
10 Height: 5
R├──42 Height: 4
| R├──91 Height: 3
| | L└──49 Height: 2
| | R└──70 Height: 1
| | | R├──77 Height: 0
| | | L└──54 Height: 0
| L└──21 Height: 0
L└──1 Height: 2
R└──7 Height: 1
| L└──2 Height: 0
After I tested it, the output was
rotate node: 21
10 Height: 5
R├──42 Height: 4
| R├──91 Height: 3
| | L└──49 Height: 2
| | R└──70 Height: 1
| | | R├──77 Height: 0
| | | L└──54 Height: 0
| L└──21 Height: 0
L└──1 Height: 2
R└──7 Height: 1
| L└──2 Height: 0
| There are these issues in the outer else block:
move_up_node->parent->right = node is not right, as move_up_node is node->left, and so move_up_node->parent is node, which means you actually set node->right = node, which creates a loop. What you really want here is node->left->parent = node
if(node == node->parent->right) is not safe if you don't first verify node has a parent. So make this an else if.
node->right = move_up_node is not right (it doesn't move that node up as the name suggests). It should be node->parent->right = move_up_node. The same mistake occurs in the next block.
Here is a correction of that outer else block:
// Set edge between node and its current inner grandchild:
node->left = move_up_node->right;
if (node->left != nullptr) {
node->left->parent = node; // <---
}
// Set edge between parent of node and the node that moves up
move_up_node->parent = node->parent;
if(node == root_)
{
root_ = move_up_node;
}
else if(node == node->parent->right) // <-- else!
{
node->parent->right = move_up_node; // <--
}
else // <-- no need for another `if`
{
node->parent->left = move_up_node; // <--
}
// Set edge between node and move_up_node (was OK):
node->parent = move_up_node;
move_up_node->right = node;
|
72,268,845 | 72,268,943 | How is it determined which memory block to use in c/c++? | This is the code I wrote:
#include <iostream>
using namespace std;
int main() {
int x[3] = {30,31,32}, y[3] = {40,41,42}, z[3] = {50,51,52};
for (int i=0; i < 3; i++) {
cout << *(x+i) << endl;
cout << *(x-(3-i)) << endl;
cout << *(x-(6-i)) << endl;
}
cout << endl;
for (int i=0; i < 3; i++) {
cout << (long int)&x[i] << endl; // address of x
}
cout << endl;
for (int i=0; i < 3; i++) {
cout << (long int)&y[i] << endl; // address of y
}
cout << endl;
for (int i=0; i < 3; i++) {
cout << (long int)&z[i] << endl; // address of z
}
}
Here is the output:
30
40
50
31
41
51
32
42
52
140701886846268
140701886846272
140701886846276
140701886846256
140701886846260
140701886846264
140701886846244
140701886846248
140701886846252
Here you can see the array which was declared at last takes the foremost memory address and second last takes memory address after the last one and so on.
|
Here you can see the array which was declared at last takes the foremost memory address and second last takes memory address after the last one and so on.
No, this is not what is happening. The program has undefined behavior because you're going out of bounds of the array for the expressions *(x-(3-i)) and *(x-(6-i)) for different values of i.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. In your case this means that you have to make sure that you don't go out of bounds of the array.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
72,269,321 | 72,271,702 | Prospective destructors in C++ | I have this code and this outputs the following:
link to the following example
https://godbolt.org/z/z8Pn9GsTv
template <typename T>
struct A1 {
A1() {
std::cout << "construction of a1" << std::endl;
}
~A1() {
std::cout << "destruction of a1" << std::endl;
}
~A1() requires (std::is_same_v<T,int>) {
std::cout << "it is an int" << std::endl;
}
};
int main() {
A1 <int>a;
return 0;
}
output:
construction of a1
destruction of a1
but swapping places of destructors it gives other result:
link to the code
https://godbolt.org/z/vxj7dPqaj
template <typename T>
struct A1 {
A1() {
std::cout << "construction of a1" << std::endl;
}
~A1() requires (std::is_same_v<T,int>) {
std::cout << "it is an int" << std::endl;
}
~A1() {
std::cout << "destruction of a1" << std::endl;
}
};
output:
construction of a1
it is an int
wondering is this a bug?
| That's indeed a reported Clang bug1, as noted by Quimby.
Note that the second snippet (the one with the the constrained destructor first) doesn't really "work" in Clang, which just ignores the second destructor2.
Also note that, unlike gcc, at the moment I'm writing, Clang doesn't seem to have implemented [P0848R3] (which is about conditional trivial special member functions) yet3.
1) https://bugs.llvm.org/show_bug.cgi?id=50570
2) See e.g.: https://godbolt.org/z/rff7qfK65
3) See the reported values of the feature test macro __cpp_concepts, e.g. here: https://godbolt.org/z/P4z3Pj5vT
|
72,269,830 | 72,270,155 | Printing time_t in a vector struct member | Sorry, I think this might be a silly question. While trying to use ctime to print a time_t inside a vector struct member, the compiler throws me this error argument of type "time_t" is incompatible with parameter of type "const tm *"
struct Trade_Record
{
std::time_t PASP;
};
std::vector<Trade_Record> Trade_Records;
for (std::vector<Trade_Record>::iterator begin = Trade_Records.begin(); begin != Trade_Records.end(); begin++)
{
std::cout << ctime(begin->PASP) << endl;
}
How could I print time_t inside a vector struct member? Thank youuu!!
| Quoting cppreference.com on the matter:
This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static std::tm object which may be shared with std::gmtime and std::localtime. POSIX marks this function obsolete and recommends std::strftime instead.
The behavior may be undefined for the values of std::time_t that result in the string longer than 25 characters (e.g. year 10000)
You should use strftime instead:
#include <iostream>
#include <ctime>
int main() {
std::time_t t = std::time(nullptr);
char mbstr[100];
if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&t))) {
std::cout << mbstr << '\n';
}
}
Output:
Tuesday Tue May 17 07:51:34 2022
(See online)
|
72,269,958 | 72,270,009 | Issue with templated Kernel for Efficient Ransac | I am trying to use the efficient Ransac algorithm of CGAL in a function using a templated Kernel, here is a minimal code to reproduce.
#include <CGAL/property_map.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Shape_detection/Efficient_RANSAC.h>
// Type declarations.
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
template < typename K > //comment for working version
void funcTest() {
//typedef CGAL::Exact_predicates_inexact_constructions_kernel K; //uncomment for working version
typedef std::tuple<typename K::Point_3,typename K::Vector_3, size_t, bool> Point_and_normals;
typedef CGAL::Nth_of_tuple_property_map<0, Point_and_normals> Point_map;
typedef CGAL::Nth_of_tuple_property_map<1, Point_and_normals> Normal_map;
typedef CGAL::Shape_detection::Efficient_RANSAC_traits
<K, std::vector<Point_and_normals>, Point_map, Normal_map> TraitsShape;
typedef CGAL::Shape_detection::Efficient_RANSAC<TraitsShape> Efficient_ransac;
typedef CGAL::Shape_detection::Plane<TraitsShape> PlaneRansac;
std::vector<Point_and_normals> points;
Efficient_ransac ransac;
ransac.set_input(points);
ransac.add_shape_factory<PlaneRansac>();
ransac.detect();
}
int main (int argc, char** argv) {
funcTest<Kernel>(); //comment for working version
//funcTest()); //uncomment for working version
return 0;
}
In this code the templated version doesn't build giving this error
tester.cpp:24:39: error: expected primary-expression before ‘>’ token
24 | ransac.add_shape_factory<PlaneRansac>();
| ^
tester.cpp:24:41: error: expected primary-expression before ‘)’ token
24 | ransac.add_shape_factory<PlaneRansac>();
However the issue is not present with the explicit Kernel, my guess is it may come from a typename issue, but I am not sure of what I may be doing wrong on this one.
Any advice, recommandation is welcome
| The problem is that the compiler doesn't know that whether the token < that follows the add_shape_factory is a less-than-operator or a beginning of a template argument list.
We can use the .template construct when calling the member function template to solve this problem as shown below:
ransac.template add_shape_factory<PlaneRansac>();
//-----^^^^^^^^------------------------------------->added template keyword here to indicate that it is a member function template
The .template is used to tell the compiler that the < token is the beginning of the template argument list and not less-than-operator.
|
72,270,503 | 72,272,335 | c++ reinterpret_cast char to int* / adjacent bits are repeatedly set as 1100 | Why does the second example find 1100 instead of 0000 after storing the address in the int pointer and then reading the adjacent bits?
Example 1:
char c = 'a';
int val = *reinterpret_cast<int*>(&c);
val = 97 or 0110 0001
Example 2:
char c = 'a';
int* iptr = reinterpret_cast<int*>(&c);
int val = *iptr;
val = -858993567 or 1100 1100 | 1100 1100 | 1100 1100 | 0110 0001
| Both have undefined behavior, generally already because accessing a char through a int pointer is an aliasing violation.
Even if that was allowed, the size of int will almost certainly be larger than that of char and trying to read an adjacent byte of a variable clearly causes undefined behavior.
And even further, the alignment of a char variable is probably not guaranteed to be large enough for an int.
All in all, it is wrong to expect any particular output from the programs.
In addition, @user253751 points out that the number pattern (1100) is generated in Visual Studio debug build. In the release build, this pattern is not set.
|
72,270,590 | 72,270,663 | c++ entering values two times instead of one | I have to solve this " create class for describing triangle and trapeze with ability to return values and finding S of the figures.. declare function which allows comparing S of the both figures.. in main function declare object triangle and trapeze and compare their areas .. " - im trying to translate it from Bulgarian to English sorry if its not translated correctly ..
Anyways I came up with a solution, but when it asks me to enter value for trapeze x2 times and I can't understand why... it always takes the first 3 entered numbers but I want it to ask for input only once .. sorry if the answer is obvious
//
// main.cpp
// compare S of 2 figures
//
// Created by Георгиос Семерджиев on 17/05/22.
//
#include <iostream>
#include <cmath>
using namespace std;
class Trap // trap class with declared functions inside
{
protected:
double a, c, h;
void setValueTrap();
public:
Trap();
void Print();
virtual double S();
}; // end trap class
class Triangle : public Trap // triangle class with declared function for finding s() print and setting value
{
double b;
void setValueTriangle();
public:
Triangle();
void Print();
virtual double S();
double p(); // returning P/2
}; // end triangle class
// trap functions ...
Trap:: Trap()
{
setValueTrap();
}
void Trap::setValueTrap() // trap input function
{
cout << "Trap enter a = "; cin >> a;
cout << "Trap enter c = "; cin >> c;
cout << "Trap enter h = "; cin >> h;
cout << endl;
}
double Trap::S() // trap calculating and returning s()
{
return ( (a+c) * h ) / 2;
}
void Trap::Print() // printing S() for trap
{
cout << "Trap S = " << S();
cout << endl;
}
// Triangle functions ..
Triangle::Triangle():Trap()
{
setValueTriangle();
}
void Triangle::setValueTriangle() // setting value for triangle a,b,c
{
cout << "Triangle a = "; cin >> a;
cout << "Triangle b = "; cin >> b;
cout << "Triangle c = "; cin >> c;
cout << endl;
}
double Triangle::p() // returning P / 2 = p
{
return (a+b+c) / 2;
}
double Triangle::S() // calculating S() of triangle
{
return sqrt(p() * (p() - a) * (p()-b) * (p()-c));
}
void Triangle::Print()
{
cout << "Triangle S = " << S();
cout << endl;
}
// creating function to compare Trap S() and Triangle S()
bool Compare (Trap *F1, Trap *F2)
{
return F1 -> S() < F2 -> S();
} // compare function
int main()
{
Trap* trap = new Trap();
Triangle* triangle = new Triangle();
trap -> Print(); triangle -> Print();
cout << endl;
if (Compare(trap, triangle))
cout << "the Trap S < Triangle S.." << endl;
else
{
cout << "The Trap S > Triangle S.." << endl;
}
return 0;
}
| For the Triangle constructor you have:
Triangle::Triangle():Trap()
{
setValueTriangle();
}
That will explicitly invoke the Trap constructor which read input. Then you will read the input for the triangle.
It's often not a good idea to read input in a constructor. It's usually better to only do basic initialization in the constructor and then get input using the fully constructed object.
Note that even if you don't have the explicit invokation of the Trap constructor, this will happen implicitly.
|
72,270,600 | 72,270,677 | Fibonacci number overflow in c++ | I am a c++ newbie, and start learning it by learning algorithm at the same time. However, I encountered some problem when writing this algorithm --- the number overflows, which is quite different to the overflow I thought. To solve the problem, I searched for a long time, but end up in no use. Here is my code:
#include <iostream>
using namespace std;
long long Fs[101];
long long F(int N) {
if (Fs[N] != -1) {
return Fs[N];
}
int res = F(N - 1) + F(N - 2);
Fs[N] = res;
return res;
}
void main() {
// initialize Fs array
for (auto& item : Fs) {
item = -1;
}
Fs[0] = 0;
Fs[1] = 1;
cout << F(60) << endl;
cout << endl;
for (auto& item : Fs) {
cout << item << endl;
}
}
Part of the result is shown here:
165580141
267914296
433494437
701408733
1134903170
1836311903
-1323752223
512559680
-811192543
Question:
You can see that the overflow number is quite small than the minimum value of long long type. Why this happened?
Appendix
I found some way to print the overflow index of unsigned type when generating fibonacci, here is the code:
#include <iostream>
#include <limits>
using namespace std;
#define outFibonacci(nType) { int i = 1;\
while (i++)\
if (Fibonacci<nType>(i+1)==Fibonacci<nType>(i+2)){\
cout<<"F("<<i<<")\t= "<<Fibonacci<nType>(i)<<endl;\
break;\
}\
cout<< "Max Num\t= " << numeric_limits<nType>::max() << endl << endl;\
}
template<typename _T> _T Fibonacci(_T n){
_T f, f1, f2;
f = f1 = f2 = 1;
for (auto i=3; i<=n; ++i){
f = f1 + f2;
if (f<f2){ // Set overflow condition
f=-1;
break;
}
f1 = f2;
f2 = f;
}
return f;
}
int main(void)
{
outFibonacci(unsigned short);
outFibonacci(unsigned int);
outFibonacci(unsigned long);
outFibonacci(unsigned long long);
outFibonacci(size_t);
return 0;
}
and here is my result:
F(24) = 46368
Max Num = 65535
F(47) = 2971215073
Max Num = 4294967295
F(47) = 2971215073
Max Num = 4294967295
F(93) = 12200160415121876738
Max Num = 18446744073709551615
F(93) = 12200160415121876738
Max Num = 18446744073709551615
| This line in your function int res = F(N - 1) + F(N - 2); makes your result an int, which is then casted to long long. so the overflow occurs here. Should be flagged by some compilers flags tho.
long long F(int N) {
if (Fs[N] != -1) {
return Fs[N];
}
// int res = F(N - 1) + F(N - 2); // HERE !
long long res = F(N - 1) + F(N - 2);
Fs[N] = res;
return res;
}
|
72,270,978 | 72,273,758 | Get wrong value from int* to JintArray in jni | I have a c function int* GenerateIntArray()
it will generate a int array like [0,8,28,108,0,3] and return by Int*
int* GenerateIntArray(){
int rtn[6]={0,8,28,108,0,3};
return rtn;
}
in my jni layer : fun getIntArrayFromJNI:JIntArray
I do this for get Int* from C Lib
jintArray rtn = env->NewIntArray(6);
int *temp = C_GetINTArrayData();
env->SetIntArrayRegion(rtn, 0, 6, temp);
return rtn;
and convert it to IntArray
but in Android Layer: fun getIntArrInAndroid():IntArray
var result=getIntArrayFromJNI()
I check the data list
it show [-214587424,119,0,0,205189680,-1275068295]
is somewhere wrong to convert Int array?
| When you want to do that in this way, you can change your void GenerateIntArray() code to:
int* GenerateIntArray()
{
static int rtn[6]={0,8,28,108,0,3};
return rtn;
}
Because, the int array is allocated on the stack and will be disappear when the function returns.
|
72,271,018 | 72,271,519 | How to use windows api GetPackagesByPackageFamily in CSharp? | API [GetPackagesByPackageFamily] in appmodel.h
#include <Windows.h>
#include <appmodel.h>
...
WINBASEAPI
_Check_return_
_Success_(return == ERROR_SUCCESS)
_On_failure_(_Unchanged_(*count))
_On_failure_(_Unchanged_(*bufferLength))
LONG
WINAPI
GetPackagesByPackageFamily(
_In_ PCWSTR packageFamilyName,
_Inout_ UINT32* count,
_Out_writes_opt_(*count) PWSTR* packageFullNames,
_Inout_ UINT32* bufferLength,
_Out_writes_opt_(*bufferLength) WCHAR* buffer
);
...
I want to use it in C#, so I define it like this in C#.
[DllImport(@"kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, EntryPoint = "GetPackagesByPackageFamily")]
private static extern long GetPackagesByPackageFamily(
string packageFamilyName,
ref uint count,
out string[] packageFullNames,
ref uint bufferLength,
out string buffer);
But the call runs wrong, how can I modify it?
| You can have a look at this library: https://github.com/dahall/Vanara/ that offers exactly that P/Invoke.
They are implementing it like that:
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern long GetPackagesByPackageFamily(string packageFamilyName, ref uint count, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] packageFullNames, ref uint bufferLength, IntPtr buffer);
(see here https://github.com/dahall/Vanara/blob/3f64f6d9d4c963070e31823ca8a720068ac07fe2/PInvoke/Kernel32/AppModel.cs
)
|
72,271,558 | 72,272,860 | use fstream to read and write in the same time | I am learning how to read and write from file . There is a problem that when I try to write (--something in the file letter for example--) after reading or read after writing in the file
using fstream
something wrong is happening. I tried to just write or read and it worked. what is the problem?
the file content is :
abcdefgh
ijklmnopqr
stuvw
xyz
and the code is :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream ioFile;
char ch;
ioFile.open("search.txt", ios::in | ios::out);
if (!ioFile)
{
cout << "problem opening the file";
goto k270;
}
while (ioFile>>ch)
{
if (ch == 'z')
{
ioFile.seekp(((int)ioFile.tellg()));
ioFile << "x";
}
}
//cout<<ioFile.rdbuf();
ioFile.close();
k270:
system("pause");
return 0;
}
| Look at this answer: https://stackoverflow.com/a/17567454/11829247 it explains the error you are experiencing.
Short version: Input and output is buffered and interleaving reads and writes only work if you force buffer updates in between.
This works for me:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream ioFile;
char ch;
ioFile.open("search.txt", std::ios::in | std::ios::out);
if (!ioFile)
{
std::cout << "problem opening the file";
return 1;
}
while (ioFile >> ch)
{
if (ch == 'z')
{
ioFile.seekp(-1, std::ios_base::cur);
ioFile << "x";
ioFile.flush();
}
}
ioFile.close();
return 0;
}
The difference is that I use ioFile.seekp(-1, std::ios_base::cur); to move one step back from the current position. You could also use ioFile.seekp((int)ioFile.tellg() -1); - note the -1.
Then after stepping back and overwriting the z, use ioFile.flush(); to force the write to be pushed to file. This also means that the read buffer is updated, without this the read operation just steps back in its buffer and keeps reading the same buffered z.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.