question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,597,027 | 70,687,515 | GPU Memory Management in OpenGL and DirectX 12 | I am currently improving my knowledge in OpenGL and DirectX 12 in order to create graphics applications with both APIs. I studied several tutorials but I still do not completely understand, how the memory is managed on the GPU side.
In OpenGL (my application runs an OpenGL 3.3 context), the frame buffers are created implicitly so I assume, that they are also freed implicitly by the API. In my example program, I created vertex and index buffers using glGenBuffers and uploaded them to the GPU using glBufferData. In case I want to update my vertex buffer every frame, I could simply do this using glBufferSubData. Let's assume instead, that I want to re-upload my vertex buffer every frame using glBufferData. According to the OpenGL documentation, this function creates and initializes the buffer's data store on the GPU. So I assume, that the GPU memory, mapped to this VBO is reused after another call to glBufferData in the next frame.
In DirectX 12, the frame buffers must be created by the graphics programmer. Those are managed and reused by the swap chain during the life time of the program. In my DirectX 12 test program, I also create vertex and index buffers using upload heaps and the ID3D12Device::CreateCommittedResource function. I also do this every frame for testing purposes. The buffers are stored in Microsoft::WRL::ComPtr<ID3D12Resource> variables. At the end of the render method, the use count of those buffer pointers should hit 0, which will free the memory behind on the CPU side. Nevertheless, I do not understand, what happens to the data and the underlying heap on the GPU side. Are they released, whenever the buffer pointer's use count hits 0, do they need to be freed manually, are they discarded by the GPU when reaching the fence or none of them.
I would really appreciate it, if you could provide some clarifications on this topic and my assumptions.
Can you also please provide an explanation, if and how GPU data needs to be freed by the graphics programmer.
Best regards.
| For DirectX 12, it uses the same lifetime model as previous versions of Direct3D: The object is kept alive until the reference count hits 0. It's then eligible for destruction. The exact time of cleanup is up to the driver/runtime as it typically does 'delayed destruction' (it actually has both an 'internal' and 'external' reference count, and both have to be 0 before it's really eligible for destruction).
See Microsoft Docs.
You should watch this YouTube video if you want an overview of the underlying details.
|
70,597,506 | 70,597,619 | Does Enum have any downsides to using | Recently I found out that there is such a thing as enumerations in C and C ++.
It immediately seemed to me that it is very visually convenient.
But, please tell me, does the enum have any negative aspects?
If I use them extensively in my code - will this not lead to some kind of problem in the future?
|
Here are the drawbacks of the classical enumerations:
The enumerators have no scope (C)
The enumerators implicitly convert to implicitly to int
The enumerators pollute the global namespace
The type of the enumerator is not defined. It just has to be big enough to hold the enumerator.
This link contains relevant and complete information for the question you asked
|
70,597,800 | 70,598,258 | Convert from std::wstring to std::string | I'm converting wstring to string with std::codecvt_utf8 as described in this question, but when I tried Greek or Chinese alphabet symbols are corrupted, I can see it in the debug Locals window, for example 日本 became "日本"
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; //also tried codecvt_utf8_utf16
std::string str = myconv.to_bytes(wstr);
What am I doing wrong?
| std::string simply holds an array of bytes. It does not hold information about the encoding in which these bytes are supposed to be interpreted, nor do the standard library functions or std::string member functions generally assume anything about the encoding. They handle the contents as just an array of bytes.
Therefore when the contents of a std::string need to be presented, the presenter needs to make some guess about the intended encoding of the string, if that information is not provided in some other way.
I am assuming that the encoding you intend to convert to is UTF8, given that you are using std::codecvt_utf8.
But if you are using Virtual Studio, the debugger simply assumes one specific encoding, at least by default. That encoding is not UTF8, but I suppose probably code page 1252.
As verification, python gives the following:
>>> '日本'.encode('utf8').decode('cp1252')
'日本'
Your string does seem to be the UTF8 encoding of 日本 interpreted as if it was cp1252 encoded.
Therefore the conversion seems to have worked as intended.
As mentioned by @MarkTolonen in the comments, the encoding to assume for a string variable can be specified to UTF8 in the Visual Studio debugger with the s8 specifier, as explained in the documentation.
|
70,597,988 | 70,598,081 | Generic friend operator== overload | I am currently stuck on a problem that I can't solve. I am a beginner in the world of c++.
For a homework, I have to create a generic class to represent a fraction like 5/6 or 11/4. This class is generic which allows to determine the type of the nominator and numerator (unsigned short, unsigned, unsigned long).
The goal is to be able to add, subtract, multiply, divide and compare fractions. In a first phase, I created a class and operator overloads allowing me to do everything that is required but only for instances of the class with the same type.
Now I would like to improve the existing code to be able to perform operations between fractions of different types like for example: Frac<unsigned> == Frac<unsigned short>. But there is something I don't understand in the syntax of overloading operators.
Let's take the == operator as an example:
template <typename T>
bool operator==(const Frac<T>& lhs, const Frac<T>& rhs) {
return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator);
}
template <typename T>
class Frac {
friend bool operator== <>(const Frac& lhs, const Frac& rhs);
private:
T numerator, denominator;
};
this is the current version that worked for the Fracs of the same type. But now I would like it to work for Fracs of a different type:
template <typename T>
class Frac;
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs){
return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator)
}
template <typename T>
class Frac {
friend bool operator== <>(const Frac& lhs, const Frac& rhs);
private:
T numerator, denominator;
};
But I have a compilation error when I want to compare Frac of different types... I don't understand and didn't find any solution explaining concretely what the problem was and how to implement this kind of solution properly.
Could you help me please ?
I hope my question is clear and complete.
| You can do this the following way:
template <typename T>
class Frac {
//friend declaration
template <typename S, typename U> friend
bool operator==(const Frac<S>& lhs, const Frac<U>& rhs);
private:
T numerator, denominator;
};
template <typename T, typename U>
bool operator==(const Frac<T>& lhs, const Frac<U>& rhs){
return ((lhs.numerator == rhs.numerator) && (lhs.denominator == rhs.denominator));
}
Now you will be able to compare Frac for different types as you want.
|
70,598,124 | 70,601,026 | Calling child method from obj of parent class | I have a couple of classes derived from Element. Each of them has a generate() method that returns something. Also, I have a Rep class that is derived from Element, too.
I need to initialize a Rep object with any of Element children and be able to call generate().
#include <string>
#include <vector>
#include <iostream>
class Element{
};
class Any : public Element{
std::string text;
public:
Any(std::string text) : text(text) {};
char generate(); //returns random symbol
};
class Per : public Element{
std::string text;
public:
Per(std::string text) : text(text) {};
std::string generate();
};
class Format : public Element{
int format;
std::string text;
public:
Format(int format, std::string text) : format(format), text(text) {};
std::string generate();
};
class Rep : public Element{
int count;
Element action;
public:
Rep(int count, Element action) : count(count), action(action) {};
void generate(){
for(int i = 0; i<count; i++)
std::cout<<action.generate();
}
};
//i want to do this
int main(){
Rep a(10, Any("help"));
a.generate(); //eg. "ehplhppelh"
}
| Rep is slicing the Element it is being given. And Element does not have a generate() method. But even if it did, it would have to be virtual, but you can't overload a virtual method based solely on its return type.
I would suggest making Rep be a template class instead, eg:
template<typename ActionType>
class Rep : public Element{
int count;
ActionType action;
public:
Rep(int count, const ActionType &action) : count(count), action(action) {};
void generate(){
for(int i = 0; i < count; ++i)
std::cout << action.generate();
}
};
int main(){
Rep<Any> a(10, "help");
a.generate();
}
Otherwise, consider giving Element a virtual generate() that returns a std::variant, eg:
#include <string>
#include <vector>
#include <iostream>
#include <variant>
using var_t = std::variant<char, std::string, std::monostate>;
class Element{
public:
virtual var_t generate() const = 0;
};
class Any : public Element{
std::string text;
public:
Any(std::string text) : text(text) {};
var_t generate() const override; //returns random symbol
};
class Per : public Element{
std::string text;
public:
Per(std::string text) : text(text) {};
var_t generate() const override;
};
class Format : public Element{
int format;
std::string text;
public:
Format(int format, std::string text) : format(format), text(text) {};
var_t generate() const override;
};
class Rep : public Element{
int count;
Element &action;
public:
Rep(int count, Element& action) : count(count), action(action) {};
var_t generate() const override {
for(int i = 0; i < count; ++i) {
std::visit(
[](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (!std::is_same_v<T, std::monostate>)
std::cout << args;
},
action.generate()
);
}
return std::monostate{};
}
};
int main(){
Any a("help");
Rep r(10, a);
r.generate();
}
|
70,598,245 | 70,600,534 | Initialize pointer member in struct with array of ints | I have an int* member in my struct. I want to initialize this member while initializing the struct, without having to resort to a temp array:
struct MyStruct{
int* arrInts;
};
MyStruct m = {
{1, 2} // Nor does compound literals work: (int[]){2, 4, 6}
};
This throws an error in MSVC 2019. So a temp int array wont be created by the compiler.
This struct is used to pass arguments to a DLL function, so I am trying to avoid STL classes object to be passed across the DLL boundary. The number of elements are not known beforehand so I can't declare a fixed size array as a struct member.
Regd the DLL function, it will simply store the passed data into a class member. The class is declared and used inside the DLL. I will use a std::vector there of course. I just want to avoid it at the DLL boundary/API and using basic types.
What are my alternatives?
| That is solution b: A compatible replacement for int*.
In this version I disabled the copy constructor and copy assignment altogether. If you want to copy, you have to decide and specify what happens with the arrInts array (e.g. should another array be allocated or the pointer should point at the same array).
The arrInts pointer can be accessed as m.arrInts and the elements as m.arrInts[0]. So everything normal. There is an implicit conversion operator to (in this case) int* defined.
You can send the MyStruct to the DLL. At the other side (if also implemented by you) you would define MyStruct with an int* type for the array.
The CompatArray has one pointer as member variable, which is put at the correct position in the MyStruct. So the layout is identical.
The array is created on the heap, when MyStruct is constructed, and the pointer is stored in the MyStruct. As soon as the MyStruct object goes out of scope, the MyStruct object is deleted together at the same time as the array.
template <typename T>
struct CompatArray {
template <typename... Types>
CompatArray(Types... l) : a(new T[]{ l... }) {};
~CompatArray() { delete[] a; };
CompatArray(const CompatArray& m) = delete;
CompatArray& operator=(const CompatArray& other) = delete;
operator T*() { return a; };
T* a;
};
struct MyStruct {
int w;
float x;
CompatArray<int> arrInts;
double y;
};
int main() {
MyStruct m = {4, .5f, { 4, 1, 2 }, 9.};
}
That is solution d: Derive from MyStruct
Advantages: The std::shared_ptr provides copy and move semantics. Copies share the same arrInts array. The shared_ptr keeps track of a usage counter.
The derived struct MySuperStruct can be used as a MyStruct. The additional member variable s for the shared_ptr is added to the end of the class. arrInts keeps a copy of the raw pointer.
It is possible to overwrite the array with store() or do it only for copies. This is all handled by the shared_ptr.
#include <memory>
struct MyStruct {
int w;
float x;
int* arrInts;
double y;
};
struct MySuperStruct : public MyStruct {
template <typename... Types>
MySuperStruct(Types... l) : MyStruct(l...) {};
template <typename... Types>
void store(Types... l) {
s = std::shared_ptr<int>(new int[]{ l... }, std::default_delete<int[]>());
arrInts = s.get();
};
std::shared_ptr<int> s;
};
extern "C" void callDll(MyStruct* m);
int main() {
MySuperStruct m = {4, .5f, nullptr, 9.};
m.store(4, 1, 2);
m.store(5, 0, -8, 6);
MySuperStruct m2 = m;
callDll(&m);
}
|
70,598,413 | 70,598,874 | Why does std:sqrt on Eigen's diagonal().row() fail with "no instance of overloaded function matches argument list" | I am trying to calculate the square root of each element of the .diagonal() of a Eigen::Matrix3d. Using
std::sqrt(matrix.diagonal().row(i))
will give me a compile error:
no instance of overloaded function "std::sqrt" matches the argument
list -- argument types are:
(Eigen::Block<Eigen::Diagonal<Eigen::Matrix<double, 3, 3, 0, 3, 3>,
0>, 1, 1, false>)C/C++(304)
I am using .row() in a for-loop to access each row of the diagonal vector.
Each element of the .diagonal() vector should be type double.
I am using a pointer dereference - but when I just print the .row() it works.
I guess the problem is within sqrt and the returned value from .row(). What am I doing wrong?
EDIT: .diagonal().array().sqrt() does the trick.
| It's because the result type of matrix.diagonal().row(n) is a one by one matrix. You can convert this to a flat type with the .value() member function:
#include <iostream>
#include <Eigen/Dense>
int main()
{
Eigen::Matrix3f m;
m << 1, 2, 3,
4, 5, 6,
7, 8, 9;
std::cout << std::sqrt( m.diagonal().row(1).value() ) << "\n";
return 0;
}
|
70,599,707 | 70,599,835 | Removal of the punctuation from strings given as an input by the user | Am presently reading the book C Primer 5th edition, and this question is asked in the book, question problem being 3.10.
So, basically we have to remove the punctuations if they exist in the string that we would provide it with.
I've attempted the question and even I get the successful output when I initialize the string beforehand. Here is my code with strings being initialized before the code execution:
Code:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s("he@@,llo world...!!@");
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
This particular code provides with the correct output, i.e. hello world.
Now, if I try to use the same code format but with the condition that the user would have to provide the string as an input then the code doesn't gives the correct output, it just ignores the rest part of the string after the whitespace.
The code that I tried is:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s;
cin>>s;
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
During the execution of the code when I put the string input as he@@,llo world...!!@
The code provides me with the output: hello. The next part of the string after the whitespace gets ignored.
Well, my question is,
Why does this code doesn't works when the string is taken as the form
of input by the user? And what can I do to make the code work without
any errors?
Edit about suggestion:
The current suggestion provided by one of the community members doesn't answers my question, as it is not about taking the input from a user and formatting the input in a file, whereas the question asked here is about the removal of the punctuation and characters and printing the rest part of the string when an input is provided by the user.
| Standard cin >> only gets the first "word" in a line; words are typically separated by a space, which is why everything after the space after he@@,llo is ignored. What you need to use instead is getline(cin, s) to capture the entire line.
|
70,599,823 | 70,600,770 | Shared_ptr instance is not set for an object as expected | I have a struct A which has a member another struct C. So A with c1Ptr_ as member.
I use 2 structs S and N. N has as member A, a_ and S has as member C, c_.
After I instantiated A and create for S a c object using the created A object and I pass the created A object to N I would expect to have the A->c1Ptr_ in N as well.
Thank you.
#include <iostream>
#include <memory>
using namespace std;
struct C1
{
C1(int x):x_(x)
{
std::cout<<"-C1: x_: " << x_ << std::endl;
}
int x_;
~C1()
{
std::cout<<"-DC1: x_: " << x_ << std::endl;
}
};
using C1ptr = std::shared_ptr<C1>;
struct A
{
C1ptr c1Ptr;
};
struct S
{
S(C1ptr& c1Ptr):c1Ptr_(c1Ptr)
{
}
C1ptr c1Ptr_;
};
struct N
{
N(std::shared_ptr<A> a):a_(a)
{
}
std::shared_ptr<A> a_;
};
int main()
{
std::shared_ptr<A> a = std::make_shared<A>();
S s(a->c1Ptr);
N n(a);
s.c1Ptr_ = std::make_shared<C1>(12);
if (n.a_->c1Ptr)
{
std::cout<<"c1Ptr is set for N\n";
}
else
{
std::cout<<"c1Ptr is NOT set for N\n"; // why c1Ptr is not set for n.a_ ?
}
return 0;
}
| You can try to work this out on your own by drawing the objects a, s, and n and their contents, and what their contents point to:
auto a = std::make_shared<A>(); // a(c1Ptr_ = null)
S s(a->c1Ptr_); // a(c1Ptr_ = null), s(c1Ptr_ = null)
N n(a); // a(c1Ptr_ = null), s(c1Ptr_ = null), n(a_ = a)
// [n.a_ points to a]
After this initial block of instructions:
a and s have their shared pointer members c1Ptr_ with a value of nullptr.
n has its shared pointer member a_ pointing to the object a.
s.c1Ptr_ = std::make_shared<C1>(12); // (1) a(c1Ptr_ = null), s(c1Ptr_->x_ = 12 ), n(a_ = a)
// [and you modify s]
if (n.a_->c1Ptr_) {
std::cout << "c1Ptr is set for N\n\n";
}
else {
std::cout << "c1Ptr is NOT set for N\n\n"; // (1)
}
Here:
you just modify s.c1Ptr_, but that doesn't affect a, and ultimately, n.
s.c1Ptr_ was originally set to point to the same C1 object as a.c1Ptr_ (actually, nullptr); now you're just making it point to something else.
a->c1Ptr_ = std::make_shared<C1>(15); // (2) a(c1Ptr_->x_ = 15 ), s(c1Ptr_->x_ = 12 ), n(a_ = a)
// [and you modify a]
if (n.a_->c1Ptr_) {
std::cout << "c1Ptr is set for N\n\n"; // (2)
}
else {
std::cout << "c1Ptr is NOT set for N\n\n";
}
What would have happened if you had changed a->c1Ptr_ instead? Since n->a_ points to a and we are modifying a, n->a_->c1Ptr_ is also set.
[Demo]
|
70,600,162 | 70,600,219 | Double object pointer array as function argument? | I come with a perhaps odd question. I was doing an exercise and I ran into a problem. The point was to make an Employee class, and then a function that has an array of Employee** and its size as an argument, and to make it show every employee with more than 5 years of experience.
Here is the relevant pieces of the Employee class:
//in Employee.h:
int Getexperience() { return experience; }
virtual void show();
//in Employee.cpp:
void Employee::show()
{
cout << "Name: " << this->surname << ", Age: " << this->age << ", Experience: " << this->experience << ", Salary: " << this->salary << endl;
}
And here's the function, written in main.cpp:
void whoWorkMoreThan5Years(Employee** tab[], int size){
for(int i =0; i<size; i++){
if(tab[i]->Getexperience() > 5){
tab[i]->show();
}
}
}
This gets me the error:
error: request for member 'Getexperience' in '* *(tab + ((sizetype)(((unsigned int)i) * 4u)))', which is of pointer type 'Employee*' (maybe you meant to use '->' ?)|
And I honestly have no clue what it's even supposed to mean since
I am using a '->' for the object's method.
I don't know what the
'* *(tab + ((sizetype)(((unsigned int)i) * 4u)))' part even refers
to.
I guess my question is basically: what am I doing wrong here? Is there any special way to use an object's methods in this situation that I just don't know?
| The way you are passing in the array is wrong. Currently Employee** tab[] means that you have an array of pointers to a pointer to an Employee object. What you want to have is either Employee* tab[] or Employee** tab which are both arrays of pointers to an Employee object.
Note that Employee** is the same as Employee* tab[] because arrays decay into pointers.
|
70,600,536 | 70,600,738 | how to properly convert byte array in java to char pointer in jni | I am new to C/C++, so I don't know how to properly convert a byte array in Java to a char array in JNI.
For example, I have an inputString containing "Hello world!", I use this to get the byte array:
byte[] data = inputString.getBytes();
Then in the JNI layer, I use:
jbyte *array = (*env)->GetByteArrayElements(env, data, &isCopy);
argv[1] = (char *)array;
Then when I print the argv[1], it is "Hello world!ZE".
Why is there extra characters "ZE" here?
Would anyone explain this, and provide me the right solution to convert byte[] to char* pointer? I need the char* pointer because the interface I am given is char* pointer for me.
| Your byte[] array is not null-terminated (does not end with a 0x00 byte), but you are clearly treating it as if it were. When printing the bytes, the "extra" characters are random values coming from surrounding memory when the print accesses beyond the bounds of the array, which is undefined behavior.
Use (*env)->GetArrayLength() to find out how many bytes are actually in the array, and then don't access more bytes than that, eg:
jint len = (*env)->GetArrayLength(env, data);
jbyte *array = (*env)->GetByteArrayElements(env, data, &isCopy);
argv[1] = (char*) array;
...
printf("%.*s", len, argv[1]);
...
(*env)->ReleaseByteArrayElements(env, data, array, JNI_ABORT);
If you really need a null-terminated string (or just need to hold on to the data longer than the Java byte[] array will exist), you will have to allocate your own char[] buffer with extra room for a terminator, and then copy the byte[] array data into that buffer, eg:
jint len = (*env)->GetArrayLength(env, data);
jbyte *array = malloc(len + 1);
if (array) {
(*env)->GetByteArrayRegion(env, data, 0, len, array);
array[len] = 0x00;
}
argv[1] = (char*) array;
...
printf("%s", argv[1]);
...
free(argv[1]);
|
70,600,886 | 70,602,114 | How do I use a composed Asio operation with C++20 coroutines to return a value? | I have a composed async operation which uses non-boost Asio 1.18.1 to resolve and connect to a host and service.
I want it to pass the actual endpoint it connects to, to the completion token. Right now it does not.
#include <iostream>
#include <string_view>
#include "asio.hpp"
template <typename Token, typename Executor>
auto async_connect_to(Executor&& executor, asio::ip::tcp::socket& socket,
asio::ip::tcp::resolver& resolver, std::string_view host,
std::string_view service, Token&& token) {
return asio::async_compose<Token, void()>(
[&](auto& self) {
co_spawn(
executor,
[&]() -> asio::awaitable<void> {
auto results = co_await resolver.async_resolve(host, service, asio::use_awaitable);
auto endpoint = co_await asio::async_connect(socket, results, asio::use_awaitable);
self.complete();
co_return;
},
asio::detached);
},
token, executor);
}
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage: client <host> <port>\n";
return 1;
}
asio::io_context io_context;
asio::ip::tcp::socket socket(io_context);
asio::ip::tcp::resolver resolver(io_context);
async_connect_to(io_context, socket, resolver, argv[1], argv[2],
[](asio::ip::tcp::endpoint endpoint = {}) {
std::cout << "connected to: " << endpoint << "\n";
});
try {
io_context.run();
} catch (std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
return 0;
}
Because I'm doing self.complete(), the completion handler in main never actually gets the endpoint we connected to so it's defaulted.
How do I actually return a value from this composed async operation?
How do I improve the error handling so that the completion handler can take the signature (error_code, tcp::endpoint) instead of just (tcp::endpoint), i.e. so that it works the same way as built-in async operations? (I believe this is straightforward after the first question is answered)
The docs do not provide an example with async_compose and coroutines, nor with returning a value from co_spawn.
| I thought I had already tried this, but just changing the signature of the async_compose template parameter and self.complete works.
For errors it seems like you need to explicitly catch the system_error, pass it as a error_code to the completion handler, and it may be either passed to the completion handler of the user or converted back into a system_error with something like a use_future token.
As Andrew suggested in the comments, I also move-capture self into the coroutine and make the lambda mutable.
template <typename Token, typename Executor>
auto async_connect_to(Executor&& executor, asio::ip::tcp::socket& socket,
asio::ip::tcp::resolver& resolver, std::string_view host,
std::string_view service, Token&& token) {
return asio::async_compose<Token,
void(std::error_code, asio::ip::tcp::endpoint)>(
[&](auto& self) {
co_spawn(
executor,
[&, self = std::move(self)]() mutable -> asio::awaitable<void> {
try {
auto results = co_await resolver.async_resolve(
host, service, asio::use_awaitable);
auto endpoint = co_await asio::async_connect(
socket, results, asio::use_awaitable);
self.complete({}, endpoint);
} catch (std::system_error& e) {
self.complete(e.code(), {});
}
co_return;
},
asio::detached);
},
token, executor);
}
This seems to work fine like this:
async_connect_to(
io_context, socket, resolver, argv[1], argv[2],
[](std::error_code ec, asio::ip::tcp::endpoint endpoint = {}) {
if (ec) {
std::cout << "error: " << ec.message() << "\n";
} else {
std::cout << "connected to: " << endpoint << "\n";
}
});
And with futures:
auto f = async_connect_to(io_context, socket, resolver, argv[1], argv[2], asio::use_future);
try {
auto endpoint = f.get();
std::cout << "connected to: " << endpoint << "\n";
} catch (std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
}
|
70,601,602 | 70,608,644 | How to work with Rcpp strings variables which could be NULL? | I am writing an R package + Rcpp code to work with an existing C++ library.
After going through the tutorials here: https://gallery.rcpp.org/articles/optional-null-function-arguments/ , I'm struggling with how to work with NULL and strings. I am confused that I cannot cast from type Rcpp::Nullable<std::string> to std::string (or equivalently Rcpp::Nullable<Rcpp::String> to Rcpp::String
Within C++, I am checking for whether the string (in C++) is empty or not. If the string is empty, I want to return NULL. If the string (in C++) is not empty, I want to return the string.
My example code is below, modifying the function rcpp_hello_world() provided by the Rcpp.package.skeleton() for simplicity. My goal is to return within R a list (Rcpp::List) containing either a string, or NULL (if the string is empty).
#include <Rcpp.h>
#include <string>
using namespace Rcpp;
// [[Rcpp::export]]
Rcpp::List rcpp_hello_world() {
// After calculations from external C++ library,
// the variable 'mystring' will either empty (i.e. "") or populated (e.g. "helloworld")
std::string mystring = "helloworld"; // string non-empty
Rcpp::Nullable<std::string> result_string = R_NilValue;
if (!mystring.empty()) {
std::string result_string(mystring);
}
Rcpp::List z = List::create(result_string);
return z ;
}
The resulting variable result_string in the above example should either be NULL or "mystring"---however, the above will always return NULL, which is not the desired behavior.
I then tried to see if I could even convert types between Rcpp::Nullable<std::string> and std::string:
std::string mystring = "helloworld";
Rcpp::Nullable<std::string> result_string = R_NilValue;
std::string result_string(mystring);
This results in a compilation error:
error: redefinition of 'result_string' with a different type: 'std::string'
(aka 'basic_string<char, char_traits<char>, allocator<char>>') vs 'Rcpp::Nullable<std::string>'
(aka 'Nullable<basic_string<char, char_traits<char>, allocator<char>>>')
Am I using the wrong data structures for this operation? Or is there a better way to work with strings if the value could be NULL?
| Here is a minimally complete answer. In the function body you can adjust your tests according to your needs, this is just a placeholder example.
Code
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::List foo(Rcpp::NumericVector v) {
// we just us a random vector here to determine: if positive
// we inject a string, if negative NULL
const std::string mystring = "helloworld"; // if positive
int n = v.size();
Rcpp::List z(n);
for (int i=0; i<n; i++) {
if (v[i] < 0) {
z[i] = mystring;
} else {
z[i] = R_NilValue;
}
}
return z;
}
/*** R
set.seed(123)
foo(rnorm(3)))
set.seed(123456)
foo(rnorm(3))
*/
Output
> Rcpp::sourceCpp("~/git/stackoverflow/70601602/answer.cpp")
> set.seed(123)
> foo(rnorm(3))
[[1]]
[1] "helloworld"
[[2]]
[1] "helloworld"
[[3]]
NULL
> set.seed(123456)
> foo(rnorm(3))
[[1]]
NULL
[[2]]
[1] "helloworld"
[[3]]
[1] "helloworld"
>
|
70,601,822 | 70,602,002 | In practice, when `std::unordered_map` must be used instead of `std::map`? | In practice, is there any circumstance which std::unordered_map must be used instead of std::map?
I know the differences between them, say internal implementation,time complexity for searching element and so on.
But I really can't find a circumstance where std::unordered_map could not be replaced by std::map indeed.
|
I know the difference between them, say internal implementation,time complexity for searching element
In that case, you should know that that the average asymptotic element lookup time complexity of unordered map is constant, while the complexity of ordered map is logarithmic. This means that there is some size of container at which point the lookup will be faster when using unordered map.
But I really can't find a circumstance where std::unordered_map could not be replaced by std::map indeed.
If the container is large enough, and if you cannot afford the cost of ordered map lookup, then you cannot choose to replace the faster unordered map lookup.
Another case where ordered map cannot be used is where there doesn't exist a cheap function to compare relative order of the key.
|
70,601,992 | 70,603,934 | c++ thread local counter implement | I wanna implement a high performance counter in multi-thread process, like this, each thread has a thread local counter named "t_counter" to count query(incr 1/query) and in "timer thread" there is a counter named "global_counter", what I want is each second, global_counter will get each t_counter(s) and add them to global_counter, but I dont know how to get each t_counter value in "timer thread". additional, which section will thread local value lay in main memory ? .data or heap or other? how to dynamic allocate memory size(there maybe 10 thread or 100 thread) ? and does x86-64 use segment register store such value?
| Starting with your second question, you can find all the specifications here.
Summarizing, thread local variables are defined in .tdata / .tbss. Those are somewhat similar to .data, however accessing those is different. These sections are replicated per thread. The actual variable offset is computed at the runtime.
A variable is identified by an offset in .tdata. Speaking of x86_64 it will use the FS segment register to find the TCB (Thread control block), using the data structures stored there it will locate the thread local storage where the variable is located. Note that all allocations are done lazily if possible.
Now, regarding your first question - I am not aware of a way to just list all the thread local variables from another thread, and I doubt it is available.
However, a thread can take a pointer to thread variable, and pass it to another thread. So what you probably need is some registration mechanism.
Each new thread will register itself to some main store, then unregister on termination. Registration and deregistration are on your responsibility.
Schematically, it would look like this:
thread_local int counter = 0;
std::map<std::thread::id, int *> regs;
void register() {
// Take some lock here or other synchronization, maybe RW lock
regs[std::this_thread::get_id()] = &counter;
}
void unregister() {
// Again, some lock or other synchronization
regs.erase(std::this_thread::get_id());
}
void thread_main() {
register();
counter++;
unregister();
}
void get_sum() {
// Again, some lock, maybe only read lock
return std::accumulate(regs.begin(), regs.end(), 0,
[](int previous, const auto& element)
{ return previous + *element.second; });
}
|
70,602,043 | 70,641,231 | Avoid memory fragmentation when memory pools are a bad idea | I am developing a C++ application, where the program run endlessly, allocating and freeing millions of strings (char*) over time. And RAM usage is a serious consideration in the program. This results in RAM usage getting higher and higher over time. I think the problem is heap fragmentation. And I really need to find a solution.
You can see in the image, after millions of allocation and freeing in the program, the usage is just increasing. And the way I am testing it, I know for a fact that the data it stores is not increasing. I can guess that you will ask, "How are you sure of that?", "How are you sure it's not just a memory leak?", Well.
This test run much longer. I run malloc_trim(0), whenever possible in my program. And it seems, application can finally return the unused memory to the OS, and it goes almost to zero (the actual data size my program has currently). This implies the problem is not a memory leak. But I can't rely on this behavior, the allocation and freeing pattern of my program is random, what if it never releases the memory ?
I said memory pools are a bad idea for this project in the title. Of course I don't have absolute knowledge. But the strings I am allocating can be anything between 30-4000 bytes. Which makes many optimizations and clever ideas much harder. Memory pools are one of them.
I am using GCC 11 / G++ 11 as a compiler. If some old versions have bad allocators. I shouldn't have that problem.
How am I getting memory usage ? Python psutil module. proc.memory_full_info()[0], which gives me RSS.
Of course, you don't know the details of my program. It is still a valid question, if this is indeed because of heap fragmentation. Well what I can say is, I am keeping a up to date information about how many allocations and frees took place. And I know the element counts of every container in my program. But if you still have some ideas about the causes of the problem, I am open to suggestions.
I can't just allocate, say 4096 bytes for all the strings so it would become easier to optimize. That's the opposite I am trying to do.
So my question is, what do programmers do(what should I do), in an application where millions of alloc's and free's take place over time, and they are of different sizes so memory pools are hard to use efficiently. I can't change what the program does, I can only change implementation details.
Bounty Edit: When trying to utilize memory pools, isn't it possible to make multiple of them, to the extent that there is a pool for every possible byte count ? For example my strings can be something in between 30-4000 bytes. So couldn't somebody make 4000 - 30 + 1, 3971 memory pools, for each and every possible allocation size of the program. Isn't this applicable ? All pools could start small (no not lose much memory), then enlarge, in a balance between performance and memory. I am not trying to make a use of memory pool's ability to reserve big spaces beforehand. I am just trying to effectively reuse freed space, because of frequent alloc's and free's.
Last edit: It turns out that, the memory growth appearing in the graphs, was actually from a http request queue in my program. I failed to see that hundreds of thousands of tests that I did, bloated this queue (something like webhook). And the reasonable explanation of figure 2 is, I finally get DDOS banned from the server (or can't open a connection anymore for some reason), the queue emptied, and the RAM issue resolved. So anyone reading this question later in the future, consider every possibility. It would have never crossed my mind that it was something like this. Not a memory leak, but an implementation detail. Still I think @Hajo Kirchhoff deserves the bounty, his answer was really enlightening.
| If everything really is/works as you say it does and there is no bug you have not yet found, then try this:
malloc and other memory allocation usually uses chunks of 16 bytes anyway, even if the actual requested size is smaller than 16 bytes. So you only need 4000/16 - 30/16 ~ 250 different memory pools.
const int chunk_size = 16;
memory_pools pool[250]; // 250 memory pools, managing '(idx+1)*chunk_size' size
char* reserve_mem(size_t sz)
{
size_t pool_idx_to_use = sz/chunk_size;
char * rc=pool[pool_idx_to_use].allocate();
}
IOW, you have 250 memory pools. pool[0] allocates and manages chunk with a length of 16 bytes. pool[100] manages chunks with 1600 bytes etc...
If you know the length distribution of your strings in advance, you can reserve initial memory for the pools based on this knowledge. Otherwise I'd just probably reserve memory for the pools in 4096 bytes increment.
Because while the malloc C heap usually allocates memory in multiple of 16 bytes it will (at least unter Windows, but I am guessing, Linux is similar here) ask the OS for memory - which usually works with 4K pages. IOW, the "outer" memory heap managed by the operating system reserves and frees 4096 bytes.
So increasing your own internal memory pool in 4096 bytes means no fragmentation in the OS app heap. This 4096 page size (or multiple of...) comes from the processor architecture. Intel processors have a builtin page size of 4K (or multiple of). Don't know about other processors, but I suspect similar architectures there.
So, to sum it up:
Use chunks of multiple of 16 bytes for your strings per memory pool.
Use chunks of multiple of 4K bytes to increase your memory pool.
That will align the memory use of your application with the memory management of the OS and avoid fragmentation as much as possible.
From the OS point of view, your application will only increment memory in 4K chunks. That's very easy to allocate and release. And there is no fragmentation.
From the internal (lib) C heap management point of view, your application will use memory pools and waste at most 15 bytes per string. Also all similar length allocations will be heaped together, so also no fragmentation.
|
70,602,278 | 70,625,182 | Openmp with more than INT_MAX iterations - is it legal? | Here is a loop that works perfectly fine:
#include <inttypes.h>
#include <iostream>
int main() {
for (int32_t i = -2; i < INT32_MAX-2; i++) {
std::cout << i << std::endl;
}
}
Adding omp parallel for clause seems to break the code by introducing int overflow.
#include <inttypes.h>
#include <iostream>
int main() {
#pragma omp parallel for
for (int32_t i = -2; i < INT32_MAX; i++) {
std::cout << i << std::endl;
}
}
For both clang-10 and gcc-10 the program produces no output. clang-12 on the other hand seems to handle it properly.
clang-10 at least produces some warnings:
> clang++-10 int_div.cpp -Wall -fopenmp
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
for (int i = -2; i < INT32_MAX; i++) {
^
int_div.cpp:133:3: warning: overflow in expression; result is 2147483646 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
int_div.cpp:133:3: warning: overflow in expression; result is -2147483647 with type 'int' [-Winteger-overflow]
Is this a legal, well defined behavior of openmp standard or an implementation bug?
| It's not a bug in a compiler but rather unspecified behavior in OpenMP.
See 2.9.1 Canonical Loop Form
If var is of an integer type, then the type is the type of var.
...
The behavior is unspecified if any intermediate result required to compute the iteration count cannot be represented in the type determined above.
A similar wording can be found on Microsoft site at 241-for-construct:
This computation is made with values in the type of var, after integral promotions. In particular, if value of b - lb + incr can't be represented in that type, the result is indeterminate.
Therefore the computation is done in int resulting in integer overflow thus UB.
|
70,602,526 | 70,602,577 | Search paths "/usr/local/include/glm/gtx" versus Use of undeclared identifier 'gtx' | Mac Big Sur C++ OpenGL attempting to learn quaternions from a tutorial.
The gtx headers are under usr/local/include/glm.
Can anyone figure out what is wrong with my header includes or header search path? Thanks.
Minimum reproducible code that fails for this issue:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h> // for window and keyboard
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
int main ( void )
{
float t =1.0;
// http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/
glm::vec3 RotationAxis(0.0f,1.0f,0.0f);
float RotationAngle = 90 * t;
glm::quat MyQuaternion;
MyQuaternion = gtx::quaternion::angleAxis(glm::degrees(RotationAngle), RotationAxis);
return 0;
}
The build error:
Use of undeclared identifier 'gtx'
which occurs on the line with gtx.
My Build Phases / Header Search Paths / Debug / Any Architecture:
/usr/local/include
/usr/local/include/glm
/usr/local/include/glm/gtx
/usr/local/Cellar
/glew/2.2.0_1/include/GL
/usr/local/Cellar
/glfw/3.3.4/include/GLFW
/usr/local/include/glad/include
My Library Search Paths:
$(inherited) /usr/local/Cellar/glew/2.2.0_1/lib /usr/local/Cellar/glfw/3.3.4/lib /usr/local/include /usr/local/include/glad/include
| In tutorial 1 of the link in the comment, the author introduces
using namespace glm;
which I assume they expect you to use throughout the tutorials.
The namespace that you want to look into is not just gtx, but glm::gtx, so without the using namespace you need to fully qualify it:
MyQuaternion = glm::gtx::quaternion::angleAxis(glm::degrees(RotationAngle), RotationAxis);
However, the tutorial seems to be rather old. As far as I can tell, the entities it uses from the glm::gtx::quaternion namespace have been moved to the glm namespace many years ago, see github commit.
So, without knowing whether anything else changed about these functions, it seems you should replace gtx::quaternion with glm in the code from your question and the tutorial.
|
70,603,024 | 70,604,319 | error: expected primary-expression before ‘long’ long double d = 1/long double(n); | ^~~~ | I wrote a program which takes an integer k and calculates geometric sum till 2^k.
using namespace std;
long double recursive( long double n){
if(n==1){
return 1;
}
long double ans = recursive(2*n);
return n+ans;
}
int main() {
int k;
cin>>k;
int n = 1<<k;
long double d = 1/long double(n);
cout<<recursive(d)<<endl;
return 0;
}
Here while converting n(integer) to long double
long double d = 1.0/long double(n);
I'm getting the following error
error: expected primary-expression before ‘long’
long double d = 1.0/long double(n);
^~~~
Whereas when I declare
double d = 1.0/double(n);
The program runs without any error. Why do I get error when I declare as long double?
I know I can make n as long double while declaring itself, but I wanted to know the reason for this error and how to solve this .
| This is something inherited from C. While doing the code analysis, the compiler sees "long" and "double" as two separate words. The same would occur for something like "unsigned int".
There are multiple ways to achieve what you want. In C you would cast it
long double my_var = 1/(long double)4;
C++ supports this because of legacy compatibility, but it's not compile time checked.
C also provides floating point literals, that are also in C++
long double my_var = 1/4.0L;
In C++ you could make your own alias to the double word type with a using statement
using LongDouble = long double;
auto my_var{1/LongDouble{4}};
But the preferred C++ way is to use static_cast
auto my_var{1/static_cast<long double>(4)};
|
70,603,855 | 70,704,065 | How to set python function as callback for c++ using pybind11? | typedef bool (*ftype_callback)(ClientInterface* client, const Member* member ,int member_num);
struct Member{
char x[64];
int y;
};
class ClientInterface {
public:
virtual int calc()=0;
virtual bool join()=0;
virtual bool set_callback(ftype_callback on_member_join)=0;
};
It is from SDK which I can call the client from dynamic library in c++ codes.
bool cb(ClientInterface* client, const Member* member ,int member_num) {
// do something
}
cli->set_callback(cb);
cli->join();
I want to port it to python bindings use pybind11. How do I set_callback in python?
I have seen the doc and try:
PYBIND11_MODULE(xxx, m) {
m.def("set_callback", [](xxx &self, py::function cb ){
self.set_callback(cb);
});
}
The code just failed to compile.
My question, how do I convert the py::function to ftype_callback or there is other way to make it?
| You need a little C++ to get things going. I'm going to use a simpler structure to make the answer more readable. In your binding code:
#include <pybind11/pybind11.h>
#include <functional>
#include <string>
namespace py = pybind11;
struct Foo
{
int i;
float f;
std::string s;
};
struct Bar
{
std::function<bool(const Foo &foo)> python_handler;
std::function<bool(const Foo *foo)> cxx_handler;
Bar()
{
cxx_handler = [this](const Foo *foo) { return python_handler(*foo); };
}
};
PYBIND11_MODULE(example, m)
{
py::class_<Foo>(m, "Foo") //
.def_readwrite("i", &Foo::i)
.def_readwrite("f", &Foo::f)
.def_readwrite("s", &Foo::i);
py::class_<Bar>(m, "Bar") //
.def_readwrite("handler", &Bar::python_handler);
}
Here, Foo is the object that is passed to the callback, and Bar is the object that needs its callback function set. Since you use pointers, I have wrapped the python_handler function with cxx_handler that is meant to be used in C++, and converted the pointer to reference.
To be complete, I'll give a possible example of usage of the module here:
import module.example as impl
class Bar:
def __init__(self):
self.bar = impl.Bar()
self.bar.handler = self.handler
def handler(self, foo):
print(foo)
return True
I have used this structure successfully in one of my projects. I don't know how you want to proceed, but perhaps if you don't want to change your original structure you can write wrapper classes upon them that use the given structure.
Update:
I thought that you controlled the structure when I wrote the answer above (I'll keep it for anyone who needs it). If you have a single cli instance, you can do something like:
using Handler = std::function<bool(std::string, int, int)>;
Handler handler;
bool cb(ClientInterface *client, const Member *member, int member_num)
{
return handler(std::string(member->x), member->y, member_num);
}
// We have created cli somehow
// cli->set_callback(cb);
// cli->join();
PYBIND11_MODULE(example, m)
{
m.def("set_callback", [](Handler h) { handler = h; });
}
If you have multiple ClientInterface instances, you can map ClientInterface pointers to handlers and call the appropriate handler in the cb function based on given ClientInterface pointer.
Note: I haven't tested the above with a python script but it should work.
Another Update
If you want to handle multiple instances, the code can roughly look like this:
using Handler = std::function<bool(std::string, int, int)>;
std::map<ClientInterface *, handler> map;
bool cb(ClientInterface *client, const Member *member, int member_num)
{
// Check if <client> instance exists in map
return map[client](std::string(member->x), member->y, member_num);
}
PYBIND11_MODULE(example, m)
{
m.def("set_callback", [](int clientid, Handler h)
{
// Somehow map <clientid> to <client> pointer
map[client] = h;
});
}
Note that this isn't a runnable code and you need to complete it.
|
70,604,357 | 70,605,251 | std::map with std::vector as key -- complexity of lookup function | I have a set of N customers, indexed 0,...,N-1. Periodically, for some subset S of customers, I need to evaluate a function f(S). Computing f(S) is of linear complexity in |S|. The set S of customers is represented as an object of type std::vector<int>. The subsets that come up for evaluation can be of different size each time. [Since the order of customers in S does not matter, the set can as well be represented as an object of type std::set<int> or std::unordered_set<int>.]
In the underlying application, I may have the same subset S of customers come up multiple times for evaluation of f(S). Instead of incurring the needless linear complexity each time, I am looking to see if it would benefit from some sort of less computational burdensome lookup.
I am considering having a map of key-value pairs where the key is directly the vector of customers, std::vector<int> S and the value mapped to this key is f(S). That way, I am hoping that I can first check to see if a key already exists in the map, and if it does, I can look it up without having to compute f(.) again.
Having an std::map with std::vector as keys is well-defined. See, for e.g., here.
CPPReference indicates that map lookup time is logarithmic. But I suppose this is logarithmic in the number of keys where each key if of a constant length -- such as an int or a double, etc. How is the complexity affected where the key itself need not be of constant length and can be of arbitrary length upto size N?
Since the keys can themselves be of different sizes (subset of customers that come up for evaluation could be different each time), does this introduce any additional complexity in computing a hash function or the compare operation for the std::map? Is there any benefit to maintain the key as a binary array a fixed length N? This binary array is such that B_S[i]=1 if the ith customer is in set S, and it is 0 otherwise. Does this make the lookup any easier?
I am aware that ultimately the design choice between reevaluating f(S) each time versus using std::map would have to be done based on actual profiling of my application. However, before implementing both ideas (the std::map route is more difficult to code in my underlying application), I would like to know if there are any known pre-existing best-practices / benchmarks.
| Complexity of lookup in a map is O(log N) That is, roughly log N comparisons are needed when there are N elements in the map. The cost of the comparison itself adds to that linearly. For example when you compare M vectors with K elements, then there are roughly log N comparisons, each comparing M*K vector elements, ie in total O(M*K*log N).
However, asymptotic complexity is only that: Asymptotic complexity. When there are only a small number of elements in the map then lower order factors might outweigh the log N that only dominates for large N. Consequently, the actual runtime depends on your specific application and you need to measure to be sure.
Moreover, you shouldn't use vectors as keys in the first place. Its a waste of memory. Subsets of S can be enumerated with a n-bit integer when S has n elements (simply set the i-th bit when i-th element of S is in the subset). Comparing a single integer (or bitset) is surely more efficient than comparing vectors of integers.
|
70,604,358 | 70,631,970 | Does pybind11 default arugments expression been called every time when the python API been invoked? | I'm trying to add an expression as default arguments to my python function API, which is implemented by pybind11.
For example, here's the C++ function:
void my_print(std::chrono::system_clock::time_point tp = std::chrono::system_clock::now()) {
std::cout << tp << std::endl;
}
PYBIND11_MODULE(my_module, m) {
m.doc() = "my python module implement in pybind11";
m.def("my_print", &my_print, py::arg("tp") = std::chrono::system_clock::now());
}
Now I'm wonderring that, the expression = std::chrono::system_clock::now(), I want it been called everytime I invoke this my_print API in python script.
But I'm not sure, is this expression been called everytime this API been invoked in python ? Or this expression is only been called once when this python module been load in python ?
| This is evaluated once, during the (runtime) initialization of the pybind bindings.
The way this feature is implemented is by overloading operator= of py::arg to return a different type, py::arg_v (short for argument with default value).
|
70,604,628 | 70,604,691 | Recursive class template and implicit instantiation error in C++ | The following minimal reproducible example contains a template struct B with default argument type containing a lambda A<[]{ return 1; }>, B is recursively inherited from B<>. And there is a specialization of B for any A<z>.
template<auto>
struct A{};
template<class = A<[]{ return 1; }>>
struct B : B<> {};
template<auto z>
struct B<A<z>> {};
B<int> x;
GCC is ok with the example, by Clang complains:
error: implicit instantiation of template 'B<A<{}>>' within its own definition
Demo: https://gcc.godbolt.org/z/xzjzo7dE9
Which compiler is right here?
P.S. If one modifies the definition of B this way:
template<class>
struct B : B<A<[]{ return 1; }>> {};
then all compilers become totally happy, demo: https://gcc.godbolt.org/z/roqnc39eq
|
Which compiler is right here?
Both are, since B is ill-formed; NDR. As always, [temp.res]/8 applies:
The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic required, if:
(8.4) - a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or
The template is B, and "its" definition here speaks of the primary. If we were to instantiate B<> immediately after, we'll get an unconditionally ill-formed class definition. Hence, GCC and Clang can do whatever.
Btw, this entire lambda as a template argument business is a red herring. We can go for plain, old int as parameter and get similar divergence as well.
template<int>
struct A{};
template<class = A<0>>
struct B : B<> {};
template<int z>
struct B<A<z>> {};
B<int> x;
int main() {}
Clang still complains, but now so does GCC.
|
70,604,687 | 70,604,756 | why would returned value of "make_share<Type>" in function list be rvalue? | here is my code:
#include <bits/stdc++.h>
class Quote {
public:
Quote() = default;
Quote(const string& book, double sales_price)
: bookNo(book), price(sales_price) {}
string isbn() const { return bookNo; }
private:
string bookNo;
double price = 0.0;
};
class Basket {
public:
void add_item(shared_ptr<Quote>& sale) { items.insert(sale); }
double total_receipt(ostream& s) const;
private:
static bool compare(const shared_ptr<Quote>& lhs,
const shared_ptr<Quote>& rhs) {
return lhs->isbn() < rhs->isbn();
}
multiset<shared_ptr<Quote>, decltype(compare)*> items{compare};
};
int main() {
Basket item;
item.add_item(make_shared<Quote>("aaaa", 1)); //here is the problem is
return 0;
}
when i complier it.I got wrong message cannot bind non-const lvalue reference of type ‘std::shared_ptr&’ to an rvalue of type ‘std::shared_ptr’
Then i change code to this:
#include <bits/stdc++.h>
class Quote {
public:
Quote() = default;
Quote(const string& book, double sales_price)
: bookNo(book), price(sales_price) {}
string isbn() const { return bookNo; }
private:
string bookNo;
double price = 0.0;
};
class Basket {
public:
void add_item(const shared_ptr<Quote>& sale) { items.insert(sale); } //after debug i add "const" at the front of ''shared_ptr<Quote>& sale'',it works
double total_receipt(ostream& s) const;
private:
static bool compare(const shared_ptr<Quote>& lhs,
const shared_ptr<Quote>& rhs) {
return lhs->isbn() < rhs->isbn();
}
multiset<shared_ptr<Quote>, decltype(compare)*> items{compare};
};
int main() {
Basket item;
item.add_item(make_shared<Quote>("aaaa", 1)); //here is the problem is
return 0;
}
It works.So that means make_shared<Quote>("aaaa",1)returns a rvalue type?
But i change function main() to this:
int main() {
Basket item;
shared_ptr<Quote> ptr = make_shared<Quote>("aaaa", 1);
item.add_item(ptr);
cout << endl;
}
and delete const at the front of shared_ptr<Quote>& salein function list void add_item( const shared_ptr<Quote>& sale) { items.insert(sale); }.It also woks.So that means make_shared<Quote>("aaaa",1) returns a lvalue type.It conflicts to mentioned before.
So can i think that when make_shared<Quote>("aaaa",1)in a function list ,it returns rvalue?
I also wanna know why would be this.Thanks!
| std::make_shared returns a std::shared_ptr<...>, which is not a reference type, therefore the expression std::make_shared<...>(...) is a prvalue (a subcategory of rvalues). This is true for all functions returning objects by-value, rather than by-reference.
Non-const lvalue references cannot bind to rvalues, as the message is telling you, while const lvalue references and rvalue references can.
The line
shared_ptr<Quote> ptr = make_shared<Quote>("aaaa", 1);
works, because there is a constructor of shared_ptr<Quote> which accepts rvalues, namely the move constructor. Since C++17 it is even simpler, since it is guaranteed that initializing a variable with a prvalue of the same type doesn't move or copy. Instead it will directly construct the return value of std::make_shared in ptr.
In the line
item.add_item(ptr);
the expression ptr is a lvalue. The names of variables used as expressions are always lvalues. And because the type of ptr is not const-qualified, a non-const lvalue reference can bind to it.
returns a rvalue type
rvalue and lvalue are value categories. These are not properties of types, they are properties of expressions. I think you might be confusing them with rvalue references and lvalue references, which are qualities of types.
|
70,605,134 | 70,606,154 | Implement a template of a Queue, using 2 Classes | I have a problem. I have implemented a Queue, while using a Class "Queue" and a Class "Element".
the problem i have now is, that I can't work out how to create the template for class Element.
If I don't use the template and just use int instead of T. Everything works fine. I already looked for many examples on the Internet. But nobody uses two classes, which is probably more efficient. I think my problem is that i don't know how to use the pointer in templates.
PS: The template in Queue.h and.cpp works i think, but if i start trying to create a template for Element it doesn't work.
My Queue.h file
#ifndef ELEMENT_H
#define ELEMENT_H
#include "Element.h"
template <class T>
class Queue{
public:
explicit Queue(int max_queue);
~Queue() = default;
void enqueue(T inhalt);
Element* dequeue();
Element* show();
bool isEmpty();
private:
Element<T>* front{};
Element<T>* back{};
int max;
int anzahl = 0;
};
#endif
My Queue.cpp file
#include "Queue.h"
#include <iostream>
#include <string>
template <class T>
Queue<T>::Queue(int max_queue){
max = max_queue;
}
template <class T>
void Queue<T>::enqueue(T inhalt){
Element* e = new Element(inhalt);
if(max > anzahl){
if(isEmpty()){
front = back = e;
}else{
back->setNext(e);
back = e;
}
} anzahl++;
}
template <class T>
Element* Queue<T>::dequeue(){
Element* e = front;
front = front->getNext();
e->setNext(nullptr);
return e;
}
template <class T>
bool Queue<T>::isEmpty()
{
return anzahl == 0;
}
template <class T>
Element* Queue<T>::show()
{
return front;
}
My Element.h file
#ifndef QUEUE_H
#define QUEUE_H
class Element{
public:
explicit Element(int);
~Element() = default;
int getInhalt()const;
void setInhalt(int);
Element*getNext()const;
void setNext(Element*);
protected:
int inhalt;
Element* next;
};
#endif
My Element.cpp file
#include <string>
#include "Element.h"
Element::Element( int inhalt_element )
{
inhalt = inhalt_element;
next = nullptr;
}
int Element::getInhalt() const {
return inhalt;
}
void Element::setInhalt(int inhalt) {
Element::inhalt = inhalt;
}
Element* Element::getNext() const {
return next;
}
void Element::setNext(Element *next) {
Element::next = next;
}
The warning I'm getting is main.cpp:(.text+0x1a): undefined reference to `Queue::Queue(int)'
And If I try to use a template for the element class. There are hundreds of lines in the warnings, so I know I'm thinking completely wrong.
I am still pretty novice if it is about programming so any help or any idea would be really appreciated.
Thank you
| The implementation of template classes must be done in the .h
The following code compiles.
#include <iostream>
#include <string>
template <class T>
class Element{
public:
Element( T inhalt_element ){
inhalt = inhalt_element;
next = nullptr;
}
T getInhalt() const {
return inhalt;
}
void setInhalt(T inhalt) {
this->inhalt = inhalt;
}
Element<T>* getNext() const {
return next;
}
void setNext(Element<T> *next) {
this->next = next;
}
protected:
T inhalt;
Element<T>* next;
};
template <class T>
class Queue{
public:
Queue(int max_queue){
max = max_queue;
}
void enqueue(T inhalt){
Element<T>* e = new Element<T>(inhalt);
if(max > anzahl){
if(isEmpty()){
front = back = e;
}else{
back->setNext(e);
back = e;
}
} anzahl++;
}
Element<T>* dequeue(){
Element<T>* e = front;
front = front->getNext();
e->setNext(nullptr);
return e;
}
bool isEmpty(){
return anzahl == 0;
}
Element<T>* show(){
return front;
}
private:
Element<T>* front{};
Element<T>* back{};
int max;
int anzahl = 0;
};
int main() {
std::cout << "Hello World!";
Queue<int> queue(10);
return 0;
}
|
70,605,511 | 70,606,034 | How to use 'mutable' correctly so the set iterator won't be const? | I'm trying to remove the employee in my code and change his salary back to 0, but all I get in the function is his id. I used the built in iterator for the set, but found out that it is const. How can I use mutable, or some other way to change his salary to 0?
I have an employee and a manager- the manager can hire or fire the employee, which will change his salary (obviously).
This is my code:
class Manager : public Citizen {
protected:
int salary;
std::set<Employee> employees;
void removeEmployee(const int id) {
mutable std::set<Employee>::iterator employee;
for (employee = this->employees.begin(); employee != this->employees.end(); employee++) {
if (employee->getId() == id) {
employee->setSalary(0);
this->employees.erase(employee);
return;
}
}
throw EmployeeNotHired();
}
And the error I'm getting-
C:\Users\User\CLionProjects\hw2Cpp\Manager.h:53:50: error: non-member 'employee' cannot be declared 'mutable'
mutable std::set<Employee>::iterator employee;
^~~~~~~~
C:\Users\User\CLionProjects\hw2Cpp\Manager.h:57:42: error: passing 'const mtm::Employee' as 'this' argument discards qualifiers [-fpermissive]
employee->setSalary(0);
What should I do?
**** edit****
I tried changing it to:
class Employee : public Citizen {
protected:
mutable int salary;
mutable int score;
std::set<Skill> skills;
But I am still unable to change the salary to 0.
error: passing 'const mtm::Employee' as 'this' argument discards qualifiers [-fpermissive]
employee->setSalary(0);
| The design of std::set ensures that elements of the set "cannot be modified" i.e. they can only be accessed via const references. This is for a good reason: std::set relies on the order of its elements remaining the same thoughout the lifetime to maintain its internal search tree datastructure.
Ways to deal with this are:
declaring setSalary as a const member function. (Not a good idea since setting the salary probably does modify the object in a way that wouldn't be expected of a const function.)
Extract the employee (C++17)
//employee->setSalary(0);
//this->employees.erase(employee);
auto node = employees.extract(employee);
node.value().setSalary(0);
Choose a different data structure such as a std::unordered_map<int, Employee> mapping from id to Employee or std::vector<Employee>.
However unless the setSalary function has effects other than modifying the Employee object, just remove the object from the set; The object is deleted in the process anyways...
|
70,605,685 | 70,605,796 | How is this 'for' loop relevant in the keylogger? | I'm reading a book on writing a keylogger for fun; I came across this 'for' loop and I'm confused as to how it is relevant.
#include <iostream>
#include <fstream>
#include <windows.h>
#include <Winuser.h>
using namespace std;
void log();
int main()
{
log();
return 0;
}
void log()
{
char c;
for(;;)
{
for(c=8;c<=222;c++) // <<=== THIS LOOP HERE
{
if(GetAsyncKeyState(c) == -32767)
{
ofstream write("C:\\Users\\IEUser\\Desktop\\text.txt",ios::app);
write<<c;
}
}
}
}
From my understanding, it means that C++ will set c=8, and go through the loop, incrementing until it hits 222, then stops (But it'll continue again anyway because of the parent loop). The book mentions that the numbers 8 and 222 indicate ASCII code.
But I don't see how it links to getting my input! Is the input not being derived from GetAsyncKeyState already?
| for(;;)
The infinite loop keeps running (listening)
for(c=8;c<=222;c++)
Run values from 8 to 222 included [8,222]
GetAsyncKeyState(c) == -32767)
Determines whether a key is up or down at the time the function is
called
So now you are testing against that ASCI represented by c. Now what does the magic number -32767 means?
If we write -32767 in binary it resolves to 1000 0000 0000 0001. As you can see both the most significant bit and the least significant bit is set so from the description follows that the key is down and that it has been pressed down since the last time you called GetAsyncKeyState.
|
70,605,861 | 70,606,007 | Cannot find std::experimental::when_any | I am trying to use std::experimental::when_any and std::experimental::when_all which according to Anthony Williams are in <experimental/future> header.
I am using Visual Studio 2022 (same is for 2019) and cannot find this header/functions neither under C++17 standard nor under C++20 standard configurations.
Can someone please help to reach this functions in VS?
| The experimental headers are not part of the standard. An implementation may provide them, but is not required to.
They are defined for features that the C++ committee is working on incorporating into a future standard.
Neither Visual Studio 2019 nor 2022 provide <experimental/future>
|
70,606,942 | 70,608,140 | Choosing from multiple DLL versions | Today I build my application and packaged the installer with QtIF. It worked nice on my computer but complained about missing msvcp140_1.dll in another computer.
Then I run find . -iname "msvcp140_1.dll" and found more than five different ones on my computer, I checked the md5sum.
Then I spend the time to try all of them on the other computer and all seem to work fine. No more complains about missing DLL.
How should I choose between the DLLs? Just pick any seems too easy.
Is there someway to inspect the DLLs, to check for a version?
I believe that DLL was a dependency from another binary included in my application, was not that the QtIF failed to include it.
| Call the MS Redist Installer from your Installer. This can be done quietly, so that the end user does not notice it.
Find the vcredist_x64.exe file (or vcredist_x32 for 32 Bit applications), add it to your installer,
let it extract to the "TEMP" folder
and then call vcredist_x64.exe /quiet at the end of your install.
This has several advantages:
You will definitely copy all required files to the users computer.
Should new versions of the runtime library be released by Microsoft and should they already be on your users computer, your code will use the newer versions, which may include bugfixes.
Windows Update may also update the libraries.
That said, it is possible to copy the DLLs themselves, but you should make sure
a) you choose the right ones
b) they come from a trustworthy place, i.e. your VS installation folder
c) reside in the same directory as the executable - otherwise you will run into trouble with manifests.
The reason you might want to include the DLLs directly is if you want to reduce the overall size of your installer.
We did this a couple of years with our products, but finally gave in and simply used the vcredist_x64.exe, even if that increased the installer binary another couple of MB in size. But in the long run that's the easiest way.
I think (not sure), msvcp140_1.dll is an additional DLL for the VS 2019 runtime. VS 2017 runtime does not need this, but the new one does.
|
70,607,712 | 70,607,881 | Attempting to reference a deleted function (copy c'tor) | I got this example of spinlock from Anthony Williams, and its something wrong with it (or I had a long day).
#include <atomic>
class spinlock
{
std::atomic_flag flag;
public:
spinlock() : flag(ATOMIC_FLAG_INIT) {}
void lock() {
while (flag.test_and_set(std::memory_order_acquire));
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
spinlock sl;
void f()
{
std::lock_guard lc(sl);
}
int main()
{
f();
}
So this is enough for std::lock_guard to acquire it, but I have a compilation error.
error C2280: 'std::atomic_flag::atomic_flag(const std::atomic_flag &)': attempting to reference a deleted function
To be honest I dont see how spinlock() : flag(ATOMIC_FLAG_INIT) {} is calling a copy constructor.
I use VS2022 with C++20 standard and ATOMIC_FLAG_INIT is defined as following:
#define ATOMIC_FLAG_INIT \
{}
Is this book example broken, or am I donning something wrong?
| ATOMIC_FLAG_INIT can only be used as follows:
std::atomic_flag v = ATOMIC_FLAG_INIT;
It is unspecified if
flag(ATOMIC_FLAG_INIT)
will work. If visual studio defines ATOMIC_FLAG_INIT as {} then your code is presumably ending up creating an std::atomic_flag with {} then calling the deleted copy constructor of flag.
If you're using c++20 you can simply remove the flag initialiser as std::atomic_flag's default constructor now initialises to false.
Without c++20 I think the only way to do this according to the standard is to use an inline initialiser:
class spinlock
{
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(std::memory_order_acquire));
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
|
70,608,353 | 70,608,420 | How to get rid of warnings that precompiler definitions are not definied | There is a file that I downloaded from the Unity web-site
#pragma once
// Standard base includes, defines that indicate our current platform, etc.
#include <stddef.h>
// Which platform we are on?
// UNITY_WIN - Windows (regular win32)
// UNITY_OSX - Mac OS X
// UNITY_LINUX - Linux
// UNITY_IOS - iOS
// UNITY_TVOS - tvOS
// UNITY_ANDROID - Android
// UNITY_METRO - WSA or UWP
// UNITY_WEBGL - WebGL
#if _MSC_VER
#define UNITY_WIN 1
#elif defined(__APPLE__)
#if TARGET_OS_TV //'TARGET_OS_TV' is not defined, evaluates to 0
#define UNITY_TVOS 1
#elif TARGET_OS_IOS //'TARGET_OS_IOS' is not defined, evaluates to 0
#define UNITY_IOS 1
#else
#define UNITY_OSX 1 //'UNITY_OSX' macro redefined
#endif
#elif defined(__ANDROID__)
#define UNITY_ANDROID 1
#elif defined(UNITY_METRO) || defined(UNITY_LINUX) || defined(UNITY_WEBGL)
// these are defined externally
#elif defined(__EMSCRIPTEN__)
// this is already defined in Unity 5.6
#define UNITY_WEBGL 1
#else
#error "Unknown platform!"
#endif
...
The problem is that when I try to include the file in my XCode project I got a warning (put them in comments)
...
#if TARGET_OS_TV //'TARGET_OS_TV' is not defined, evaluates to 0
#define UNITY_TVOS 1
#elif TARGET_OS_IOS //'TARGET_OS_IOS' is not defined, evaluates to 0
#define UNITY_IOS 1
#else
#define UNITY_OSX 1 //'UNITY_OSX' macro redefined
#endif
...
I tried to use #pragma warning(suppress: 4101) and a few similar approaches, but it doesn't help
UPD
...
#ifdef TARGET_OS_TV
#define UNITY_TVOS 1
#elif TARGET_OS_IOS //'TARGET_OS_IOS' is not defined, evaluates to 0
#define UNITY_IOS 1
#else
#define UNITY_OSX 1
#endif
...
Using ifdef helps to get rid of the first warning, but the second one is still in place
UPD2
...
#ifdef TARGET_OS_TV
#define UNITY_TVOS 1
#elifdef TARGET_OS_IOS //Invalid preprocessing directive
#define UNITY_IOS 1
#else
#define UNITY_OSX 1
#endif
...
| You should not use #if to test an undefined macro. The warning implies that you should use #ifdef instead.
You may not define a previously defined macro. You could first undefined the old definition, but that's rarely a good idea.
Using ifdef helps to get rid of the first warning, but the second one is still in place
In c++23 you will be able to use #elifdef instead.
Otherwise, you can use #elif defined(the_macro).
|
70,608,372 | 70,608,566 | tuple of vectors from std::tuple | I'm trying to create a tuple of vectors from a std::tuple (Reason: https://en.wikipedia.org/wiki/AoS_and_SoA) and came up with the following piece of code.
Can anyone think of a more elegant, less verbose solution? PS: I'm stuck with a C++14 compiler...
template<std::size_t N, class T, template<class> class Allocator>
struct tuple_of_vectors {};
template<class T, template<class> class Allocator>
struct tuple_of_vectors<1, T, Allocator>
{
using type = std::tuple
<
std::vector
<
typename std::tuple_element<0, T>::type
, Allocator<typename std::tuple_element<0, T>::type>
>
>;
};
template<class T, template<class> class Allocator>
struct tuple_of_vectors<2, T, Allocator>
{
using type = std::tuple
<
std::vector
<
typename std::tuple_element<0, T>::type
, Allocator<typename std::tuple_element<0, T>::type>
>,
std::vector
<
typename std::tuple_element<1, T>::type
, Allocator<typename std::tuple_element<1, T>::type>
>
>;
};
// and so on...
template<class T, template<class> class Allocator>
class series
{
public:
using tov_type = typename tuple_of_vectors
<std::tuple_size<T>{}, T, Allocator>::type;
tov_type tov_;
};
| You can use C++14 std::index_sequence to extract the elements of the tuple.
#include <tuple>
#include <vector>
#include <utility>
template<class IndexSeq, class Tuple, template<class> class Alloc>
struct tuple_of_vectors;
template<class Tuple, template<class> class Alloc, std::size_t... Is>
struct tuple_of_vectors<std::index_sequence<Is...>, Tuple, Alloc> {
using type = std::tuple<
std::vector<std::tuple_element_t<Is, Tuple>,
Alloc<std::tuple_element_t<Is, Tuple>>>...
>;
};
template<class Tuple, template<class> class Alloc>
class series {
public:
using tov_type = typename tuple_of_vectors<
std::make_index_sequence<std::tuple_size<Tuple>::value>, Tuple, Alloc>::type;
tov_type tov_;
};
Demo.
|
70,608,387 | 70,611,318 | SWIG typemap 2d array to Python list | This is next level of this question. I need to cast 2d C char array to Python list.
Python side
device_info = getInfoFromCpp()
print(device_info.angles)
for angle in device_info.angles:
print("Angel: " + angle)
Error
<Swig Object of type 'char (*)[MaxStringLength]' at 0x000000D8B2710330>
Execution error: 'SwigPyObject' object is not iterable
С++ header
struct DeviceInformation {
static const int MaxStringLength= 200;
static const int MaxNumberOfAngles= 5;
char serialNumber[MaxStringLength];
char angles[MaxNumberOfAngles][MaxStringLength];
};
Based on @MarkTolonen 's answer I try the following typemaps but no result.
// %typemap(out) char*[ANY] %{
// %typemap(out) char (*)[ANY] %{
%typemap(out) char [ANY][ANY] %{
PyObject *pyArray = PyList_New(5);
for (uint8_t i = 0; i < 5; ++i) {
PyObject *pyString = PyString_FromString(reinterpret_cast<char*>($1[i]));
PyList_SetItem(pyArray, i, pyString);
}
$result = pyArray;
%}
| Your code as is worked for me, but here are some corrections as mentioned in the question comments and a working example:
test.i
%module test
// This works for any size of 2d char array assuming it contains
// UTF-8-encoded, null-terminated strings (no error checking!)
%typemap(out) char [ANY][ANY] %{
$result = PyList_New($1_dim0);
for (Py_ssize_t i = 0; i < $1_dim0; ++i) {
PyList_SET_ITEM($result, i, PyUnicode_FromString($1[i]));
}
%}
%inline %{
struct DeviceInformation {
static const int MaxStringLength= 200;
static const int MaxNumberOfAngles= 5;
char serialNumber[MaxStringLength];
char angles[MaxNumberOfAngles][MaxStringLength];
};
// test function
DeviceInformation getInfoFromCpp() {
return {"serialnumber",{"angle1","angle2","angle3","angle4","angle5"}};
}
%}
Demo:
>>> import test
>>> x=test.getInfoFromCpp()
>>> x.serialNumber
'serialnumber'
>>> x.angles
['angle1', 'angle2', 'angle3', 'angle4', 'angle5']
|
70,608,425 | 70,722,807 | try except and inheritance | Why the result is "B", I thought that it should hit first inherited class ("A")? When I ran it with class B that do not inherit anything from class A it hits first catch block, but I don't know reason for behavior like this in code below:
#include <iostream>
#include <exception>
using namespace std;
class A {};
class B : public A{};
class C : public A, public B {};
int main() {
try {
throw C();
}
catch (A a) {
cout << "A" << endl;
}
catch (B b) {
cout << "B" << endl;
}
catch (C c) {
cout << "C" << endl;
}
}
| Your classes are some variant of the deadly diamond of death case of multiple inheritance: the base class A is twice a base class of C: once directly, and once indirectly via B:
A
|\
| \
| B
| /
|/
C
The consequence of this kind of inheritance graph is that your C object has two different A sub-objects. I name them in the graph for convenience:
a1:A a2:A
| |
| |
| b:B
| /
| /
c:C
As you see, if you mention the A sub-object, there is an ambiguity: is it a1 or a2, whereas for B there is no ambiguity. And this impacts the matching the exception handling. Because the standard's rules are as follows:
[except.handle]/3: A handler is a match for an exception object of type E if
— The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
— the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
— ...
When you throw C, first the catch (A a) is tested: A is not the same type than C. And A is non an unambiguous public base class either. Then the next catch (B b) is tested: B is not the same type than C. But it's an unambiguous public base class of it. Match! And therefore your result.
Solution 1:
Making A a virtual base of both B and C as suggested in the other answer, ensures that there is only one unique and unambiguous A sub-object in C. This is why it works.
Solution 2
Virtual inheritance is not a silver bullet. As soon as you have non-default constructors, you must explicit the virtual constructor systematically. Moreover, you must use the virtual inheritance wherever A is a subclass. Last but not least, virtual inheritance is sometimes just not suitable for the needs (for example if two independent strands are needed).
In this last situation, you could also disambiguate by introducing an intermediary class:
class AA : public A {};
class C : public AA, public B {};
and then catch (AA& a) instead of catching A. This is stupid simple, but it removes the ambiguity, whereas there are still two different A sub-objects (again: only if you need them). (online demo)
Recommendation: To get a full understanding of the situation, I recommend that you try to update your example and add in each class some members that you'd initialize with a non-default constructor. ANd yes, catch the exception by reference.
|
70,608,692 | 70,608,839 | Does program fail because class lack copy ctor or proper assignment operator? | I'm struggling to understand the exact reason the program fails.
Regarding the following program:
#include <iostream>
template < class T, size_t SIZE>
class Stack {
T arr[SIZE] = {};
int pos = 0;
public:
Stack & push(const T & t) {
arr[pos++] = t;
return *this;
}
Stack & push(T && t) {
arr[pos++] = std::move(t);
return *this;
}
T pop() {
return std::move(arr[--pos]);
}
};
class Foo {
std::string s;
public:
Foo(const char* s = "@") : s(s) {}
Foo(Foo && foo) : s(std::move(foo.s)) {}
Foo & operator=(Foo && foo) {
s = std::move(foo.s);
return *this;
}
void print() const { std::cout << s << std::endl; }
};
int main() {
Stack<std::string, 5> s1;
s1.push("hi").push(std::string{ "bye" });
std::cout << s1.pop() << std::endl;
Stack<Foo, 5> s3;
Foo f2;
s3.push(f2);
}
The program fails at s3.push(f2); is it because Foo doesn't have a copy ctor or is it because its assignment operator function only handles Foo&& types?
I'm suspecting it's the assignment operator function but I'm not sure it's not because of copy ctor as well.
| Because you provided a custom move cosntructor and assignment operator, the compiler no longer generates default copy constructor and assignment operator.
You either need to write those too, or, even better, remove the custom move operations.
The compiler will then generate all 4 for you, and they might be better than your manually written ones (e.g. one problem is that you forgot noexcept on move operations, so standard containers will prefer making copies to moves in some scenarios).
|
70,608,713 | 70,609,217 | Problem when trying to find memory leaks by using crtdbg.h | I am first time trying to use CRT library to detect memory leaks. I have defined #define _CRTDBG_MAP_ALLOC at the begginging of the program. My program is made of classes one struct and main function. In main function i have _CrtDumpMemoryLeaks(); at the end. I tried to follow these Instructions.
And I wanted to get lines where data are allocated that cause memory leaks but I get output like this:
Detected memory leaks!
Dumping objects ->
{326} normal block at 0x00E02C40, 8 bytes long.
Data: <<# > 3C 23 E0 00 00 00 00 00
{322} normal block at 0x00E02CB0, 8 bytes long.
Data: <L > 4C 1F E0 00 00 00 00 00
{318} normal block at 0x00E02AF0, 8 bytes long.
Data: < " > CC 22 E0 00 00 00 00 00
{312} normal block at 0x00E02A10, 8 bytes long.
Data: < $ > FC 24 E0 00 00 00 00 00
...
I don't exit anywhere in my program and it allways finishes in main. What can be the cause that I don't get allocation number ? I can add my code if needed.
Thanks for any help.
| Ok, It was impossible to answer my question with the information I gave(I am sorry). The problem was that I had a Base class and derived classes. And in the base class I did not have a virtual destructor. Adding virtual destructor fixed my problem and removed all memory leaks.
|
70,608,834 | 70,609,259 | Returning a matrix array in C++ function | I am trying to write an OLS regression in C++. I want the user to specify how many observations and variables goes into the X (independent variable matrix). I want to write this as a function outside the int main() function. But everytime I return the array, I get a type error. How do I specify that I want function input_x to return a matrix/array?
/******************************************************************************
Online C++ Compiler.
*******************************************************************************/
#include <iostream>
using namespace std;
int input_x(int num_rows, int num_cols){
int mat[num_rows][num_cols];
int user_input;
for (int i=0; i<num_rows; i++){
for (int j=0; j<num_cols; j++){
cout<<"Enter the value X:";
cin>>user_input;
mat[i][j]=user_input;
}
}
return mat;
}
int main()
{
int mat[1000][1000];
int input;
int rows;
int cols;
cout<<"How many row?";
cin>> rows;
cout<<"How many columns?";
cin>> cols;
//Enter the X data
input_x(rows,cols);
return 0;
}
| Mistake 1
In C++ the size of an array must be a compile time constant. So take for example,
int n = 10;
int arr[n]; //INCORRECT because n is not a compile time constant
The correct way to write the above would be
const int n = 10;
int arr[n]; //CORRECT
Similarly in your code:
int mat[num_rows][num_cols];//INCORRECT because num_rows and num_cols are not constant expressions
Mistake 2
The return type of your function input_x is int.
But the type of mat inside the function input_x is int [num_rows][num_cols] which decays to int (*)[num_cols] due to type decay.
So essentially the return type of your function(int) and what you're actually returning(int (*)[num_cols]) doesn't match and hence you get the following error:
error: invalid conversion from ‘int (*)[num_cols]’ to ‘int’
Solution
To solve these problems you should use std::vector instead of built in array as shown below:
#include <iostream>
#include <vector>
//this function takes vector by reference and returns nothing
void input_x(std::vector<std::vector<int>> &vec){
for(auto &rows: vec)
{
for(auto &cols: rows)
{
std::cout << "Enter element: "<<std::endl;
std::cin >> cols;
}
}
//NO NEED TO RETURN ANYTHING SINCE THE VECTOR IS PASSED BY REFERENCE SO THE CHANGE IS ALREADY REFLECTED ON THAT PASSED VECTOR
}
int main()
{
int rows;
int cols;
std::cout<<"How many row?"<<std::endl;
std::cin>> rows;
std::cout<<"How many columns?"<<std::endl;
std::cin>> cols;
//create 2D vector
std::vector<std::vector<int>> myVec(rows, std::vector<int>(cols));
//call the function and pass the vector as argument
input_x(myVec);
return 0;
}
|
70,609,271 | 70,609,356 | c++ call an overriden virtual function with a derived argument | How can I call an overridden virtual function with a derived argument?
The argument I'm calling it with is of a derived class of the argument it was defined and overriden with.
//Args
struct ArgBase{
int val;
};
struct ArgDerived: ArgBase{
int derivedVal;
};
/////
struct Base {
int name;
virtual int doSomething(ArgBase a) = 0;
};
struct Derived: public Base {
int doSomething(ArgBase a){ //I want to overide Base's virtual function, so I need to pass in an ArgBase here (and not an ArgDerived)
return a.derviedVal; //<------------- how can I get this to work?
// option 1: return static_cast<ArgDerived>(a).derviedVal; does not work
// option 2: can I may be do something like "if(a is ArgDerived){....}"?
}
};
int main ()
{
Derived d;//object of derived class
ArgDerived ad; //object of derived argument class
ad.val = 25;
ad.derivedVal = 75;
std::cout << d.doSomething(ad) << std::endl; //<---------- call with derived argument ad
return 0;
}
| You should accept the argument by reference or pointer for it to behave polymorphically
virtual int doSomething(const ArgBase& a) = 0;
then you can cast in your overriden function
return static_cast<const ArgDerived&>(a).derviedVal;
of course static_cast assumes that this cast is valid at runtime. If you are unsure of the derived type being passed then you'd need to use something like dynamic_cast which will throw a std::bad_cast if the reference is not of that type. Or use some other pattern, but the point being you must only static_cast if that type is appropriate at runtime.
|
70,609,349 | 70,609,540 | Is assign with braces the same as call the constructor? | I know that for scalar types you can assign values with braces like int a { 0 };.
This helps with cast, type conversion ecc.
But what for udt? Is
shared_ptr<int> myIntSmartPtr { my_alloc(42), my_free };
the same as
shared_ptr<int> myIntSmartPtr = shared_ptr<int>(my_alloc(42), my_free);
The braces should call the constructor, right?
Is it like an initializer list?
I know what an std::initializer_list is, but it must be the same type T, while in { my_alloc(42), my_free } the types diverge.
| This is direct list initialization.
shared_ptr<int> myIntSmartPtr { my_alloc(42), my_free };
This is an example of the first syntax:
T object { arg1, arg2, ... }; (1)
The exact effect it has is therefore
List initialization is performed in the following situations:
direct-list-initialization (both explicit and non-explicit constructors are considered)
initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists)
And for more detail about what that actually means:
The effects of list-initialization of an object of type T are:
... [A bunch of cases that don't apply]
Otherwise, the constructors of T are considered, in two phases:
All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list
If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).
std::shared_ptr does not have a constructor that takes an std::initializer_list, so the second bullet point applies and it's constructed from the arguments therein.
|
70,609,855 | 70,609,963 | Data member pointers as associative container keys | I am trying to create an std::set of pointers to data members. However, I can't find a method to sort or hash such pointers.
They can't be compared with operator<, they don't seem to be supported by std::less and there is no standard integer type that is guaranteed to hold their representation (they might not fit in std::uintptr_t).
This is what I tried first (https://godbolt.org/z/K8ajn3rM8) :
#include <set>
struct foo
{
int x;
int y;
};
using t_member_ptr = int (foo::*);
const std::set<t_member_ptr> members = {
&foo::x,
&foo::y
};
It produces the error error: invalid operands of types 'int foo::* const' and 'int foo::* const' to binary 'operator<'. The full error message also implies this occurs during instantiation of std::less.
I found a similar question (Set of pointer to member) but it dates back to C++14 and the answers boil down to "put your pointers in a vector and perform a linear search instead".
Has there been any changes with C++17 or C++20 that make it possible to use pointers to data members as keys for standard associative containers?
| Compare them bytewise, e.g. using this comparator:
#include <cstring>
#include <type_traits>
struct BitLess
{
template <typename T>
requires std::has_unique_object_representations_v<T>
constexpr bool operator()(const T &a, const T &b) const
{
return std::memcmp(reinterpret_cast<const char *>(&a), reinterpret_cast<const char *>(&b), sizeof(T)) < 0;
}
};
Checking std::has_unique_object_representations_v<T> ensures that there's no padding inside. It tried it on GCC, Clang, and MSVC, and it returned true for member pointers on all three.
|
70,610,264 | 70,610,839 | Where can I find the library that provides String.substring() method? | I'm trying to compile an Arduino project on Linux, abstracting away the hardware parts. Consider the following line:
int keyNumRepeat = userInputPrev.substring(6, 8).toInt();
It looks like Arduino uses some non-standard library, which isn't on my system:
hsldz_totp_lock/hsldz_totp_lock.ino:335:38: error: ‘String’ {aka ‘class std::__cxx11::basic_string<char>’} has no member named ‘substring’; did you mean ‘substr’?
335 | int keyNumRepeat = userInputPrev.substring(6, 8).toInt();
| ^~~~~~~~~
| substr
make: *** [Makefile:54: sim] Error 1
Is it available somewhere so that I could include it in my project while trying to compile? Or is it something that heavily depends on other Arduino implementation details?
| It looks like Arduino has a custom implementation of String.
Since it's open source, here are the header and class files. I only skimmed through them, but they don't appear to be heavily dependent on the rest of the Arduino core API.
That said, you may be better off replacing their implementation with standard c++. Especially if they're just quality-of-life improvements. The equivalent code using string::substr and std::stoi should be:
int keyNumRepeat = std::stoi(userInputPrev.substr(6, 8));
|
70,610,603 | 70,611,128 | How to declare concept function signature with a template type? | Is there a way to have a concept function signature that has a template argument?
Something like this:
template<typename SomeTypeT, typename U>
concept SomeType = requires(SomeTypeT s) {
{ s.SomeFunction<U>() };
};
?
| The shown concept definition works, except that you need to tell the compiler that SomeFunction is a template:
template<typename SomeTypeT, typename U>
concept SomeType = requires(SomeTypeT s) {
{ s.template SomeFunction<U>() };
};
This is always necessary if you want to reference a template member of a dependent name in a template definition, not specific to concepts. When parsing the definition, the compiler doesn't know yet what type s is and so can't know that SomeFunction is supposed to be a template. But it needs to know, since the meaning of the angle brackets and the whole expression can dependent on it.
|
70,611,109 | 70,611,315 | How do std::exception's derivatives pass the string from their constructor to its what() virtual function? | I'd like to reimplement the standard exception hierarchy.
std::exception is defined in the following way, according to the documentation:
class exception {
public:
exception () noexcept;
exception (const exception&) noexcept;
exception& operator= (const exception&) noexcept;
virtual ~exception();
virtual const char* what() const noexcept;
}
Now, for example, std::logic_error is declared like this:
class logic_error : public exception {
public:
explicit logic_error (const string& what_arg);
explicit logic_error (const char* what_arg);
};
My question is, how does such an instantiation: std::logic_error("Error!") work under the hood?
The "Error!" string gets passed to logic_error (const char* what_arg), and somehow passes its value to the what() overload in the implementation, without calling it.
One way of doing this is probably copying the string and storing it somewhere (as a private member, in the base class), then throwing it in what().
I just wanted to clarify whether this is what I should do. I know that exceptions should be as lightweight as possible. I'd want to avoid storing any objects.
Is there a good way to implement this?
| Yes, they most likely store the string in a private member.
Not a plain std::string though, because copying those can throw. Probably something equivalent to std::shared_ptr<std::string>.
|
70,611,234 | 70,611,406 | Default fallback for C++ template functions using enable_if | I want to write a C++ mechanism, where different instantiations of a function are called if a given class Param is derived from a certain base class.
This works pretty nicely with std::is_base_of and std::enable_if.
However, I would like to have a "default version" of this doStuff() function that is called for "every other class".
This would basically work by doing something like "if Param is not derived from A and if not derived from B", but I wonder whether there is a more elegant solution.
#include <iostream>
class A {};
class B : public A {};
class X {};
class Y : public X {};
class Other {};
template <typename Param, std::enable_if_t<std::is_base_of<A, Param>::value, bool> = true>
void doStuff() {std::cout << "Base A" << std::endl;};
template <typename Param, std::enable_if_t<std::is_base_of<X, Param>::value, bool> = true>
void doStuff() {std::cout << "Base X" << std::endl;};
int main()
{
doStuff<B>();
doStuff<Y>();
// doStuff<Other>(); this is neither derived from B and Y, so call the default case
}
The solution should work with C++14.
| When using std:::enable_if, you will have to provide a 3rd SFINAE'd overload that handles the default conditions which are not handled by the other overloads, eg:
#include <iostream>
#include <type_traits>
class A {};
class B : public A {};
class X {};
class Y : public X {};
class Other {};
template <typename Param, std::enable_if_t<std::is_base_of<A, Param>::value, bool> = true>
void doStuff() { std::cout << "Base A" << std::endl; }
template <typename Param, std::enable_if_t<std::is_base_of<X, Param>::value, bool> = true>
void doStuff() { std::cout << "Base X" << std::endl; }
template <typename Param, std::enable_if_t<!(std::is_base_of<A, Param>::value || std::is_base_of<X, Param>::value), bool> = true>
void doStuff() { std::cout << "Something else" << std::endl; }
int main()
{
doStuff<B>(); // prints "Base A"
doStuff<Y>(); // prints "Base X"
doStuff<Other>(); // prints "Something else"
}
Online Demo
That being said, in C++17 and later, you can use if constexpr instead, which is cleaner than using SFINAE in this situation, eg:
#include <iostream>
#include <type_traits>
class A {};
class B : public A {};
class X {};
class Y : public X {};
class Other {};
template <typename Param>
void doStuff() {
if constexpr (std::is_base_of_v<A, Param>)
std::cout << "Base A" << std::endl;
else if constexpr (std::is_base_of_v<X, Param>)
std::cout << "Base X" << std::endl;
else
std::cout << "Something else" << std::endl;
}
int main()
{
doStuff<B>(); // prints "Base A"
doStuff<Y>(); // prints "Base X"
doStuff<Other>(); // prints "Something else"
}
Online Demo
|
70,611,683 | 70,611,788 | Array constant not evaluating to constant even though only constexpr functions called in initialization | This is a simplified, reproducible version of my code:
type_id.h
template<typename>
void type_id() {}
typedef void(*type_id_t)();
c_sort.h (based on this answer)
template<typename Array>
constexpr void c_sort_impl(Array& array_) noexcept {
using size_type = typename Array::size_type;
size_type gap = array_.size();
bool swapped = false;
while ((gap > size_type{ 1 }) or swapped) {
if (gap > size_type{ 1 }) {
gap = static_cast<size_type> (gap / 1.247330950103979);
}
swapped = false;
for (size_type i = size_type{ 0 }; gap + i < static_cast<size_type> (array_.size()); ++i) {
if (array_[i] > array_[i + gap]) {
auto swap = array_[i];
array_[i] = array_[i + gap];
array_[i + gap] = swap;
swapped = true;
}
}
}
}
template<typename Array>
constexpr Array c_sort(Array array_) noexcept {
auto sorted = array_;
c_sort_impl(sorted);
return sorted;
}
foo.h
#include "type_id.h"
#include "c_sort.h"
#include <array>
template<class... Cs>
struct Foo
{
constexpr static auto key =
c_sort( std::array<type_id_t, sizeof...(Cs)>{ type_id<Cs>... } );
};
If I try to instantiate Foo, I get a compiler error telling me expression did not evaluate to a constant. Why is this? When initializing key, I only call functions marked with constexpr. What part of the expression can't be evaluated at compile-time?
| A recent version of GCC or Clang will tell you the evaluation that failed to yield a constant expression. See https://godbolt.org/z/adhafn8v7
The problem is the comparison:
array_[i] > array_[i + gap]
A comparison between unequal function pointers (other than to check whether or not they are equal) has an unspecified result, and therefore is not permitted inside a constant expression evaluation.
|
70,611,921 | 70,611,922 | Swift Static Library based on C++ sources: linker command failed error: ld: symbol(s) not found for architecture x86_64 clang | I've C++ based swift static library called: FooCppBasedSwiftLibrary
It's a Swift Static Library which uses some C++ sources mixed with Objective C using .mm files (Objective C++)
ObjectiveC++ classes are exposed to Swift(within the same library) using module.private.modulemap file
Library on its own builds successfully and generated libFooCppBasedSwiftLibrary.a binary and FooCppBasedSwiftLibrary.swiftmodule file BUILT FOR SIMULATOR
Then in client app project I added and linked .a file
Also in client app project I added .swiftmodule file and given it's parent folder path in SWIFT_INCLUDE_PATHS in app's build settings
Now I build client app on same SIMULATOR with same iOS version as in Static Library, But got number of errors like:
// ...100-500 lines error log above...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
| TLDR: Use linker flag: -lc++ or -lstdc++
// You can skip to the "The Endgame" section below
Initial Workaround
Background
While going through lot of forums for solution I came across someone's thoughts:
NOTE: This text is quoted from a thread of similar question (as mine), but the difference being: Importing Swift Static Library in ObjC Project
This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.
So basically all you have to do is add at least one .swift file to
that compile list and it will include the Swift libraries for you. It
doesn't even need to have any code or values in it, it can be an empty
file.
The workaround:
So considering same logic, I thought, my client App Project, which Swift based:
How will it know that static library libFooCppBasedSwiftLibrary.a has used or needs (not sure what's correct word here) standard C++ libraries, like for eg: std::
So what is did to solve this is:
In my client app project clicked on root/any folder "New File..." -> Select "C++ File" -> Set any file name -> Check "Also create a header file" -> Next -> Create -> You will get Prompt saying "Would you like to configure an Objective-C bridging header?", click on "Create Bridging Header" button
And you are DONE, now build you app it should be working fine!
This is a workaround at best, but not sure if there is any Build Setting that enforces this rahter than adding empty C++ file.
The Endgame:
After some more digging I found perfect solution to this
Firstly, ignore/undo that inital workaround, we don't need it any more
Go to to client app project's build settings (For app target) and in Other linker flags add -lc++ or -lstdc++ and build the app, done!
What to chooese -lc++ or -lstdc++?
Check "C++ standard library"/ CLANG_CXX_LIBRARY setting in build
settings
if its libc++ then use: lc++ in Other linker flags
else if its libstdc++ then use: lstdc++ in Other linker flags
I'm assuming this is explicitly telling linker to properly link .a binary of static library with given Standard C++ library
|
70,612,017 | 70,612,181 | Sudoku Solver code gives unexpected result | Question Link: https://leetcode.com/problems/valid-sudoku/description/
Below is my code for Sudoku Solver.
I am expected to return true if the sudoku is solvable else false.
class Solution {
public:
bool solveSudoku(vector<vector<char>> &board, int row, int col) {
// If the position is now at the end of the 9*9 grid
if(row == 8 and col == 9) return true;
// if column has reached upper bound
if(col==9) {
row++;
col=0;
}
// For characters other than dot move to the next position
if(board[row][col]!='.') return solveSudoku(board,row,col+1);
for(int i=1; i<=9; i++) {
char num='0'+i;
if(isValid(board, row, col, num)) {
board[row][col]=num;
if(solveSudoku(board,row,col+1)) return true;
}
board[row][col]='.';
}
return false;
}
bool isValid(vector<vector<char>> &board, int row, int col, char num) {
int i,j;
/* Checking if its duplicated on the same row */
for(i=0; i<9; i++) {
if(i!=col && board[row][i] == num) {
return false;
}
}
/* Checking if its duplicated on the same col */
for(i=0; i<9; i++) {
if(i!=row && board[i][col] == num) {
return false;
}
}
/* Checking if its duplicated inside the 3*3 grid */
int rowOffset=row-(row%3);
int colOffset=col-(col%3);
for(i=0; i<3;i++) {
for(j=0;j<3;j++) {
if((rowOffset+i)!=row && (colOffset+j)!=col && board[rowOffset+i][colOffset+j] == num) {
return false;
}
}
}
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
if(solveSudoku(board, 0, 0)) return true;
return false;
}
};
for the below test input
[[".","8","7", "6","5","4", "3","2","1"],
["2",".",".", ".",".",".", ".",".","."],
["3",".",".", ".",".",".", ".",".","."],
["4",".",".", ".",".",".", ".",".","."],
["5",".",".", ".",".",".", ".",".","."],
["6",".",".", ".",".",".", ".",".","."],
["7",".",".", ".",".",".", ".",".","."],
["8",".",".", ".",".",".", ".",".","."],
["9",".",".", ".",".",".", ".",".","."]]
Note: This is a leetcode question
It returns false which I feel is correct but the expected answer is true. How is this supposed to be a wrong Answer.
Could anyone pls explain.
Thanks in advance
| You are misinterpreting the task.
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
The filled cells do NOT violate Sudoku's rules.
|
70,612,196 | 70,612,374 | "using namespace <blank>" within the source for the library <blank> | I'm newish to C++, and I'm trying to write a library. I am using a custom namespace for the library, glz, as this seems like good practice to avoid conflicts with other libraries. The only problem is the library files end up cluttered with the namespace, especially because I have a bunch of types I've defined. For example I end up with function definitions like,
void glz::find_equilibrium(const glz::Grids &grids, const glz::vec_t &F, glz::Consts consts, double beta, glz::point_t gamma, glz::EgVec_t &f, glz::vec_t &rho, glz::vec_t &phi)
I would really like to use something like using namespace glz within the .cpp within the library files. I know this is generally frowned upon, but this seems like a special case where it might be a good idea.
Will this end up messing with the namespace of the library users?
Is there a better way to deal with this?
|
Will [using namespace glz within the .cpp] end up messing with the namespace of the library users?
No, there will not be problems for the library users.
But, there can be problems for the library developer / maintainer (i.e. presumably you). The problems are less frequent compared to using namespace in the header.
Is there a better way to deal with this?
You can simply define the functions within the namespace. That way you can use unqualified names:
namespace glz {
void
find_equilibrium(
const Grids &grids,
const vec_t &F,
Consts consts,
double beta,
point_t gamma,
EgVec_t &f,
vec_t &rho,
vec_t &phi)
|
70,612,294 | 70,612,767 | Getting parameter type of function with templates | Let's say I have a function with the following signature:
void foo(std::string const& a, int b, char &c) {
...
}
How could I do something like param_type<foo, 3>::type to get type == char?
Background:
I have a set of macros/TMP which generates a struct for converting a json object into a c++ value. I also have a set of structs representing each of the json types (primitives, array, object, etc). The main struct is defined by an X-macro, and the implementer must pass the parameter type (also used as the field type), the json type (one of the structs), and the key name into the X macros to define the fields.
I want to be able to separate the field type from the parameter type, so I can have something like std::optional<TField> as the struct's field type and TField passed to the parse method. These macros are being used in many places, so I don't want to add another parameter to the X macros.
I tried using an auto variable but as far as I know, something like the following isn't possible, which is why I want param_type.
auto value;
parse(..., value);
field = value;
| You can create a function traits with partial specialization:
template <auto func, std::size_t I>
struct param_type;
template <typename Ret, typename... Args, Ret (*func)(Args...), std::size_t I>
struct param_type<func, I>
{
using type = std::tuple_element_t<I, std::tuple<Args...>>;
};
// C-ellipsis version aka printf-like functions
template <typename Ret, typename... Args, Ret (*func)(Args..., ...), std::size_t I>
struct param_type<func, I>
{
using type = std::tuple_element_t<I, std::tuple<Args...>>;
};
Demo
|
70,612,389 | 70,613,445 | std::hex cannot process negative numbers? | I'm trying to use std::hex to read hexadecimal integers from a file.
0
a
80000000
...
These integers are both positive and negative.
It seems that std::hex cannot handle negative numbers. I don't understand why, and I don't see a range defined in the docs.
Here is a test bench:
#include <iostream>
#include <sstream>
#include <iomanip>
int main () {
int i;
std::stringstream ss;
// This is the smallest number
// That can be stored in 32 bits -1*2^(31)
ss << "80000000";
ss >> std::hex >> i;
std::cout << std::hex << i << std::endl;
}
Output:
7fffffff
| Setting std::hex tells the stream to read integer tokens as though using std::scanf with the %X formatter. %X reads into an unsigned integer, and the resulting value would overflow an int even through the bit pattern fits. Because of the overflow, the read fails, and the contents of i cannot be trusted to hold the expected value. Side note: i will be set to 0 if compiling to C++11 or more recent or unchanged from its current unspecified value before c++11.
Note that if we check the stream state after the read, something you should ALWAYS do, we can see that the read failed:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdint> // added for fixed width integers.
int main () {
int32_t i; //ensure 32 bit int
std::stringstream ss;
// This is the smallest number
// That can be stored in 32 bits -1*2^(31)
ss << "80000000";
if (ss >> std::hex >> i)
{
std::cout << std::hex << i << std::endl;
}
else
{
std::cout << "FAIL! " << std::endl; //will execute this
}
}
The solution is, as the asker surmised in the comments to read into an unsigned int (uint32_t to avoid further surprises if int is not 32 bits). The following is the zero-surprises version of the code using memcpy to transfer the exact bit pattern read into i.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdint> // added for fixed width integers.
#include <cstring> //for memcpy
int main () {
int32_t i; //ensure 32 bit int
std::stringstream ss;
// This is the smallest number
// That can be stored in 32 bits -1*2^(31)
ss << "80000000";
uint32_t temp;
if (ss >> std::hex >> temp)
{
memcpy(&i, &temp, sizeof(i));// probably compiles down to cast
std::cout << std::hex << i << std::endl;
}
else
{
std::cout << "FAIL! " << std::endl;
}
}
That said, diving into old-school C-style coding for a moment
if (ss >> std::hex >> *reinterpret_cast<uint32_t*>(&i))
{
std::cout << std::hex << i << std::endl;
}
else
{
std::cout << "FAIL! " << std::endl;
}
violates the strict aliasing rule, but I'd be stunned to see it fail once 32 bit int is forced with int32_t i;. This might even be legal in more recent C++ Standards as being "Type Similar", but I'm still wrapping my head around that.
|
70,612,537 | 70,612,653 | C++ calculation of long long with int | below you can find a part of my C++ code of a box class.
When I want to calculate the volume for
l=1039
b=3749
h=8473
I am expecting 33004122803.
Unfortunately I do not understand why only the first implementation (CalculateVolume1) gives the correct answer.
The other two calculations result in -1355615565.
Can someone please help me to understand why this is the case?
class Box{
private:
int l,b,h;
public:
//works
long long CalculateVolume1() { return (long long) l*b*h;}
// does not work
long long CalculateVolume2() { return long long v = l*b*h;}
//does not work
long long CalculateVolume3()
{
long long v = long long (l)* long long(b)* long long (h);
return v;
}
};
| In the first one, (long long) l*b*h, the cast applies to l, as if it had been written ((long long)l)*b*h. So l gets converted to long long. And since one of the factors in the multiplication is long long, the other two are promoted to long long and the result of the multiplication is correct.
"Fixing" the syntactic errors in the second and third,
long long v = l*b*h;
here, the type of all three factors is int, so the multiplication is done on ints, and the result overflows.
long long v = (long long)l*(long long)b*(long long)h;
this is essentially the same as the first: all three factors are promoted to long long, this time by explicit casts on all three, so the result is calculated using long long arithmetic, and the result fits.
The problem with the second one as written is that you can't define a variable inside a return statement. So
return long long v = l; // illegal
should be:
long long v = l;
return v;
The problem with the third one as written is that a function-style cast has to have a name that's a single word:
long long v = int(l); // okay, but pointless
long long v = long long(l); // error, invalid name
could be:
typedef long long my_type;
long long v = my_type(l); // okay
|
70,612,577 | 70,623,107 | Does anyone know of a fix for an MSVC compiler bug/annoyance where SIMD Extension settings get "stuck" on AVX? | Does anyone know of a fix for an MSVC compiler bug/annoyance where SIMD Extension settings get "stuck" on AVX?
The context of this question is coding up SIMD CPU dispatchers, closely following Agner's well-known dispatch_example2.cpp project. I've been going back and forth in three different MSVC projects and have dead-ended with this issue in two of them, after which one of those two "fixed itself" somehow.
The question is pretty simple: To compile the dispatchers I need to compile 4 times with
/arch:AVX512 /DINSTRSET=10
/arch:AVX2 /DINSTRSET=8
/arch:AVX /DINSTRSET=7
/arch:SSE2 /D__SSE4_2__
While I'm doing this I'm watching the value of INSTRSET and this code:
#if defined ( __AVX512VL__ ) && defined ( __AVX512BW__ ) && defined ( __AVX512DQ__ )
#define AVX512_FLAG 1
#else
#define AVX512_FLAG 2
#endif
#if defined ( __AVX2__ )
#define AVX2_FLAG 1
#else
#define AVX2_FLAG 2
#endif
#if defined ( __AVX__ )
#define AVX_FLAG 1
#else
#define AVX_FLAG 2
#endif
The behavior is like this: For the three AVX compiles everything is exactly as expected. When the problem is not happening, the SSE2 compile shows as expected (AVX512_FLAG, AVX2_FLAG, AVX_FLAG == 2) and the final code runs fine.
When the problem is happening, for the /arch:SSE2 /D__SSE4_2__ compile the code above shows AVX512_FLAG == 2 but AVX2_FLAG == AVX_FLAG == 1 and INSTRSET == 8, and the compiler thinks the AVX2 instructions are enabled - the project compiles, but crashes on an SSE4.2 machine.
If I try /arch:SSE2 /DINSTRSET=6 then I get INSTRSET == 6 for the compile, but the code above still shows AVX2_FLAG == 1 and AVX_FLAG == 1, and the final project still crashes on an SSE4.2 machine.
The crashes happen even if I don't run any vector code - anything that calls into the dispatcher crashes immediately even if all vector code is short circuited.
FYI, trying /DINSTRSET=6 is just an act of desperation - I've never gotten anything to work with SSE4.2 without using /D__SSE4_2__
Does anyone know how to fix this problem that is completely halting my progress? Tried "Clean Solution" already.
| I figured this out (it's simple and boring). For the incremental object files I'm compiling 3 .obj files from the same .cpp (the .cpp with the vector code). When the MSVC SIMD settings are changed in the project level Properties, they may or may not get inherited in the .cpp file Properties. This is where the project gets "stuck" on AVX (sometimes, not always). Just need to check the .cpp file properties and make sure they are correct.
BTW I'm using VS 2019, /std:c++17 and the context above is the 32-bit build.
|
70,612,729 | 70,612,800 | Exception thrown when trying to access a protected variable from a child class after a dynamic casting | I am trying to learn about dynamic casting in C++.
So I have developed 2 classes to test some things related to dynamic casting:
class Entity {
protected:
int x = 10;
public:
virtual void f1() { cout << "f1 from Entity class" << endl; }
};
class Player : public Entity {
public:
void f1() { cout << "f1 from Player class" << endl; }
int f2() { return x; }
void f3() { cout << "f3 from Player class" << endl; }
};
The method f2() returns x that is defined in the Parent Class Entity.
And here is the main:
int main() {
Entity* e = new Entity;
Player* p = dynamic_cast<Player*>(e);
cout << p->f2() << endl;
//the program prints : "p is not null"
if(p == nullptr)
cout << "p is null";
else
cout << "p is not null";
return 0;
}
An exception is thrown when calling p->f2(), specifically on line return x; and it says:
Exception thrown: read access violation.
this was nullptr.
The strange thing here is that x is a protected variable, so it must exist at
Entity and Player objects, but after the dynamic casting from Entity to Player, the new object can not access it.
So what is the exception reason?
Note: When doing static casting instead of dynamic, p->f2() gives 10 normally
| dynamic_cast will never lie. It checks the runtime type of the object to see if it matches the T gi8ven in the dynamic_cast<T>. You created an instance of the Entity base class. The runtime type of this object is Entity because that's what you created.
dynamic_cast knows the runtime type of the object, so it knows dynamic_cast<Player*> cannot work since the object isn't a Player object. Therefore, it returns nullptr.
static_cast doesn't know if the object is a Player or not; it assumes that it is and returns a pointer to that object if it is there. But since it's not there, any attempt to use the result of the static_cast yields undefined behavior.
Which just so happens to do what you want, but there's no guarantee of that.
|
70,612,730 | 70,612,834 | How can I make this expression involving floating-point functions a compile-time constant? | I have a constant integer, steps, which is calculated using the floor function of the quotient of two other constant variables. However, when I attempt to use this as the length of an array, visual studio tells me it must be a constant value and the current value cannot be used as a constant. How do I make this a "true" constant that can be used as an array length? Is the floor function the problem, and is there an alternative I could use?
const int simlength = 3.154*pow(10,7);
const float timestep = 100;
const int steps = floor(simlength / timestep);
struct body bodies[bcount];
struct body {
string name;
double mass;
double position[2];
double velocity[2];
double radius;
double trace[2][steps];
};
| It is not possible with the standard library's std::pow and std::floor function, because they are not constexpr-qualified.
You can probably replace std::pow with a hand-written implementation my_pow that is marked constexpr. Since you are just trying to take the power of integers, that shouldn't be too hard. If you are only using powers of 10, floating point literals may be written in the scientific notation as well, e.g. 1e7, which makes the pow call unnecessary.
The floor call is not needed since float/double to int conversion already does flooring implicitly. Or more correctly it truncates, which for positive non-negative values is equivalent to flooring.
Then you should also replace the const with constexpr in the variable declarations to make sure that the variables are usable in constant expressions:
constexpr int simlength = 3.154*my_pow(10,7); // or `3.154e7`
constexpr float timestep = 100;
constexpr int steps = simlength / timestep;
Theoretically only float requires this change, since there is a special exception for const integral types, but it seems more consistent this way.
Also, I have a feeling that there is something wrong with the types of your variables. A length and steps should not be determined by floating-point operations and types, but by integer types and operations alone. Floating-point operations are not exact and introduce errors relative to the mathematical precise calculations on the real numbers. It is easy to get unexpected off-by-one or worse errors this way.
|
70,613,097 | 70,613,217 | In IsClassT<T>, why use "int C::*"? I am confusing about the int type | An example described in book C++ Templates The Complete Guide:
template <typename T>
class IsClass {
private:
typedef char One;
typedef struct { char a[2];} Two;
template<typename C> static One test(int C::*);
template<typename C> static Two test(...);
public:
enum {
Yes = (sizeof(IsClass<T>::test<T>(0)) == 1)
};
enum {
No = !Yes
};
};
I've read related topic Where can I find a description about the usage of "int C::*"?
I've got the concept that C::* means a pointer to member, and test(0) means test(nullptr), but I have some other questions:
Suppose the compiler does not check if the class C really has a member of type int. Why compiler does not check?
The int type in int C::* could be replaced by any type but void, although I think void is less confusing. Why this error reported?
In file included from testisclass.cpp:12:
../inc/isclass.hpp:17:54: error: cannot declare pointer to ‘void’ member
17 | template<typename C> static One test(void C::*);
| ^
../inc/isclass.hpp: In instantiation of ‘class IsClass<A>’:
testisclass.cpp:22:16: required from here
../inc/isclass.hpp:17:41: error: creating pointer to member of type void
17 | template<typename C> static One test(void C::*);
| ^~~~
../inc/isclass.hpp: In instantiation of ‘class IsClass<int>’:
testisclass.cpp:28:18: required from here
../inc/isclass.hpp:17:41: error: creating pointer to member of type void
Yes = true/false is a complete definition, why still No defined?
| Because the Standard says so. In [dcl.mptr]:
3 - Example: [...]
double X::* pmd;
[...] The declaration of pmd is well-formed even though X has no members of type double. [...]
4 - A pointer to member shall not point to [...] “cvvoid”.
Some possible reasons: if you had to check data members, you wouldn't be able to define pointer to data members of incomplete classes. And while void* is useful for interoperability with C and for type erasure, C doesn't have pointer to member types, and it's unlikely that you'd ever need to type erase a pointer to member.
As for why No is defined in addition to Yes - no idea, perhaps the author thought it might be useful.
|
70,613,175 | 70,613,425 | Atomically copy a bit (or bits) into an integer | I have some code that copies masked bits into an integer by first clearing them in the target int then ORing them into the int.
Like this:
bitsToSet = 6
targetInt &= ~(1 << bitsToSet)
targetInt |= desiredBitValue << bitsToSet
The problem is that it now needs to be thread safe, and I need to make the operation atomic. I think that using std:atomic<int> would only make each sub-operation atomic but not the operation as a whole.
How can I make the whole operation (including both the &= and the |= operations) atomic?
For example, it would solve the problem for me if I had a function (or better, a macro) like SetBits(TARGET, MASK, VALUE) that would atomically set the MASKed bits in TARGET to VALUE. The MASK and VALUE can already be left-shifted.
My current, non-atomic code is
#define SetBits(TARGET, MASK, VALUE) {(TARGET) &= ~((uint64_t)MASK); (TARGET)|=((uint64_t)VALUE);}
| You could use a compare-exchange loop:
void SetBitsAtomic(std::atomic<int>& target, int mask, int value) {
int original_value = target.load();
int new_value = original_value;
SetBits(new_value, mask, value);
while (!target.compare_exchange_weak(original_value, new_value)) {
// Another thread may have changed target between when we read
// it and when we tried to write to it, so try again with the
// updated value
new_value = original_value;
SetBits(new_value, mask, value);
}
}
This reads the original value of target, does the masking operations, and then writes the modified value back to target only if no other thread has modified it since it was read. If another thread has modified target then its updated value gets written into original_value and it keeps trying until it manages to update target before anyone else.
Note that I've used (default) full sequential consistency here for the load and compare_exchange_weak operations. You may not need full sequential consistency, but I have no way of knowing exactly what you need without more info on what you're using this for.
Alternatively, you could just use a mutex:
std::mutex mtx;
void SetBitsAtomic(int& target, int mask, int value) {
std::lock_guard lock{mtx};
SetBits(target, mask, value);
}
This may be less performant than the lock-free compare_exchange_weak version, but again it really depends what it's being used for. It's certainly simpler and easier to reason about, which may be more important than raw performance in your situation.
|
70,613,471 | 70,620,457 | Cython program (print Hello world) much slower than pure Python | I am new to Cython. I've written a super simple test programm to access benefits of Cython. Yet, my pure python is alot faster. Am I doing something wrong?
test.py:
import timeit
imp = '''
import pyximport; pyximport.install()
from hello_cy import hello_c
from hello_py import hello_p
'''
code_py = '''
hello_p()
'''
code_cy = '''
hello_c()
'''
print(timeit.timeit(stmt=code_py, setup=imp))
print(timeit.timeit(stmt=code_cy, setup=imp))
hello_py.py:
def hello_p():
print('Hello World')
hello_cy.pyx:
from libc.stdio cimport printf
cpdef void hello_c():
cdef char * hello_world = 'hello from C world'
printf(hello_world)
hello_py timeit takes 14.697s
hello_cy timeit takes 98s
Am I missing something? How can I make my calls to cpdef functions run faster?
Thank you very much!
| I strongly suspect a problem in your configuration.
I have (partially) reproduced your tests in Windows 10, Python 3.10.0, Cython 0.29.26, MSVC 2022, and got quite different results
Because in my tests the Cython code is slightly faster. I made 2 changes:
in hello_cy.pyx, to make both code closer, I have added the newline:
...
printf("%s\n", hello_world)
In the main script I have splitted the call of the functions and the display of the times:
...
pyp = timeit.timeit(stmt=code_py, setup=imp)
pyc = timeit.timeit(stmt=code_cy, setup=imp)
print(pyp)
print(pyc)
When I run the script I get (after pages of hello...):
...
hello from C world
hello from C world
19.135732599999756
14.712803700007498
Which looks more like what could be expected...
Anyway, we do not really know what is tested here, because as much as possible, the IO should not be tested because it depends of a lot of things outside of the programs themselves.
|
70,613,489 | 70,613,597 | C++ type to hold members that can't be initialized in the constructor | I have some members that can't be initialized at construction time of the container class because the information to construct them is not available. At the moment I'm using std::unique_ptr to construct them later when the information becomes available.
The dynamic allocation/indirection is an unnecessary overhead as I know they will be constructed eventually. I could use std::optional, but I feel the semantics of std::optional will make the ones reading the code think the members are somehow optional and they might be missing which is not the case.
Is there any std library type that can hold a type for later construction with better semantics than std::optional?
EDIT: example code
struct Inner
{
Inner(int someValue)
: internalValue(someValue)
{}
int internalValue;
};
struct Outer
{
Outer(){/*...*/}
void createInner(int someValue)
{
assert(inner == nullptr);
inner = std::make_unique<Inner>(someValue);
}
// I would like to avoid the dynamic memory allocation here
std::unique_ptr<Inner> inner;
};
| std:::optional is what you are looking for, eg:
#include <optional>
struct Inner
{
Inner(int someValue)
: internalValue(someValue)
{}
int internalValue;
};
struct Outer
{
Outer(){/*...*/}
void createInner(int someValue)
{
inner = Inner(someValue);
}
std::optional<Inner> inner;
};
If you don't like how optional looks in your code, you can simply define an alias to give it a more suitable name for your situation, eg:
#include <optional>
struct Inner
{
Inner(int someValue)
: internalValue(someValue)
{}
int internalValue;
};
template<typename T>
using delayed_create = std::optional<T>;
struct Outer
{
Outer(){/*...*/}
void createInner(int someValue)
{
inner = Inner(someValue);
}
delayed_create<Inner> inner;
};
|
70,613,542 | 70,614,185 | Conversion from string literal loses const qualifier | error C2664: 'void add_log(char *,...)': cannot convert argument 1 from 'const char [33]' to 'char *'
message : Conversion from string literal loses const qualifier (see /Zc:strictStrings)
I restarted my computer and now my project stopped being able to be built. I've looked everywhere that had the similar problems but can no longer build this project with any changes to the project.
Using -> ISO C++17 Standard (/std:c++17)
Character Set -> Use Multi-Byte Character Set
I don't understand what happened in a span of a few minutes for this to just completely break my project when I was compiling multiple times this morning.
| As of today, all I had to do was add a const before anything that I use a char* for. This was used with VS2019 using std:c++17 and Multi-Byte Character Set.
The original code:
void add_log(char* format, ...)
The new code
void add_log(const char* format, ...)
|
70,613,774 | 70,613,916 | How to get all derived classes from a base class in C++? | I'm implementing a game engine in C++ which uses an ECS (Entity-Component-System).
Each GameObject can have multiple Components (stored in GameObject's std::vector<Component*> _components).
I have a method that allows me to get a Component of a GameObject by specifying the type of Component I want:
// In GameObject.h
template <typename T> T* GetComponent() {
for (Component* c : _components) {
if (typeid(*c) == typeid(T)) return (T*)c;
}
return nullptr;
}
// In main.cpp
RandomComponent* RC = gameObject.GetComponent<RandomComponent>();
Now let's say I have those Components defined:
class TerrainComponent { /* ... */ }
class PerlinTerrainComponent : public TerrainComponent { /* ... */ }
class FlatTerrainComponent : public TerrainComponent { /* ... */ }
// And possibly many more
And have world GameObjects, which all have a TerrainComponent's derived class attached to it.
My problem is that I would need a way to get the TerrainComponent of a world, like so:
TerrainComponent* TC = world.GetComponent<TerrainComponent>();
And get any type of TerrainComponent attached to the world (which, in reality, will be a TerrainComponent derived class).
Is it possible, in C++, to implement a method that would allow me to do that (get all derived classes of a class), without having to manually update a list of TerrainComponent derived classes?
| Assuming these classes are all polymorphic/dynamic (which they need to be to use typeid like this), you can just use dynamic_cast instead:
template <typename T> T* GetComponent() {
for (Component* c : _components) {
if (T *tc = dynamic_cast<T *>(c)) return tc;
}
return nullptr;
}
|
70,614,047 | 70,614,178 | Using erase - is there a way to make this code less repetitive? | This code deletes six lines from a file about a person from a contact list. This code works perfectly fine, however I don't know how to make this code less repetitive.
I use a while loop to push my lines inside a vector, and then use the following for loop to erase from the vector. At the end of the loop, I recreate the file again and push the remaining data into the file.
As you can see, I repeat file.erase() many times.
std::cout << "Enter name of contact you would like to delete: ";
getline(std::cin, search);
for(int i = 0; i < (int)file.size(); ++i)
{
if(file[i].substr(0, search.length()) == search)
{
file.erase(file.begin() + i);
file.erase(file.begin() + i);
file.erase(file.begin() + i);
file.erase(file.begin() + i);
file.erase(file.begin() + i);
file.erase(file.begin() + i);
std::cout << "Success, contact deleted!"<< std::endl;
i = 0;
}
}
Could I use the following code to manufacture my code in a better, less repetitive, way?
for(int remaining = 6; remaining > 0 && itr != file.end(); itr++, remaining--) {
| Instead of erasing the first element for 6 times, you can do:
file.erase(file.begin() + i, file.begin() + i + 6)
The two args in this erase method denotes the range [first, last) to erase. Reference link
|
70,614,651 | 70,614,700 | Templated function type lost when embedding templates | When playing around with C++20's concepts, I've found that when making a concept describing how a function should be (i.e. T must be a callable function that takes a size_t as argument), then using that concept in another template, the type of the function seems to be "lost". I don't really have a good way of phrasing it, so here's the code:
template<typename Func, typename ... Args>
concept FuncWithArgs = requires (Func f, Args... args) { f((size_t)1, args...); };
template<FuncWithArgs Func, typename ... Args>
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
Then calling it with:
void MyFunc(size_t i, const std::string& s)
{
std::cout << i << ", " << s << std::endl;
}
int main(int argc, char **argv)
{
Foo(MyFunc, 1, "asdf");
return 0;
}
Gives the following compilation error messages (using GCC 11.2 with -std=c++20, https://godbolt.org/z/dvs9j77o3):
<source>: In function 'int main(int, char**)':
<source>:20:8: error: no matching function for call to 'Foo(void (&)(size_t, const string&), int, const char [5])'
20 | Foo(MyFunc, 1, "asdf");
| ~~~^~~~~~~~~~~~~~~~~~~
<source>:8:6: note: candidate: 'template<class Func, class ... Args> requires FuncWithArgs<Func> void Foo(const Func&, size_t, Args ...)'
8 | void Foo(const Func& f, size_t i = 0, Args... args)
| ^~~
<source>:8:6: note: template argument deduction/substitution failed:
<source>:8:6: note: constraints not satisfied
<source>: In substitution of 'template<class Func, class ... Args> requires FuncWithArgs<Func> void Foo(const Func&, size_t, Args ...) [with Func = void(long unsigned int, const std::__cxx11::basic_string<char>&); Args = {const char*}]':
<source>:20:8: required from here
<source>:5:9: required for the satisfaction of 'FuncWithArgs<Func>' [with Func = void()]
<source>:5:24: in requirements with 'Func f', 'Args ... args' [with Args = {}; Func = void()]
<source>:5:59: note: the required expression 'f((size_t)(1), args ...)' is invalid
5 | concept FuncWithArgs = requires (Func f, Args... args) { f((size_t)1, args...); };
| ~^~~~~~~~~~~~~~~~~~~~
cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail
Looking closely at this, I first see [with Func = void(long unsigned int, const std::__cxx11::basic_string<char>&); Args = {const char*}], followed shortly after by [with Args = {}; Func = void()]. Why/how did Func change?
After more digging, I came up with a solution that works (https://godbolt.org/z/j6W7P895q):
template<typename Func, typename ... Args>
requires requires (Func f, Args... args)
{
f((size_t)1, args...);
}
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
Since the constraint used is identical to the one I tried doing with the concept, it leads me to believe that the type of the function is "lost" and that the concept itself is properly written.
Is it something that I am not doing right, a known issue, or a limitation of templates?
| When you write this:
template<typename Func, typename ... Args>
concept FuncWithArgs = requires (Func f, Args... args) { f((size_t)1, args...); };
template<FuncWithArgs Func, typename ... Args>
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
The declaration of Foo is shorthand for this:
template <typename Func, typename ... Args>
requires FuncWithArgs<Func>
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
Which probably makes it clear what went wrong. You're requiring that the function is callable with no args (well, really 1 arg, the size_t), but that's not what you want. You want this:
template <typename Func, typename ... Args>
requires FuncWithArgs<Func, Args...>
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
which can be written using this shorthand:
template <typename ... Args, FuncWithArgs<Args...> Func>
void Foo(const Func& f, size_t i = 0, Args... args)
{
f(i, args...);
}
|
70,615,011 | 70,615,056 | Non-constant-expression cannot be narrowed from type 'unsigned long' to 'int' in initializer list | please help a c++ newbie understand what is going wrong here. I got compile error message of Non-constant-expression cannot be narrowed from type 'unsigned long' to 'int' in initializer list on leetcode web and my local ubuntu terminal, but it works perfectly fine on my CLion IDE. Also could explain why I got the error and how to solve it?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> heights({{1, 2, 2, 3, 5}, {3, 2, 3, 4, 4}, {2, 4, 5, 3, 1}, {6, 7, 1, 4, 5}, {5, 1, 1, 2, 4}});
deque<vector<int>> dq;
for (int i=0;i<heights.size();i++){
dq.push_back({i,heights[0].size()-1});
}
for (auto vec: dq){
if (vec.empty())
cout<< "vec is empty";
else
cout<<vec[0]<< " "<< vec[1]<<endl;
}
return 0;
}
Soon as switch to pair from vector<int>, the error is gone. It's quite confusing to a newbie like me. Please shed some light on this.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> heights({{1, 2, 2, 3, 5}, {3, 2, 3, 4, 4}, {2, 4, 5, 3, 1}, {6, 7, 1, 4, 5}, {5, 1, 1, 2, 4}});
deque<pair<int, int>> dq;
for (int i=0;i<heights.size();i++){
dq.push_back({i,heights[0].size()-1});
}
for (auto [u,v]: dq){
cout<<u<< " "<< v<<endl;
}
return 0;
}
| When you use brace-initialization, it is forbidden for a narrowing conversion to be used to convert from the type of the value in the braced list to the type that the constructor actually requires. heights[0].size()-1 has type size_t, and the constructor of std::vector<int> takes std::initializer_list<int>. Usually, int cannot represent all values of type size_t, which means that size_t to int is a narrowing conversion. You can fix this using an explicit cast:
dq.push_back({i,static_cast<int>(heights[0].size()-1)});
When the type being constructed is std::pair<int, int>, it is a different story. No conversion actually occurs when calling the constructor; instead, the following constructor is called:
template< class U1, class U2 >
constexpr pair( U1&& x, U2&& y );
See cppreference.
Internally, presumably in the constructor initializer list, the constructor will convert size_t to int, but this will not be done inside braces, so it's legal.
|
70,615,288 | 70,615,425 | exception thrown error. why is it happening? and what should i do to fix it? | int main() {
int** a;
int l, h;
cout << "the lenght of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int* [l];
a[l] = new int [h];
//a = new int [l][h];
if (l = h) {
Pn(l,a);
}
}
void Pn(int l,int** a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int** a) {
for (int i = 0; i < h; i++) {
for (int j = 0; j < l; j++)
a[i][j] = 0; //the exception error
}
}
this is a part of my code where the error is happening. what is this error and how can i fix it?
also yes i am putting the same numbers for 'l' and 'h'.
| You are not allocating the array correctly.
After a = new int* [l];, you try to access a[l], which is out of bounds.
You need to allocate a separate int[] for each element of the array's 2nd dimension.
Even if you were doing that correctly, there are other problems in the code:
leaking the array.
if (l = h) is using the = assignment operator, thus assigning the value of h to l, and then comparing the new value of l against 0. To compare l to h, you need to use the == comparison operator instead.
the loop in intMatrix() is backwards. The outer loop needs to iterate through l, and the inner loop needs to iterate through h, not the other way around. The only way intMatrix() would work correctly is if l and h have the same value, which your if is (incorrectly) trying to force. But the user is not being forced to enter 2 of the same value.
With that said, try something more like this:
#include <iostream>
using namespace std;
void Pn(int l, int** a);
void intMatrix(int l, int h, int** a);
int main() {
int** a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int* [l];
for(int i = 0; i < l; ++i) {
a[i] = new int [h];
}
if (l == h)
Pn(l, a);
else
intMatrix(l, h, a);
for(int i = 0; i < l; ++i) {
delete[] a[i];
}
delete[] a;
}
void Pn(int l, int** a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int** a) {
for (int i = 0; i < l; ++i) {
for (int j = 0; j < h; ++j)
a[i][j] = 0;
}
}
Though, you might consider using a 1-dimensional contiguous array instead of a 2-dimensional sparse array, eg:
#include <iostream>
using namespace std;
void Pn(int l, int* a);
void intMatrix(int l, int h, int* a);
int main() {
int* a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int [l*h];
if (l == h)
Pn(l, a);
else
intMatrix(l, h, a);
delete[] a;
}
void Pn(int l, int* a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int* a) {
for (int i = 0; i < l; ++i) {
for (int j = 0; j < h; ++j)
a[(i*l)+j] = 0;
}
}
That being said, consider using std::vector instead of new[] manually. For instance, for the 2-dimensional array:
#include <iostream>
#include <vector>
using namespace std;
void intMatrix(vector<vector<int>> &a);
int main() {
vector<vector<int>> a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a.resize(l);
for(int i = 0; i < l; ++i) {
a[i].resize(h);
}
intMatrix(a);
// or simply:
// a.resize(l, vector<int>(h, 0));
}
void intMatrix(vector<vector<int>> &a) {
for (size_t i = 0; i < a.size(); ++i) {
vector<int> &b = a[i];
for (size_t j = 0; j < b.size(); ++j)
b[j] = 0;
}
}
Or, for the 1-dimensional array:
#include <iostream>
#include <vector>
using namespace std;
void intMatrix(vector<int> &a);
int main() {
vector<int> a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a.resize(l*h);
intMatrix(a);
// or simply:
// a.resize(l*h, 0);
}
void intMatrix(vector<int> &a) {
for (size_t i = 0; i < a.size(); ++i) {
a[i] = 0;
}
}
|
70,615,371 | 70,615,581 | What happens when running (int *)"some string" | I'm learning the pointer nowadays and I find there is a code on the book
std::cout << (int *)"Home of the jolly bytes";
I run it and it print the
0x55c064d9b005
that seem like something's address and I want to know what did it print, so I use "*" try to check its value at that address and convert it to char and foud it's "H".
std::cout << (char)*(int *)"Home of the jolly bytes";
//output: H
I know that "typename*" creats a pointer points to the typename data, but what happened when running this code?
| On this statement:
std::cout << (int *)"Home of the jolly bytes";
It is indeed printing the starting address of the characters in the string literal. A string literal is a const char[N] array (in this case, N=24), and an array decays into a pointer to its 1st element.
std::istream does not have any operator<< that accepts an int* pointer, but it does have one that accepts a char* pointer to print a null-terminated string, and one that accepts a void* pointer to print the address being pointed at.
int* is implicitly convertible to void*, so the code is printing the address of the string literal, rather than printing its contents. But, it is unusual to cast a char* pointer to an int* in this situation, void* would make more sense, eg:
std::cout << (const void *)"Home of the jolly bytes";
In any case, on this statement:
std::cout << (char)*(int *)"Home of the jolly bytes";
It is reinterpreting the starting address of the characters as-if it were the starting address of an int instead. Thus, dereferencing that int* pointer will read the 1st 4 characters together as a single int value (assuming char is 8 bits in size, and int is 32 bits in size):
--------------------------------------------------------------------------------------------
| H | o | m | e | | o | f | | t | h | e | | j | o | l | l | y | | b | y | t | e| s |
--------------------------------------------------------------------------------------------
|___|
|
char*
|_______________|
|
int*
Thus, the dereferenced int will consist of these bytes in memory:
H o m e
*int = 0x48 0x6F 0x6D 0x65
The code is then truncating that int value to a 1-byte char value.
On a little-endian system, that will yield the value of the H character:
H o m e
*int = 0x48 0x6F 0x6D 0x65
= 0x656D6F48 (decimal 1701670728)
= 0x48 when truncated to char
On a big-endian system, it will yield the value of the e character instead:
H o m e
*int = 0x48 0x6F 0x6D 0x65
= 0x486F6D65 (decimal 1215262053)
= 0x65 when truncated to char
|
70,615,480 | 70,615,582 | Accessing private member variables of a class from a static method | I am able to access the private member variable of the class shown in below code directly using an object instance (pointer to object). As per my understanding private members should not be accessible. Can someone please help to explain the reason behind this behaviour ?
#include <iostream>
class myClass;
using myClassPtr = std::shared_ptr<myClass>;
class myClass {
public:
myClass(unsigned int val) : m_val(val) {}
~myClass() {}
static
myClassPtr create(unsigned int val) {
myClassPtr objPtr = nullptr;
objPtr = std::make_shared<myClass>(val);
if(objPtr) {
std::cout << objPtr->m_val << std::endl;
}
return objPtr;
}
private:
unsigned int m_val;
};
int main () {
myClassPtr objPtr = myClass::create(10);
return 0;
}
Output
anandkrishnr@anandkrishnr-mbp cpp % g++ static_test.cc -std=c++11 -Wall -Werror
anandkrishnr@anandkrishnr-mbp cpp % ./a.out
10
| static myClassPtr create(unsigned int val) {
create() is a static method of myClass, it is a member of this class. As such it it entitled to access all private members and methods of its class. This right extends not only to its own class instance, but any instance of this class.
As per my understanding private members should not be accessible.
... except by members of their class.
Let's create a completely pointless copy constructor for your class, the same copy constructor you would get by default:
myClass(const myClass &o) : m_val{o.m_val} {}
This copy constructor has no issues, whatsoever, of accessing m_val of the passed-in object. Exactly the same thing happens here. m_val is a private member of its class. It doesn't mean that only an instance of the same exact object can access its private members, it means that any instance of the class, or a static class method, can access the private class members.
|
70,615,486 | 70,615,524 | Problem with casting pointers from one structure to another structure? | I'm trying to cast the address of individual array components into another structure
Here are the structures:
#define ADDRESS_SPACE 8
struct dma_engine
{
int *Address[ADDRESS_SPACE] = {nullptr};
};
struct data_engine
{
int data[ADDRESS_SPACE] = {0x10,0x14,0x18,0x1B,0x20,0x24,0x28,0x2B};
};
Its working when I do each array component individually, like that:
dma_engine Dma_0;
data_engine Data_0;
Dma_0.Address[0] = (int*) &Data_0.data[0];
Dma_0.Address[1] = (int*) &Data_0.data[1];
Dma_0.Address[2] = (int*) &Data_0.data[2];
Dma_0.Address[3] = (int*) &Data_0.data[3];
Dma_0.Address[4] = (int*) &Data_0.data[4];
Dma_0.Address[5] = (int*) &Data_0.data[5];
Dma_0.Address[6] = (int*) &Data_0.data[6];
Dma_0.Address[7] = (int*) &Data_0.data[7];
But when I'm trying to pass everything at once, like that:
dma_engine Dma_0;
data_engine Data_0;
Dma_0.Address = (int*) &Data_0.data;
I receive the following compilation ERROR:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:30:36: error: incompatible types in assignment of ‘int*’ to ‘int* [8]’
30 | Dma_0.Address = (int*) &Data_0.data;
Also, doesn't work when I try this way:
dma_engine Dma_0;
data_engine Data_0;
Dma_0.Address = &Data_0.data;
I receive this ERROR !
main.cpp: In function ‘int main(int, char**)’:
main.cpp:30:36: error: incompatible types in assignment of ‘int*’ to ‘int* [8]’
30 | Dma_0.Address = (int*) &Data_0.data;
Can someone please help me with this?
Many Thanks
| You need to change Address to be a pointer to int[ADDRESS_SPACE]:
#define ADDRESS_SPACE 8
struct dma_engine {
int (*Address)[ADDRESS_SPACE] = nullptr; // correct type
};
struct data_engine {
int data[ADDRESS_SPACE] = {0x10, 0x14, 0x18, 0x1B, 0x20, 0x24, 0x28, 0x2B};
};
int main() {
dma_engine Dma_0;
data_engine Data_0;
Dma_0.Address = &Data_0.data; // no cast here
}
or just a plain int*:
#define ADDRESS_SPACE 8
struct dma_engine {
int *Address = nullptr; // int*
};
struct data_engine {
int data[ADDRESS_SPACE] = {0x10, 0x14, 0x18, 0x1B, 0x20, 0x24, 0x28, 0x2B};
};
int main() {
dma_engine Dma_0;
data_engine Data_0;
Dma_0.Address = Data_0.data; // still no cast here, but don't take the address
}
|
70,615,789 | 70,615,837 | undefined reference to `Class::Function() / error: Id returned 1 exit status | I'm trying to initialize value, I follow Bjarne Stroustrup's book but cannot run this code.
#include <iostream>
using namespace std;
struct Date
{
int y, m, d; // year, month, day
Date(int y, int m, int d); // check for valid & initialize
void add_day(int n); // increase the Date by n days
};
int main()
{
Date today(2021, 1, 6);
return 0;
}
Here is the error:
undefined reference to `Date::Date(int, int, int)'
collect2.exe: error: ld returned 1 exit status
| In the C++ programming language, you can define a struct just like you define a class. The reason you're getting the error is because you haven't defined the methods strictly.
#include <iostream>
using namespace std;
struct Date
{
/* fields */
int _year, _month, _day;
/* constructor */
Date(int year, int month, int day) : _year(year), _month(month), _day(day){}
/* setter method */
void add_day(int n)
{
/* You need to develop an algorithm to keep track of the end of the month and the year. */
_day += n;
}
/* getter method */
int get_day()
{
return _day;
}
};
int main()
{
Date today(2021, 1, 6);
today.add_day(1);
cout << today.get_day() << endl;
return 0;
}
|
70,615,937 | 70,616,088 | How to run a command as root with C or C++ with no pam in linux with password authentication | TL;DR How does for example su or sudo work with no PAM?
Hello,
I want to play around with suid and stuff,
I already got the SUID part and the SUID bit
and stuff, but the problem is that it's not asking me for
a password and as I want it to ask a password
and find su and sudo quite mangled in source
I am very confused.
I looked into setsuid() and getuid() documentation
and it doesn't seem like there is anything about
password authentication.
How would one achieve password authentication
with no PAM, I use sudo with no pam
and it works fine, su with pam, both work
fine, I am confused how I'd make it work
This C++ code is what I have right now:
// a.cc //
#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
int main(int argc, char *argv[]) {
uid_t user = getuid();
if (setuid(0) == -1) {
std::cerr << strerror(errno) << '\n';
return 1;
}
system(argv[1]);
if (setuid(user) == -1) {
std::cerr << errno << '\n';
return 1;
}
return 0;
}
and after compiling it with for example GCC and the file being named a.cc:
$ g++ a.cc -o a
and giving it execute and SUID permissions and giving the
ownership to root
$ sudo chown root:root ./a
$ sudo chmod 4555 ./a
it just works, but without password authentication
$ ./a id
uid=0(root) gid=1000(ari) groups=1000(ari),5(tty),10(wheel),27(video),78(kvm),250(portage)
(ari is my user)
Even after logging out or running sudo -k to
end sudo timeout it still works with no password
authentication.
Su souce: https://github.com/shadow-maint/shadow/blob/master/src/su.c
Sudo source: https://github.com/sudo-project/sudo/blob/main/src/sudo.c
Thanks for answers in advance
| First, the basics: each process has a userid and a groupid (I am going to ignore supplemental attributes like additional groupids).
Userid 0 is root. That's it, end of story.
When you have a process whose userid is 0, it's a root process. End of story.
How a process acquires its userid 0 is immaterial. If a process's userid is 0, it is a root process, and that's it.
When you go through the motions of setting up a setuid process, that setuid(0)s itself, you're done. You're a root process. That's it. There's nothing more to say about it.
setsuid() and getuid() documentation and it doesn't seem like there is
anything about password authentication.
Correct. All they do is adjust/update the userid. That's it. There's nothing more to it.
The su and sudo processes do the following:
They are setuid executables.
$ ls -al /bin/su /bin/sudo
-rwsr-xr-x. 1 root root 57504 Aug 17 04:59 /bin/su
---s--x--x. 1 root root 185440 Aug 7 13:17 /bin/sudo
Does this look familiar to you? Your hand-made setuid program's permissions looks identical to this, doesn't it?
But before they go any further, they demand that you provide an acceptable password (or meet some other criteria, in some form or fashion, it is immaterial what the exact details of acceptable authentication criteria is, a password in su's case, or an acceptable match in sudo's configuration). If you don't they terminate with no further action taking place.
All the password validation logic, involving PAM or some other authentication framework, is implemented by the su and sudo processes themselves. Unless you provide acceptable authentication credentials (whatever it means for su or sudo) they terminate with no further action taking place. A successful authentication results in a shell, or an executed command, but that's for the very simple, elementary reason that the su and sudo programs themselves used setuid (the permission bit and the system call) to acquire root privileges, as the first order of business.
|
70,615,977 | 70,666,261 | QThread run function with unknown number of arguments and types | I'm tyring to write a QThread function.
And in run function there is a function m_pFunc in the while loop.The m_pFunc is a function pointer with unknown number of arguments annd types.
How to achieve this function pointer?
void func1(int){ cout<<"func1"<<endl; }
void func2(int,char){ cout<<"func2"<<endl; }
class CThread: public QThread
{
Q_OBJECT
Q_DISABLE_COPY(CThread)
public:
using PFunc = void (*)(...); //how to achieve it?
CThread() = default;
~CThread() = default;
CThread(const PFunc pFunc) :
m_bRunning(false),
m_pFunc(pFunc){
};
protected:
void run()
{
m_bRunning = true;
while (m_bRunning) {
m_pFunc(...); //how to run this function pointer?
}
}
private:
std::atomic_bool m_bRunning;
PFunc m_pFunc;
};
CThread ct1(func1);
CThread ct2(func2);
ct1.run();
ct1.run();
expected result:
func1
func2
| class CThread: public QThread
{
Q_OBJECT
Q_DISABLE_COPY(CThread)
public:
using PFunc = std::function<void()>; //use std::function
CThread() = default;
~CThread() = default;
template<class F> //template here
CThread(F&& pFunc) :
m_bRunning(false),
m_pFunc(std::forward<F>(pFunc)){
};
protected:
void run()
{
m_bRunning = true;
while (m_bRunning) {
m_pFunc(); //call m_pFunc();
}
}
private:
std::atomic_bool m_bRunning;
PFunc m_pFunc;
};
CThread ct1(std::bind(func1,1));
CThread ct2(std::bind(func2,2,'a'));
ct1.run();
ct2.run();
|
70,616,526 | 70,616,986 | most efficient way to find all the anagrams of each word in a list | I have been trying to create a program that can find all the anagrams(in the list) for each word in the text file (which contain about ~370k words seperated by '\n').
I've already written the code in python. And it took me about an hour to run. And was just wondering if there is a more efficient way of doing it.
My code
from tqdm.auto import tqdm
ls = open("words.txt","r").readlines()
ls = [i[:-1] for i in ls]
ls = [[i,''.join(sorted(i))] for i in ls]
ln = set([len(i[1]) for i in tqdm(ls)])
df = {}
for l in tqdm(ln):
df[l] = [i for i in ls if len(i[0]) == l]
full = {}
for m in tqdm(ls):
if full.get(m[0]) == None:
temp = []
for i in df[len(m[0])]:
if i[1] == m[1] and i[0] != m[0]:
temp.append(i[0])
for i in temp:
full[i] = temp
if there are more efficient ways of writing this in other languages (Rust, C, C++, Java ...) It would be really helpful if you can also post that :)
| Using the word sorted alphabetically by character as a search key is the direction to go. And maybe you are already doing this (I hardly ever use python) with this line in your code :
[[i,''.join(sorted(i))] for i in ls]
Anyway this is my c++ take on your problem.
Live demo here : https://onlinegdb.com/_gauHBd_3
#include <algorithm> // for sorting
#include <string>
#include <unordered_map> // for storing words/anagrams
#include <iostream>
#include <fstream>
#include <set>
// create a class that will hold all words
class dictionary_t
{
public:
// load a text file with one word per line
void load(const std::string& filename)
{
std::ifstream file{ filename };
std::string word;
while (file >> word)
{
add_anagram(word);
}
}
auto& find_anagrams(const std::string& word)
{
const auto key = get_key(word);
// intentionally allow an empty entry to be made if word has no anagrams yet
// for readability easier error handling (not for space/time efficiency)
auto& anagrams = m_anagrams[key];
return anagrams;
}
// show all anagrams for a word
void show_anagrams(const std::string& word)
{
std::cout << "anagrams for word '" << word << "' are : ";
auto anagrams = find_anagrams(word);
for (const auto& anagram : anagrams)
{
if (anagram != word)
{
std::cout << anagram << " ";
}
}
std::cout << "\n";
}
private:
// this function is key to the whole idea
// two words are anagrams if they sort their letters
// to the same order. e.g. beast and betas both sort (alphabetically) to abest
std::string get_key(const std::string& word)
{
std::string key{ word };
// all anagrams sort to the same order of characters.
std::sort(key.begin(), key.end());
return key;
}
void add_anagram(const std::string& word)
{
// find the vector of anagrams for this word
auto& anagrams = find_anagrams(word);
// then add word to it (I use a set so all words will be unique even
// if input file contains duplicates)
anagrams.insert(word);
}
std::unordered_map<std::string, std::set<std::string>> m_anagrams;
};
int main()
{
dictionary_t dictionary;
dictionary.load("words.txt");
dictionary.show_anagrams("beast");
dictionary.show_anagrams("tacos");
return 0;
}
|
70,616,742 | 70,618,465 | Can atomic_thread_fence(acquire) prevent previous loads being reordered after itself? | I understand atomic_thread_fence in C++ is quite different with atomic store/loads, and it is not a good practice to understand them by trying to interpret them into CPU(maybe x86)'s mfence/lfence/sfence.
If I use c.load(memory_order_acquire), no stores/loads after c.load can be reordered before c.load. However, I think there are no restriction to stores/loads before c.load. I mean some stores/loads before c.load can be reordered after it theoretically.
However when it comes to atomic_thread_fence(memory_order_acquire), it involves 3 kinds of objects: the fence, store/loads before this fence and store/loads after this fence.
I think the fence will certainly prevent store/loads after this fence being reordered before itself, just like atomic store/load. But will it prevent store/loads before this fence being reordered after itself?
I think the answer is yes with the following searching:
In preshing's article
An acquire fence prevents the memory reordering of any read which precedes it in program order with any read or write which follows it in program order.
So he does not specify a direction.
In modernescpp
there is an additional guarantee with the acquire memory barrier. No read operation can be moved after the acquire memory barrier.
So I think he say yes directly?
However, I find no "official" answer in cppreference, it only specifies how fences and atomics interact with each other in different threads.
but I am not sure, so I have this question.
| After reading your question more carefully, looks like your modernescpp link is making the same mistake that Preshing debunked in https://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/ - fences are 2-way barriers, otherwise they'd be useless.
A relaxed load followed by an acquire fence is at least as strong as an acquire load. Anything in this thread after the acquire fence happens after the load, thus it can synchronize-with a release store (or a release fence + relaxed store) in another thread.
But will it prevent store/loads before this fence being reordered after itself?
Stores no, it's only an acquire fence.
Loads, yes. In terms of a memory model where there is coherent shared cache/memory, and we're limiting local reordering of access to that, an acquire fence blocks LoadLoad and LoadStore reordering. https://preshing.com/20130922/acquire-and-release-fences/
(This is not the way ISO C++'s formalism defines things. It works in terms of happens-before rules that order things relative to a load that saw a value from a store. In those terms, a relaxed load followed by an acquire fence can create a happens-before relationship with a release-sequence, so later code in this thread sees everything that happened before the store in the other thread.)
|
70,617,006 | 70,618,335 | How to rotate an object around a point with GLM OpenGL C++? | I'm trying to do something like this, but for some reason my cube still rotates around the origin. What am I doing wrong?
glm::mat4 identity = glm::mat4(1.0f); // construct identity matrix
glm::mat4 trans;
glm::mat4 rot;
glm::mat4 transBack;
glm::mat4 M;
glm::vec4 br = glm::vec4(currentPositionX - 0.4, 0.0f, currentPositionZ + 1.2, 1.0f);
//get the matrix transformation to translate
trans = glm::translate(identity, glm::vec3(+0.4, 0.0f, -1.2));
identity = glm::mat4(1.0f); // construct identity matrix
//get the matrix transformation to rotate
rot = glm::rotate(identity, glm::radians(rotation), glm::vec3(0.0, 1.0, 0.0)); // rotate with car ROT -
identity = glm::mat4(1.0f); // construct identity matrix
//get the matrix transformation to translate
transBack = glm::translate(identity, glm::vec3(-0.4, 0.0f, +1.2));
M = transBack * rot * trans;
// A' = M . A , A being a point
br = M * br;
| Formula to rotate a point around (x,y,z) is:
T(x,y,z) * R * T(-x,-y,-z) // operations are combined from right to left
you have to move the point P(x,y,z) to center of locale coordinate system, apply rotate
and translate back to world space.
auto rotAroundPoint(float rad, const glm::vec3& point, const glm::vec3& axis)
{
auto t1 = glm::translate(glm::mat4(1),-point);
auto r = glm::rotate(glm::mat4(1),rad,axis);
auto t2 = glm::translate(glm::mat4(1),point);
return t2 * r * t1;
}
int main() {
glm::vec4 geom(0,0,0,1); // one point of cube geometry
glm::vec3 o(6,0,6); // origin of rotation
glm::vec3 cp(5,0,5); // current position of cube
for (float deg : {0.f,90.f,180.f,270.f}) {
auto res = rotAroundPoint(glm::radians(deg),o,glm::vec3(0,1,0)) *
glm::translate(glm::mat4(1),cp) * geom;
std::cout << glm::to_string(res) << std::endl;
}
/*
------------------> x
|
|
| cp(5,5) (7,5)
| o(6,6)
| (5,7) (7,7)
|
z
*/
godbolt demo
|
70,617,062 | 70,617,327 | C++ output depends on global variable initialization | This Code is solution of n-queen problem.
Solving the problem I found that the output changes depends on global variable ans initialization.
If ans initialized before grid and input value is 8, the output value is 28.
If ans initialized after grid and input value is 8, the output value is 92.
I guess its memory problem but I'm not sure exactly.
Why does the output value change depending on the position of the Initialization statement?
#include <cstdio>
using namespace std;
int ans = 0;
bool grid[14][14] = { false, };
int N;
bool isValid(int i, int cnt) {
int x, y;
for (x = 0; x < cnt; x++) {
if (grid[i][x]) return false;
}
for (x = cnt - 1, y = i - 1; y >= 0; x--, y--) {
if (grid[y][x]) return false;
}
for (x = cnt - 1, y = i + 1; y < N; x--, y++) {
if (grid[y][x]) return false;
}
return true;
}
void dfs(int cnt) {
int i;
// basecase
if (cnt == N) {
ans++;
return;
}
for (i = 0; i < N; i++) {
if (!grid[i][cnt] && isValid(i, cnt)) {
// constraint satisfied
grid[i][cnt] = true;
dfs(cnt + 1);
grid[i][cnt] = false;
}
}
}
int main() {
scanf("%d", &N);
dfs(0);
printf("%d ", ans);
return 0;
}
| Your program has undefined behavior. This is because at some points inside the isValid function you're using negative indices while accessing array grid's elements. You can verify this by printing the value of x(which you then use in grid[i][x]) and notice that there are some negative values. This will result in undefined behavior.
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.
So the output that you're seeing is a result of undefined behavior. And as i said don't rely on the output of a program that has UB.
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.
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.
|
70,617,252 | 70,617,416 | what is empty function size? | integer is 4 byte
double is 8 byte
What is the size of an empty function?
void test(){} //-> size????
void test1(){ int a, int b, double c } //-> size????
void test2(){ test() } -> size??????
When I run the program, the result is the same
void test(){}
void test1() {int a}
void main()
{
cout<<sizeof(&test) <<endl;
cout<<sizeof(&test1) <<endl;
}
please solve my questions
| ISO C++ does not have a notion of the size of a function.
How the compiler creates the machine-level instructions for the individual functions and merges them into an entire program is not specified by the ISO standard. Every individual platform can do this its own way. Therefore, it would not make sense for the ISO standard to attempt to define what the size of a function is.
As a consequence, you cannot use the sizeof operator to determine the size of a function.
When you write the expression &test, you get a pointer that points to the function test. On 32-bit platforms, pointers are usually 32 bits (i.e. 4 bytes), and on 64-bit platforms, they are usually 64 bits (i.e. 8 bytes).
That is why the expressions
sizeof(&test)
and
sizeof(&test1)
will both evaluate to either 4 or 8, depending on your platform.
Depending on how code is generated on your platform, you may be able to find a meaningful definition of the size of a function, and find the size of a function in a platform-specific manner. However, most platforms perform compiler optimizations which allow functions to be, for example, inlined, so that they may not even exist as a separate entity. In such a case, it is probably hard to find a meaningful definition of the size of a function.
|
70,617,385 | 70,657,632 | ZMQCPP using socket_t as class variable | I'm creating a class to handle ZMQCPP that I can use within several different projects. I want to have the context_t and socket_t be a class variable so I do not have to pass them around to different functions as parameters (what I currently do). But I keep getting errors and am unsure if this is even possible.
I've looked through the zmq.hpp file and not seeing a "Default" null constructor for socket_t class without needing a context and socket type off the bat.
Any input or guidance would be appreciated.
Here is my current class setup
#include "zmq_addon.hpp"
#include <zmq.h>
#define DEFAULT_IP "tcp://127.0.0.1:"
#define DEFAULT_PORT 5555
class zmqClientTCP {
public:
zmqClientTCP(); // Default Constructor
~zmqClientTCP(); // Deconstructor
int setAddress(std::string); // Changes the IP Address.
int setPortNumber(int); // Change port number explicitly
int setSocketType(int); // Change the socket type
int connect(); // Connects
void disconnect(); // Disconnects from active connection
void sendMessage(std::string*); // Send Message over connection.
private:
std::string ipAddress = ""; // Holds the IP Address
int portNum = -1; // Holds port number
int sockType = ZMQ_SUB; // Set socket type for ZMQ connection
const zmq::context_t context; // ZMQ Context for single thread
zmq::socket_t socket; // ZMQ Socket
bool isConnected = false; // Bool for connection.
};
Class implementation: (what I would like to do)
int zmqClientTCP::connect() {
socket(context, sockType);
socket.connect(ipAddress);
// MONITOR IMPLEMENTATION HERE
if(isConnected)return 1;
return 0
}
void sendMessage(std::string msg){
zmq::message_t zOut(msg);
socket.send(zOut, zmq::send_flags::none);
}
void zmqClientTCP::disconnect() {
socket.disconnect(ipAddress);
}
Class Implementation (What I currently do):
int zmqClientTCP::connect() {
zmq::context_t context;
zmq::socket_t socket(context, sockType);
socket.connect(ipAddress);
std::string temp
/* MONITOR IS HERE TO TRIGGER isConnected BOOL */
while(isConnected){
temp.clear();
std::getline(std::cin, temp);
sendMessage(socket, temp);
}
disconnect(socket);
return 1;
}
void sendMessage(zmq::socket_t &socket, std::string msg){
zmq::message_t zOut(msg);
socket.send(zOut, zmq::send_flags::none);
}
void zmqClientTCP::disconnect(zmq::socket_t &socket) {
socket.disconnect(ipAddress);
}
| For anyone that comes across this; I was able to achieve my desire by using ZMQ C++ API functionality. You'll need the "zmq_addons.hpp".
class zmqClientTCP {
public:
zmqClientTCP(); // Default Constructor
~zmqClientTCP(); // Deconstructor
void connect(); // Connects to address
void disconnect(); // Disconnects from active connection
void sendMessage(const std::string*);// Send string over connection.
void sendMessage(const char*); // Send c style string over connection.
void recvMessage(std::string*); // Recv message over connection.
private:
void* context; // ZMQ Context for single thread
void* socket; // ZMQ Socket
char buffer[256]; // Buffer for message receiving
};
Here is the basic functionality to accompany the class.
void zmqClientTCP::connect() {
context = zmq_ctx_new();
socket = zmq_socket(context, ZMQ_REQ);
zmq_connect(socket, ipAddress+PortNum);
}
void zmqClientTCP::sendMessage(const std::string* msg) {
zmq_send(socket, _strdup(msg->c_str()), strlen(msg->c_str()), 0);
}
void zmqClientTCP::sendMessage(const char* msg) {
zmq_send(socket, _strdup(msg), strlen(msg), 0);
}
void zmqClientTCP::recvMessage(std::string* msg) {
// Clear buffer
memset(buffer, '\0', sizeof(buffer));
// Recv message from zmq into the buffer
zmq_recv(socket, buffer, sizeof(buffer), 0);
// Convert buffer to string
std::string temp(buffer);
// Assign temp string to inbound string parameter.
msg->assign(temp);
}
void zmqClientTCP::disconnect() {
zmq_close(socket);
zmq_term(context);
}
Then you can just write easy class implementation like so:
zmqClientTCP zmqClient;
zmqClient.connect();
std::string msgOut = "Hello World";
zmqClient.sendMessage(&msgOut);
std::string msgIn = "";
zmqClient.recvMessage(&msgIn);
zmqClient.disconnect();
|
70,617,969 | 70,624,418 | ZLIB with small memory usage | I'm working on embedded device (STM32) with < 5kb free FLASH memory left. I'm trying to compress string with zlib library.
I created function HERE and it returns -2 (Z_STREAM_ERROR).
What I did:
On zconf.h, I changed value of MAX_MEM_LEVEL to 1 and MAX_WBITS to 5 to lower memory usage. But i still returns -2 (Z_STREAM_ERROR).
Then I found this On deflate.c which I cannot lower MAX_WBITS less than 8:
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
return Z_STREAM_ERROR;
}
if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
Then I set it to MAX_MEM_LEVEL to 1 and MAX_WBITS to 8 but when I try to compile it always returns region FLASH overflowed by 15960 bytes. Looks like I run out of memory.
Then I tried another example:
Follow with zpipe.c sample with defined CHUNK to 1024.
Result still the same, region FLASH overflowed by 15960 bytes.
Is there any other way to do it with FLASH memory only 5kb left?
Note:
RAM is also 5kb left.
| No. The minimum amount of RAM required by deflate is 9K. You might try a different compressor, such as lz4.
The deflate code itself compiles to 33K on my machine (x86_64 ISA), with speed optimization. I tried compiling with aggressive space optimization, which got it down to 25K.
|
70,618,320 | 70,618,435 | The constructor of base class is not called by derived class when base class pointer is used | Why the base class constructor is not called twice in the following code?
#include<iostream>
using namespace std;
class base{
public:
base(){cout << "In the Base Constructor\n"; }
~base(){
cout << "In Base Destructor\n";
}
};
class derived: public base{
public:
derived(){cout << "In Derived Constructor\n";}
~derived(){
cout << "In Derived Destructor\n";
}
};
int main(){
base *bptr;
derived d;
}
output:
In the Base Constructor
In Derived Constructor
In Derived Destructor
In Base Destructor
It must be because of the pointer. But I am not clear why?
| This is a pointer to something.
base *bptr;
It is not initialised.
It does not point to anything clean.
It especially does not point to any already created object.
Even if it did, that would not cause any constructor to be executed.
If there would be any object the pointer points to, then the creation of that object would have happened elsewhere, earlier.
This defines an object:
derived d;
This is what causes the observed execution of constructors.
|
70,618,341 | 70,623,469 | how to create templated-like namespace for member functions | I am curretntly trying to define a namespace/struct which contain function pointers which store a specific implementations (let's say a structure to contain several functions). For now everything works fine with the following structure:
class foo{
int a;
int b;
public:
explicit foo(int _a, int _b) : a(_a), b(_b) {};
std::function<int(int)> bar(int num) = [=](int num) -> int{
// here I need to know a and b
//do something with num and return
}
}
This class contains several functions where each has to know a and b. The problem is that I have to create and instance of the class and set the parameters a and b, which I would rather omit.
In another class I use this class only by taking its functions. Namely
class foo2{
//some other parameters
int a, b;
std::function<...> fun1, fun2,...;
public:
foo2(int a, int b, ....){this->a = a; this->b = b;};
setFuncs(){
foo instance(a, b);
this->fun1 = [instance](int num){ return instance.bar(num);}
this->fun2 = ...
}
}
but i want to omit creating a new class inctance each time (in the sense that I repeat the above behavior in the same class but another place in the code). I tried to template this class as
template<int a, int b>
class foo{
...
}
so i could assign the funtions as:
this->fun1 = foo<a,b>::bar;
But then I would need to know a and b at compile time, which is not possible. Those parameters are set once in class foo2. I realise the overall code may not be clean, I'm a physicist, not IT guy, as you can see. One way would be to store an instance of class foo in class foo2 and initialize it once for the whole class and let the functions fun1, fun2,... have access by reference to those pointers, but I 'm looking if there is another way (maybe a template like class, where I don't need to know the values at compile time).
Also I can't paste the whole code here as it contains thousands of lines in several files and describing what the code does is very hard. I appreciate any help and apologize if this may be a stupid or trivial question (i don't work in IT strictly, I'm a physicist ;) )
| Since you want some input data to stay longer than a single function call, unless it's fully compile-time data a runtime state is inevitable. The question is how you want this data to be encapsulated - different approaches will yield very different (subjective) feelings of how convenient they are.
Based on your usage example:
this->fun1 = foo<a,b>::bar;
If you want to avoid state (or rather encapsulate it) you can create a factory that will create functions for you:
std::function<int(int)> make_func(int a, int b)
{
return [=](int x){ return actual_function(a, b, x); };
}
this->fun1 = make_func(a, b); // now std::function will hold lambda's captured state
This topic is generally known as partial application and I guess boost or other libraries already have a lot of supporting code for such manipulations.
|
70,618,350 | 70,618,565 | What exactly empty input means for cin.get()? | I think it's a simple question, but I don't understand the concept in this sample of code, mainly in the while loop:
#include <iostream>
const int ArSize = 10;
void strcount(const char * str);
int main(){
using namespace std;
char input[ArSize];
char next;
cout << "Enter text:\n";
cin.get(input, ArSize);
while(cin){
cin.get(next);
while(next != '\n')
cin.get(next)
strcount(input);
cout << "Enter next line, empty line ends the program:\n";
cin.get(input, ArSize);
}
cout << "The end\n";
return 0;
}
...
What I understand is that the while loop continues until cin returns false. It filters out the remaining input that's left in the buffer (because it wasn't the size of ArSize or under, or it was - then it will just filter out the newline character) until it meets the newline character. Then it counts string's characters (not important in this question), and then, let's say someone just presses enter. cin.get() discards newline character in input. So if someone for example enters an empty line of text in the terminal, it reads it as 'failed' input and cin returns false? Because if someone proceeds to the new line, just by pressing enter, it just leaves the newline character in the buffer, and cin.get() can't get it so it returns false. Or am I wrong?
In short - What exactly happens if you just press enter? cin.get() can't get the input because there's only newline in buffer and it counts it as failed input, so it returns false?
| If cin.get(input, ArSize); reads no characters (i.e. the first character it encounters is a newline) it calls setstate(failbit) putting the stream into a failed state and therefore while(cin) becomes false, ending the loop.
|
70,618,884 | 70,619,703 | Unable to pass `pyarrow` table to `arrow::Table` | I'm trying to pass a pyarrow table to c++ via pybind11. In this example I'm simply trying to print the number of rows of a pyarrow table passed from python.
#include <pybind11/pybind11.h>
#include <Python.h>
#include <iostream>
#include <arrow/python/pyarrow.h>
// Convert pyarrow table to native C++ object and print its contents
void print_table(PyObject* py_table)
{
// convert pyobject to table
auto status = arrow::py::unwrap_table(py_table);
if (!status.ok())
{
std::cout << "Error converting pyarrow table to arrow table" << std::endl;
return;
}
std::shared_ptr<arrow::Table> table = status.ValueOrDie();
std::cout << "Table has " << table->num_rows() << " rows" << std::endl;
}
PYBIND11_MODULE(df_test, m)
{
arrow::py::import_pyarrow();
m.doc() = "Pyarrow Extensions";
m.def("print_table", &print_table);
}
However I get the following error:
error: member access into incomplete type 'std::shared_ptr<arrow::Table>::element_type' (aka 'arrow::Table')
std::cout << "Table has " << table->num_rows() << " rows" << std::endl;
How do I fix this error?
| The error tells you that the c++ class arrow::Table is missing its full definition. That is often the case if the class is only declared in some header but not defined.
To fix the error, you probably need to add an #include statement.
The definition might be in the header "arrow/table.h" as suggested in the comments, but I am not familiar with the Apache arrow framework so you may have to checkout the documentation.
|
70,618,889 | 70,622,162 | How to create a program that can overwrite a pre-initialized variable with user inputted data during runtime? | I was tasked to create an ATM mock program and my problem is overwriting the money and PIN variables with the information that the user will enter.
Here it is:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
void ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
PIN = p;
cout << "Your new PIN is: " << PIN << endl;
}
int main() {
int money = 5000, PIN = 1234, EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
break;
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
ChangePIN(PIN);
break;
}
}
}
return 0;
}
}
As you can see I'm pretty much a beginner at this. My problem is the money and PIN have the default values of 5000 and 1234 respectively. Now, I need to make the user be able to change these values but once I use return main() they get assigned the same starting values again, What would be the best workaround for this? I thought of using some sort of accumulator for this but I'd like some advice first.
| You can simply do this by using a while loop.
Run an infinite while loop and break it whenever you want to exit from the program.
Here is the code:
#include <iostream>
using namespace std;
void Check(int money) { cout << "Your current balance is: " << money << endl; }
void Deposit(int money) {
int deposit;
cout << "Please enter the amount of cash you wish to deposit.\n";
cin >> deposit;
money += deposit;
cout << "Your new balance is: " << money << endl;
}
void Withdraw(int money) {
int withdraw;
cout << "Please enter the amount of cash you wish to withdraw.\n";
cin >> withdraw;
money -= withdraw;
cout << "Your new balance is: " << money << endl;
}
void Interest(int money) {
money += money * 0.05;
cout << "Your money with interest is: " << money << endl;
}
void Penalty(int money) {
if (money < 5000) {
money -= money * 0.02;
cout << "Your penalty is: " << money << endl;
} else
cout << "Your account will not incur a penalty because you are above the "
"minimum threshold.\n";
}
int ChangePIN(int PIN) {
int p;
cout << "Enter a new PIN: ";
cin >> p;
cout << "Your new PIN is: " << PIN << endl;
return p;
}
int main() {
int money = 5000, PIN = 1234;
while(1){ // run an infinite loop
int EPIN;
cout << "Enter your PIN (Default PIN is 1234): \n";
cin >> EPIN;
if (EPIN == PIN) {
int choice;
cout << "Welcome!\n"
<< "1 - Check available balance \n"
<< "2 - Deposit cash \n"
<< "3 - Withdraw cash \n"
<< "4 - Compute for the interest of your account(5%)\n"
<< "5 - Compute for the penalty of having a balance below 5000 (2%) \n"
<< "6 - Change your PIN\n"
<< "7 - Exit\n"
<< "Your choice: ";
cin >> choice;
switch (choice) {
case 7: {
return 0; // breaking condition
}
{
case 1: {
Check(money);
break;
}
case 2: {
Deposit(money);
break;
}
case 3: {
Withdraw(money);
break;
}
case 4: {
Interest(money);
break;
}
case 5: {
Penalty(money);
break;
}
case 6: {
PIN = ChangePIN(PIN);
break;
}
}
}
}
}
return 0;
}
Does this answer your question?
|
70,619,355 | 70,623,205 | how to utilize cudaMemcpy and cudaMalloc? | I'learning CUDA programming. To figure out what is copy unit of cudaMemcpy() and transport unit of cudaMalloc(), I wrote the below code, which adds two vectors,vector1 and vector2, and stores result into vector3. However, after compilation and execution, the result in vector3 was not as expected. I'm not pretty sure what is the problem. But, presumably, the functions, cudaMalloc and cudaMemcpy, might be used wrongly. Does anyone know where exactly the problem is?
#include<iostream>
using namespace std;
__global__ void vector_mul(int *const c_vector,const int *const a_vector,const int *const b_vector){
const unsigned int idx=blockIdx.x*blockDim.x+threadIdx.x;
const unsigned int idy=blockIdx.y*blockDim.y+threadIdx.y;
const unsigned int thid=(idy*blockDim.x*gridDim.x)+idx;
c_vector[thid]=a_vector[thid]+b_vector[thid];
}
int vec1[64];
int vec2[64];
int vec3[64];
int main(void){
const dim3 thread_layout(4,4);
const dim3 block_layout(2,2);
for(int i=0;i<64;i++){
vec1[i]=i;
vec2[i]=64-i;
}
//declare gpu pointer
int *gpu_vec1;
int *gpu_vec2;
int *gpu_vec3;
//allocate gpu memory to gpu pointer
cudaMalloc((void**)&gpu_vec1,64);
cudaMalloc((void**)&gpu_vec2,64);
cudaMalloc((void**)&gpu_vec3,64);
//copy data from host to device
cudaMemcpy(gpu_vec1,vec1,64,cudaMemcpyHostToDevice);
cudaMemcpy(gpu_vec2,vec2,64,cudaMemcpyHostToDevice);
vector_mul<<<block_layout,thread_layout>>>(gpu_vec3,gpu_vec1,gpu_vec2);
cudaMemcpy(vec3,gpu_vec3,64,cudaMemcpyDeviceToHost);
for(int i=0;i<64;i++)
cout << vec3[i] <<endl;
cudaFree(gpu_vec1);
cudaFree(gpu_vec2);
cudaFree(gpu_vec3);
return 0;
} 1,1 Top
| For an array that is intended to hold 64 int elements:
int vec1[64];
...
for(int i=0;i<64;i++){
vec1[i]=i;
These are not correct:
cudaMalloc((void**)&gpu_vec1,64);
cudaMalloc((void**)&gpu_vec2,64);
cudaMalloc((void**)&gpu_vec3,64);
...
cudaMemcpy(gpu_vec1,vec1,64,cudaMemcpyHostToDevice);
cudaMemcpy(gpu_vec2,vec2,64,cudaMemcpyHostToDevice);
...
cudaMemcpy(vec3,gpu_vec3,64,cudaMemcpyDeviceToHost);
All of the size parameters for those operatiosn are intended to be the size in bytes. So instead of 64, in each place it should be sizeof(int)*64.
There is a CUDA sample application called vectorAdd where you can see an example of this.
|
70,619,527 | 70,620,594 | GTKMM - Error drawing image for some widths | I'm trying to draw on a window with Gtkmm for C++, cairo::context, gdk::pixbuf. I've noticed that for some widths (in my example 298), instead of my image, I get some horizontal black lines (alternated with white stripes).
For other widths (in my example 300) I get a normal image. (I'm just drawing a yellow background in my example).
What am I doing wrong ? How can I obtain to draw correctly for any image width ?
I'm finding this behavior both on :
windows 10 / msys2 / gcc11.2 / std=c++20
opensuse 15.2 / gcc 11.2.1 / std=c++17
and on both I have library versions:
-I/usr/include/gtkmm-3.0 -L/usr/lib64 -I/usr/lib64/glibmm-2.4/include -I/usr/include/glibmm-2.4 -I/usr/lib64/glib-2.0/include -I/usr/include/glib-2.0 -I/usr/include/sigc++-2.0/ -I/usr/lib64/sigc++-2.0/include -I/usr/include/giomm-2.4 -I/usr/lib64/giomm-2.4/include -I/usr/include/gdkmm-3.0 -I/usr/lib64/gdkmm-3.0/include -I/usr/lib64/pangomm-1.4/include -I/usr/include/gtk-3.0/ -I/usr/include/pango-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/cairomm-1.0 -I/usr/include/cairomm-1.0/cairomm -I/usr/lib64/cairomm-1.0/include -I/usr/include/freetype2 -I/usr/lib64/gtkmm-3.0/include -I/usr/include/pangomm-1.4 -I/usr/include/harfbuzz -I/usr/include/atkmm-1.6 -I/usr/include/atk-1.0 -I/usr/lib64/atkmm-1.6/include -LC:/programs/msys64/mingw64/bin -lgtkmm-3.0 -lglibmm-2.4 -I/usr/include/sigc++-2.0 -lsigc-2.0 -lgdkmm-3.0 -latkmm-1.6 -lcairomm-1.0
Here's my code:
#include <gtkmm/application.h>
#include <gtkmm/fixed.h>
#include <gdkmm/pixbuf.h>
#include <gtkmm/window.h>
#include <cairomm/context.h>
#include <giomm/resource.h>
#include <gdkmm/general.h>
#include <iostream>
class TesterWindow : public Gtk::Window
{
public:
TesterWindow()
{
int width = 298; // lines
// int width = 300; // yellow
int height = 300;
set_size_request(width, height);
try
{
m_image = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, false, 8, width, height);
auto pixels = m_image->get_pixels();
int channels = 3;
for(int i = 0; i < width * height * channels; ++i)
{
switch(i % 3)
{
case 0 : pixels[i] = 255; break;
case 1 : pixels[i] = 255; break;
case 2 : pixels[i] = 0; break;
default : break;
}
}
}
catch(const Gio::ResourceError& ex)
{
std::cout << "ResourceError: " << ex.what() << std::endl;
}
catch(const Gdk::PixbufError& ex)
{
std::cout << "PixbufError: " << ex.what() << std::endl;
}
}
void show()
{
set_position(Gtk::WIN_POS_CENTER);
show_all_children();
}
bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
if(!m_image) return false;
Gdk::Cairo::set_source_pixbuf(cr, m_image, 0, 0);
cr->paint();
return true;
}
private:
Glib::RefPtr<Gdk::Pixbuf> m_image;
};
int main(int argc, char** argv)
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
TesterWindow window;
window.show();
return app->run(window);
}
| I'm used to the fact that image rows are often (not always) stored with a certain alignment. Whenever I see an image that appears erroneously in stripes, the row alignment is the first thing I would check.
With this suspicion in mind, I look for some gdkmm (or Gdk) doc. Instead I found a comment in the Gdk source code.
GitHub: gdk-pixbuf.c:
channels = has_alpha ? 4 : 3;
rowstride = width * channels;
if (rowstride / channels != width || rowstride + 3 < 0) /* overflow */
return NULL;
/* Always align rows to 32-bit boundaries */
rowstride = (rowstride + 3) & ~3;
bytes = height * rowstride;
The function Gdk::Pixbuf::get_rowstride() can be used to retrieve the number of bytes between two consecutive rows in the image buffer.
A fix of OP's code could look like:
auto pixels = m_image->get_pixels();
const int rowstride = m_image->get_rowstride();
const int channels = 3;
for (int y = 0; y < height; ++y) {
auto rowpixels = pixels + y * rowstride;
for (int x = 0; x < width * channels; x += channels) {
rowpixels[x + 0] = 255;
rowpixels[x + 1] = 255;
rowpixels[x + 2] = 0;
}
}
Notes:
I transformed the inner loop a bit. (I consider branch-less inner loop bodies as performance friendlier.)
I didn't compile nor debug my code. Please, take it with a grain of salt.
|
70,620,090 | 70,620,184 | Visual Studio: what is the difference between 'Build Solution' and 'Rebuild Solution' when i do not use precompiled headers | I try to understand what is the difference between the 2 built types in visual studio (Build vs Rebuild Solution). As i know when i use precompiled headers the simple built will not complile the precompiled headers as long the code in these files remain the same, but 'rebuilt' will compile them always.
So what happend when i don't use precompiled headers?
I notice that simple built is still faster than rebuilt, what exactly does to reduce the compling time (c++)?
| Using Build will typcally only rebuild the files that needs to be rebuilt because of changes you've made to the code.
If you create two files in your project/solution, a.cpp and b.cpp, and then Build the first time, both will be compiled (into a.obj and b.obj) and then linked into an .exe file.
If you then make changes to a.cpp only and select Build again, only a.cpp would be compiled (into a a.obj) and that a.obj and the already existing b.obj would be linked into an .exe file.
If you instead select Rebuild, b.cpp would also be recompiled before linking, even though you didn't make any changes to b.cpp.
|
70,620,650 | 70,621,028 | C++ Member and vtable order in diamond (multiple) virtual inheritance | I wanted to know the ordering of member variables and vtable pointers in C++ on a diamond virtual inheritance.
Consider the below inheritance:
class Base
{
int b;
};
class Derived: public virtual Base
{
int d;
};
class Derived2: public virtual Base
{
int d2;
};
class Derived3: public Derived, public Derived2
{
int d3;
};
I wanted to know the memory layout of class Derived3.
I looked at following links online:
c++ data alignment /member order & inheritance
C++ Inheritance Memory Model
After going through the above links this is what I feel the memory layout of Derived3 could be:
void* vtable_ptr1 //vtable pointer of Derived
int d //Derived
void* vtable_ptr2 //vtable pointer of Derived2
int d2 //Derived2
int b //Base? not sure where will this be.
int d3 //Derived3
Online compilers give the size of Derived3 as 40 bytes, so I feel (assuming 8 bytes for pointer and 4 bytes for int) int b has to come after vtable_ptr2 (8(vtable_ptr1) + 4(d) + [4 padding] + 8(vtable_ptr2) + 4(d2) + 4(b) + 4(d3) + [4 class padding]) or before vtable_ptr1 (4(b) + [4 padding] + 8(vtable_ptr1) + 4(d) + [4 padding] + 8(vtable_ptr2) + 4(d2) + 4(d3)) so that padding comes into picture and increases the size of the class to 40.
To summarize, I have the following question:
Is the ordering correct? If not, what is the correct ordering of member variables and vtable pointers?
|
what is the correct ordering of member variables and vtable pointers?
There is no "correct ordering". This is not specified in the C++ standard. Each compiler is free to arrange the memory layout of this class hierarchy in any fashion that's compliant with the C++ standard.
A compiler may choose the layout of the class, in this situation, according to some fixed set of rules. Or, a compiler may try to optimize amongst several possibilities and pick a layout that can take advantage of hardware-related factors, like preferred alignment of objects, to try to minimize any required padding. This is entirely up to the compiler.
Furthermore: if you review the text of the C++ standard you will not find even a single mention of anything called a "vtable". It's not there. This is just the most common implementation mechanism for virtual class methods and virtual inheritance. Instead of a pointer, it would be perfectly compliant with the C++ standard for a C++ compiler to use a two-byte index into a table, instead of an entire pointer -- into a table containing records that define each particular class's virtual properties. This would work perfectly fine as long as the number of all classes with virtual properties does not exceed 65536.
In other words: you have no guarantees, whatsoever, what this class's layout will be, in memory, or what its size is. It is not specified in the C++ standard and is entirely implementation-defined.
|
70,621,067 | 70,621,191 | How does std::unordered_map determine the location of a specific key in a hash table? | The documentation mentions that std::unordered_map uses a hash table. How does it achieve O(1) lookup of a specific key in the hash table? The only way I can think of is to store each key at an address computed from the hash value of the data it holds. If this is the case, how does it keep all of the keys close together in memory such that it does not get used up quickly? Furthermore, what if more than one std::unordered_map is used? How does the implementation guarantee that no two maps will ever compute hashes that boil down to the same address?
| Typically a hash map keeps an array of buckets inside. A bucket, on the other hand is a list of entries. And so something like this:
template<class TKey, class TValue>
class HashMap {
vector<vector<pair<TKey, TValue>>> Buckets;
};
Then when you do a lookup, it simply takes the key, computes its hash, say hash, goes to Buckets[hash % Buckets.size], which is of type vector<pair<TKey,TValue>> and does a linear search on it. This makes the amortized (average) lookup complexity constant, while in the worst case (e.g. bad hashing function) it is linear. And indeed, this is the guarantee you get with the unordered_map.
Note that the top level vector will eventually grow when you add elements (maybe even when you remove), in order to allow more entries and avoid collisions. Rehashing is likely to take place in such case. And so adding/removing elements is not trivial, and can be expensive from time to time.
Also note that since vector allocates memory on the heap under the hood, then there is no issue with using more than one map. They share nothing (well, they may share something, but it doesn't affect the behaviour). But even if an implementation does not use vector (which is not mandatory, its just an example), some form of dynamic malloc has to be used to guarantee that.
|
70,621,203 | 70,621,498 | ifndef with cpp file in new library | Hello im trying to build my own library in c++, and after many hours of searching and trying i learnt that a good way of doing one would be using nested classes, so i made some code in this form of tree:
file tree
So i divided all the class files into different header files(i know this is harder and maybe not necessary but i wanted have it like that, if nothing more then just for training). And so to keep the nested class connected, but in different files, each header needs to include its child and or parent to function correctly. This didnt work, gave me errors of recursive include (duh) so i searched online and found #ifndef and #define and i used them in this way:
//A.hpp
#ifndef A_HPP_INCLUDED // some unique macro
#define A_HPP_INCLUDED
class A
{
public:
class B;
class C;
};
#include "B.hpp"
#include "C.hpp"
#endif
//B.hpp
#ifndef B_HPP_INCLUDED
#define B_HPP_INCLUDED
#include "A.hpp"
class A::B
{
public:
static int num;
void func();
};
#endif
int A::B num = 5;
//C.hpp
#ifndef C_HPP_INCLUDED // some unique macro
#define C_HPP_INCLUDED
#include "A.hpp"
class A::C
{
public:
void func();
};
#endif
But the second i add #include "B.hpp" into the B.cpp file it immediately gives me error that all variables and functions ive added in this way are defined multiple times. Without cpp files it works perfectly, but with them it crashes. In fact this happens when adding any cpp file to any header
Answers to this problem are welcome, but if you have any tips on how to make library files in a better way or even just random tips, thatd be awesome!
fyi im using qt creator, qmake, c++11. if qmake file is needed ill send it but i think everything there is good.
The files in question (for reproducing the problem):
//testlibrary.hpp
#ifndef TESTLIBRARY_HPP_INCLUDED // some unique macro
#define TESTLIBRARY_HPP_INCLUDED
class TestLibrary
{
public:
class Core;
class SFML;
};
#include <Core/Core.hpp>
#include <SFML++/SFMLpp.hpp>
#endif
//Core.hpp
#pragma once
#ifndef CORE_HPP_INCLUDED // some unique macro
#define CORE_HPP_INCLUDED
#include <testlibrary.hpp>
class TestLibrary::Core
{
public:
class Constants;
};
#include "Constants.hpp"
#endif
//Constants.hpp
#pragma once
#ifndef CONSTANTS_HPP_INCLUDED // some unique macro
#define CONSTANTS_HPP_INCLUDED
#include "Core.hpp"
class TestLibrary::Core::Constants
{
public:
static float const_PI;
static float const_Euler;
Constants();
};
float TestLibrary::Core::Constants::const_PI = 3.1415;
float TestLibrary::Core::Constants::const_Euler = 2.71828;
#endif
//SFMLpp.hpp
#pragma once
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#ifndef SFML_HPP_INCLUDED // some unique macro
#define SFML_HPP_INCLUDED
#include <testlibrary.hpp>
class TestLibrary::SFML
{
public:
class Text;
};
//#include "Text.hpp"
#endif
//Text.hpp
#pragma once
#ifndef TEXT_HPP_INCLUDED // some unique macro
#define TEXT_HPP_INCLUDED
#include "SFMLpp.hpp"
class TestLibrary::SFML::Text : public sf::Text
{
public:
sf::Font font_;
Text();
Text(std::string string);
Text(std::string string, sf::Font &font);
Text(std::string string, sf::Font &font, int size);
Text(std::string string, sf::Font &font, int size, sf::Color color);
void setTextInt(int inputText);
void drawText(sf::RenderWindow &window);
};
#endif
//text.cpp
#include "text.hpp"
| Static variables must be defined only once in the entire program. If you define them in a header file, they are defined in every .cpp file that includes the header.
Move these lines into a .cpp file:
float TestLibrary::Core::Constants::const_PI = 3.1415;
float TestLibrary::Core::Constants::const_Euler = 2.71828;
Or use constexpr to define them in place:
class TestLibrary::Core::Constants
{
public:
static constexpr float const_PI = 3.1415;
static constexpr float const_Euler = 2.71828;
|
70,621,688 | 70,624,442 | A "constexpr" function should not be declared "inline" | By analyzing code using SonarLint, I got a message (the title of the question) about a destructor that is declared like below:
class Foo
{
public:
. // default ctor
. // parameterized ctor
.
inline ~Foo() = default; // dtor
.
. // copy ctor = delete
. // copy assignment operator = delete
. // move ctor
. // move assignment operator
private:
...
mutable std::vector< std::vector<char> > m_Matrix;
...
};
Here is the message's description:
Declaring a function or a static member variable constexpr makes it implicitly inline.
I don't think the dtor of this class can be constexpr or consteval because it has a non-static data member of type std::vector so ~Foo has to call delete[] at some point to deallocate the vector's storage.
So why is SonarLint showing this message? Is it because of = default? Does any defaulted special member function become implicitly constexpr?
| Yes:
An explicitly-defaulted function that is not defined as deleted may be declared constexpr or consteval only if it is constexpr-compatible ([special], [class.compare.default]).
A function explicitly defaulted on its first declaration is implicitly inline ([dcl.inline]), and is implicitly constexpr ([dcl.constexpr]) if it is constexpr-compatible.
(From Explicitly defaulted functions, emphasis mine.)
Foo is likely constexpr-compatible in C++20, because std::vector can now be constexpr.
|
70,622,617 | 70,622,677 | for-loop counter gives an unused-variable warning | My program has an iterative algorithm with a for-loop that I had written as
for ( auto i: std::views::iota( 0u, max_iter ) ) { ... }
I really like the fact that it can be written like this, even if the necessary header files are enormous. When I compile it though I get a warning that i is an unused variable.
When I write the for-loop in the old-fashioned way
for ( unsigned i=0; i < max_iter; i++ ) { ... }
then there is no warning.
I tested this with a minimal program for-loop.cpp:
#include<ranges>
#include<numeric>
#include<iostream>
int main() {
char str[13] = "this is good";
for (auto i : std::views::iota(0u, 2u)) {
std::cout << str << "\n";
}
for (unsigned it=0; it<2; it++ ) {
std::cout << str << "\n";
}
return 0;
}
and sure enough, compiling it with g++ -Wall --std=c++20 -o for-loop for-loop.cpp gives a warning for the first loop and not the second.
Am I missing something here? I prefer the first notation -- and I know that I can stop the warnings wit -Wno-unused-variables; I would like those warnings, it's just that I am really using the for-loop counter.
| i is indeed never used.
You might add attribute [[maybe_unused]] (C++17) to ignore that warning:
for ([[maybe_unused]]auto i : std::views::iota(0u, 2u)) {
std::cout << str << "\n";
}
|
70,623,318 | 70,631,611 | How to know a generic type T if it has an appropriate constructor for use? | I am implementing a doubly linked list which has sentinel nodes as its head and tail, say this class named List. Node is a private structure in List. This class has a private method Init for initializing the head and tail node, which is invoked in the constructors of List.
template<typename T>
class List {
public:
List() {
Init();
}
...
private:
struct Node {
T data;
Node* prev;
Node* next;
// Constructors
};
size_t size;
Node* head;
Node* tail;
void Init() {
// Codes arise some problem if instances of T have no default constructor.
head = new Node;
tail = new Node;
head->prev = nullptr;
head->next = tail;
tail->prev = head;
tail->next = nullptr;
size = 0;
}
};
Now, the question is that, if instances of T have no default constructor, I cannot create sentinel nodes using head = new Node; and tail = new Node;. The new operator always allocates a piece of memory and constructs it. When constructing the Node object, it must use some constructor of T to initialize the data field in Node.
Is there a way to inspect which constructors (except the copy and move construtors) of T I can use to construct the variable data of type T? Or can I only initialize the prev and next fields in Node, leaving the data field uninitialized?
| Your code has a type T that should follow the concepts you are requiring.
In your case, you want it to be default constructible. If the instantiator of the template doesn't provide a T the complies, it'll get a large template error.
You could add a static_assert to your code, to provide a better message (and to provide it earlier, if your method ain't directly used)
You could use: static_assert(is_default_constructible_v).
More variants exist, if it shouldn't throw ..., see documentation
In C++20, you could use concepts as well to restrict T. I'm not fluent in them, so I'll leave it to you to find the correct syntax.
There are other solution, like storing std::optional, or using variadic arguments on your init function in order to construct T.
In which case you might want to restrict the code using std::is_constructible. std::aligned_storage could also work if you don't mind placement news. All depends on what you want to achieve with this.
|
70,623,395 | 70,624,022 | Why doesn't this_thread::sleep_for need to be linked against pthread? | Usually when building thread related code in GCC, explicit linking against pthread is necessary:
g++ -pthread main.cxx
However, the following code compiles, links, and runs fine without being linked against pthread:
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
int main() {
std::this_thread::sleep_for(1000ms);
return 0;
}
I guess what is happening here is that std::this_thread::sleep_for is using some POSIX function from libc (instead of something from pthread)? But if that is the case, does the execution of std::this_thread::sleep_for change depending on whether or not it was called from the main thread?
|
Why doesn't this_thread::sleep_for need to be linked against pthread?
Because the call to std::this_thread::sleep_for translates into underlying call to nanosleep, which is defined in libc.so.6, and not in libpthread.so.0.
Note that when linking with GLIBC-2.34 and later, using other functions (which previously required -pthread) no longer require it, because GLIBC got rid of libpthread.
See also this answer.
|
70,624,027 | 70,643,475 | What to use on Nodejs addons. Node.h or Napi.h | I have some pretty simple questions.
What is the main difference between node.h and napi.h.
What should I use for normal/personal use case.
Why are there more "nodejs" headers. (node.h, napi.h, nan.h, node_api.h, ...)
I have looked on Internet for answers on these questions but I could find any.
I'm sorry if this is one of the must know things, but I started with addons recently.
| There are four different interfaces for a Node.js addons
The raw node.h (C++) which is no interface at all - in this case you will have to deal with different V8/Node.js versions - which is very hard and cumbersome;
The old Node.js Nan (C++) which is still maintained and it allows you to have an uniform C++ API across all Node.js versions - but it requires that your addon is built separately for every Node.js version and does not support worker_threads;
The new napi.h (C) which has an uniform ABI across all versions - meaning that a binary module built for one version will work with all later versions;
The newest Node Addon API (C++) which is a set of C++ classes around napi.h that allows you to use NAPI with C++ semantics. It is fully compatible with napi.h and you can mix the two.
For a new module, Node Addon API is by far the best choice.
|
70,624,519 | 70,625,599 | Boost gzip how to output compressed string as text | I'm using boost gzip example code here.
I am attempting to compress a simple string test and am expecting the compressed string H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA as shown in this online compressor
static std::string compress(const std::string& data)
{
namespace bio = boost::iostreams;
std::stringstream compressed;
std::stringstream origin(data);
bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
out.push(origin);
bio::copy(out, compressed);
return compressed.str();
}
int main(int argc, char* argv[]){
std::cout << compress("text") << std::endl;
// prints out garabage
return 0;
}
However when I print out the result of the conversion I get garbage values like +I-. ~
I know that it's a valid conversion because the decompression value returns the correct string. However I need the format of the string to be human readable i.e. H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA.
How can I modify the code to output human readable text?
Thanks
Motivation
The garbage format is not compatible with my JSON library where I will send the compressed text through.
| The example site completely fails to mention they also base64 encode the result:
base64 -d <<< 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA' | gunzip -
Prints:
test
In short, you need to also do that:
Live On Coliru
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <iostream>
#include <sstream>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
std::string decode64(std::string const& val)
{
using namespace boost::archive::iterators;
return {
transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>{
std::begin(val)},
{std::end(val)},
};
}
std::string encode64(std::string const& val)
{
using namespace boost::archive::iterators;
std::string r{
base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>{
std::begin(val)},
{std::end(val)},
};
return r.append((3 - val.size() % 3) % 3, '=');
}
static std::string compress(const std::string& data)
{
namespace bio = boost::iostreams;
std::istringstream origin(data);
bio::filtering_istreambuf in;
in.push(
bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
in.push(origin);
std::ostringstream compressed;
bio::copy(in, compressed);
return compressed.str();
}
static std::string decompress(const std::string& data)
{
namespace bio = boost::iostreams;
std::istringstream compressed(data);
bio::filtering_istreambuf in;
in.push(bio::gzip_decompressor());
in.push(compressed);
std::ostringstream origin;
bio::copy(in, origin);
return origin.str();
}
int main() {
auto msg = encode64(compress("test"));
std::cout << msg << std::endl;
std::cout << decompress(decode64(msg)) << std::endl;
}
Prints
H4sIAAAAAAAC/ytJLS4BAAx+f9gEAAAA
test
|
70,624,600 | 70,652,032 | faiss: How to retrieve vector by id from python | I have a faiss index and want to use some of the embeddings in my python script. Selection of Embeddings should be done by id. As faiss is written in C++, swig is used as an API.
I guess the function I need is reconstruct :
/** Reconstruct a stored vector (or an approximation if lossy coding)
*
* this function may not be defined for some indexes
* @param key id of the vector to reconstruct
* @param recons reconstucted vector (size d)
*/
virtual void reconstruct(idx_t key, float* recons) const;
Therefore, I call this method in python, for example:
vector = index.reconstruct(0)
But this results in the following error:
vector = index.reconstruct(0)
File
"lib/python3.8/site-packages/faiss/init.py",
line 406, in replacement_reconstruct
self.reconstruct_c(key, swig_ptr(x)) File "lib/python3.8/site-packages/faiss/swigfaiss.py",
line 1897, in reconstruct
return _swigfaiss.IndexFlat_reconstruct(self, key, recons)
TypeError: in method 'IndexFlat_reconstruct', argument 2 of type
'faiss::Index::idx_t' python-BaseException
Has someone an idea what is wrong with my approach?
| This is the only way I found manually.
import faiss
import numpy as np
a = np.random.uniform(size=30)
a = a.reshape(-1,10).astype(np.float32)
d = 10
index = faiss.index_factory(d,'Flat', faiss.METRIC_L2)
index.add(a)
xb = index.xb
print(xb.at(0) == a[0][0])
Output:
True
You can get any vector with a loop
required_vector_id = 1
vector = np.array([xb.at(required_vector_id*index.d + i) for i in range(index.d)])
print(np.all(vector== a[1]))
Output:
True
|
70,625,489 | 70,627,491 | ++v2 output to stop before my first variable | I'm trying a very basic C++ exercise:
Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
This is my program:
#include <iostream>
int main()
{
std::cout << "Write two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::endl;
while (v1 > v2)
{
std::cout << ++v2 << std::endl;
}
}
My output shows like this:
Write two numbers:
10
5
The numbers between 10 and 5 are:
6
7
8
9
10
And my questions is, how do I output just from 6 to 9, without the 10?
I'm with the basics, so I don't need for or loops or other things more advanced, just a while and ++v2.
| I finally added this code in order to work and to read both cases as a comment suggested before:
#include <iostream>
int main()
{
std::cout << "Write two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::endl;
while (v2 < v1 && ++v2 < v1)
{
std::cout << v2 << std::endl;
}
while (v1 < v2 && ++v1 < v2)
{
std::cout << v1 << std::endl;
}
}
If it is too newbie, let me know, maybe there is another way to make it look simpler (just with while).
|
70,625,788 | 70,625,914 | Calculate the sum of all arguments(non-type parameters) passed through a template | I want to calculate the sum of all arguments (non-type parameters) passed through a template. I compiled the following program with: g++ -std=c++17 -g -Wall -o main main.cpp. It seems that I miss something, because I get this errors when compiling:
error: call of overloaded ‘func<N_0>()’ is ambiguous
std::cout << func<N_0>() << std::endl;
error: call of overloaded ‘func<22>()’ is ambiguous
return N + func<Next... >();
#include <iostream>
using namespace std;
template <std::size_t T>
std::size_t sum()
{
return T;
}
template <std::size_t N, std::size_t ...Next>
std::size_t sum()
{
return N + sum<Next... >();
}
int main()
{
const size_t N_0 = 4;
const size_t N_1 = 11;
const size_t N_2 = 22;
std::cout << sum<N_0>() << std::endl;
std::cout << sum<N_0, N_1, N_2>() << std::endl;
return 0;
}
I found a lot of examples like this:
#include <iostream>
template<typename T>
T adder(T first) {
return first;
}
template<typename T, typename... Args>
T adder(T first, Args... args) {
return first + adder(args...);
}
int main() {
const int c = adder(1, 8, 4);
std::cout << c << '\n';
return 0;
}
I am very curious why my code is not working.
| In both the first and second code example, calling the function with only one (template) argument results in both function templates being viable. The packs will simply be empty.
However, in overload resolution in the second example the variadic template is considered less specialized than the non-variadic one, basically because the set of possible arguments to call it with is a superset of those that the non-variadic one can be called with. This is only because of the parameter pack in the function parameters. Therefore overload resolution will prefer the non-variadic template as a tie-breaker.
This ordering doesn't apply to your first code example, where the function parameters of both templates are the same.
Therefore overload resolution with a single (template) argument is ambiguous in your first code example, but not ambiguous in the second.
You can specify that the variadic template requires at least two arguments to resolve the ambiguity:
template <std::size_t N, std::size_t M, std::size_t ...Next>
std::size_t sum()
{
// May wrap-around to zero
return N + sum<M, Next... >();
}
However, in C++17 and later the whole sum construct can be simplified by use of fold expressions to:
template <std::size_t ...Ns>
std::size_t sum()
{
// May wrap-around to zero
return (Ns + ...);
}
(This function should probably be marked noexcept and constexpr in C++17 or consteval in C++20 and one should be careful with many/large arguments since the addition will silently wrap-around if the sum becomes too large for std::size_t to hold.)
|
70,626,858 | 70,626,871 | macOS: C++11 Compilation Error with Apple clang Version 13 In Terminal but not In Xcode | I'm trying to run an example from Microsoft Docs on delegating constructors in C++. For small bits of code like this, I like to use VS Code, but when I use my usual make command in the terminal I get the error,
error: delegating constructors are permitted only in C++11
I do not get this error when I run the same code in Xcode.
Why can't I run this in the terminal? My Xcode stuff, including command line tools, is up to date so is there something else I'm missing?
Edit
If I enter g++ --version in the terminal I get,
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: x86_64-apple-darwin21.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
| You need to add --std=c++11 to the g++ command line options in your Makefile. Visual Studio defaults to the latest possible C++ standard. gcc defaults to the earliest.
|
70,627,117 | 70,627,498 | Loading Wave File but there is random nonsense at the end of the data rather than the expected samples | I've got a simple wav header reader i found online a long time ago, i've gotten back round to using it but it seems to replace around 1200 samples towards the end of the data chunk with a single random repeated number, eg -126800. At the end of the sample is expected silence so the number should be zero.
Here is the simple program:
void main() {
WAV_HEADER* wav = loadWav(".\\audio\\test.wav");
double sample_count = wav->SubChunk2Size * 8 / wav->BitsPerSample;
printf("Sample count: %i\n", (int)sample_count);
vector<int16_t> samples = vector<int16_t>();
for (int i = 0; i < wav->SubChunk2Size; i++)
{
int val = ((wav->data[i] & 0xff) << 8) | (wav->data[i + 1] & 0xff);
samples.push_back(val);
}
printf("done\n");
}
And here is the Wav reader:
typedef struct
{
//riff
uint32_t Chunk_ID;
uint32_t ChunkSize;
uint32_t Format;
//fmt
uint32_t SubChunk1ID;
uint32_t SubChunk1Size;
uint16_t AudioFormat;
uint16_t NumberOfChanels;
uint32_t SampleRate;
uint32_t ByteRate;
uint16_t BlockAlignment;
uint16_t BitsPerSample;
//data
uint32_t SubChunk2ID;
uint32_t SubChunk2Size;
//Everything else is data. We note it's offset
char data[];
} WAV_HEADER;
#pragma pack()
inline WAV_HEADER* loadWav(const char* filePath)
{
long size;
WAV_HEADER* header;
void* buffer;
FILE* file;
fopen_s(&file,filePath, "r");
assert(file);
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
std::cout << "Size of file: " << size << std::endl;
buffer = malloc(sizeof(char) * size);
fread(buffer, 1, size, file);
header = (WAV_HEADER*)buffer;
//Assert that data is in correct memory location
assert((header->data - (char*)header) == sizeof(WAV_HEADER));
//Extra assert to make sure that the size of our header is actually 44 bytes
assert((header->data - (char*)header) == 44);
fclose(file);
return header;
}
Im not sure what the problem is, i've confirmed that there is no meta data, nor is there a mis match between the numbers read from the header of the file and the actual file. Im assuming its a size/offset misallignment on my side, but i cannot see it.
Any help welcomed.
Sulkyoptimism
| WAV is just a container for different audio sample formats.
You're making assumptions on a wav file that would have been OK on Windows 3.11 :) These don't hold in 2021.
Instead of rolling your own Wav file reader, simply use one of the available libraries. I personally have good experiences using libsndfile, which has been around roughly forever, is very slim, can deal with all prevalent WAV file formats, and with a lot of other file formats as well, unless you disable that.
This looks like a windows program (one notices by the fact you're using very WIN32API style capital struct names – that's a bit oldschool); so, you can download libsndfile's installer from the github releases and directly use it in your visual studio (another blind guess).
|
70,627,386 | 70,627,591 | Segmentation fault looking for longest strings in a vector | Given an array of strings, return another array containing all of its longest strings. The solution I developed is available below:
#include <iostream>
#include <vector>
using namespace std;
vector<string> solution(vector<string> ia) {
int maxi = -1;
int size = ia.size();
vector<string> iasol;
for (int i = 0; i < size; i++) {
int m = ia[i].length();
cout << m << " " << maxi << endl;
if (m > maxi)
maxi = m;
}
for (int i = 0; i < size; i++) {
int m = ia[i].length();
if (m == maxi) {
iasol[i] = ia[i];
cout << iasol[i];
}
}
return iasol;
}
int main() {
vector<string> inputArray = {"aba", "aa", "ad", "vcd", "aba"};
solution(inputArray);
}
The program is expected to work as follows:
INPUT
inputArray ← ["aba", "aa", "ad", "vcd", "aba"]
OUTPUT
solution(inputArray) → ["aba", "vcd", "aba"]
The above solution gives the following error:
3 -1
2 3
2 3
3 3
3 3
Segmentation fault
How do I solve this problem?
| Since I found the readability of the source code you developed low, I developed a new solution for this problem.
#include <iostream>
#include <vector>
using namespace std;
/* Returns the size of the vector with the maximum length. */
size_t getMaximumSize(vector<string> input);
/* Returns a vector container based on the string length. */
vector<string> getElementBySize(vector<string> input, size_t size);
/* Prints the vector container. */
void print(vector<string> input);
int main()
{
vector<string> input{"aba", "aa", "ad", "vcd", "aba"};
print(getElementBySize(input, getMaximumSize(input)));
return 0;
}
vector<string> getElementBySize(vector<string> input, size_t size)
{
vector<string> result;
for(int i = 0 ; i < input.size(); ++i)
if(input[i].size() == size)
result.push_back(input[i]);
return result;
}
size_t getMaximumSize(vector<string> input)
{
size_t maximumNumberOfCharacters = input[0].size();
for(int i = 0 ; i < input.size() - 1 ; ++i)
if(input[i].size() < input[i+1].size())
maximumNumberOfCharacters = input[i+1].size();
return maximumNumberOfCharacters;
}
void print(vector<string> input)
{
for(string i : input)
cout << i << ' ';
}
This program produces the following output:
aba vcd aba
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.