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
|
|---|---|---|---|---|
73,678,576
| 73,680,258
|
Does std:: library of c++ have .cpp files?
|
This may be a naive question since I'm a c++ beginner.
In a typical cpp project, we have cpp files and their header files. So based on my understanding, usually cpp files have definitions, while respective header files have declarations. During compiling, we have to include very cpp files in the project since header files do not specify the location of the definition of the declared object. Finally, linker links declaration and definition. This allows the communication between different translation units.
However, when it comes to std:: library, we do include header files but never compile its cpp files. For example, we write #include in main.cpp, but when compiling, the command does not have anything like g++ vector.cpp main.cpp ...
I even tried to search cpp files in the std library folder in my system, but all I can find is various header files.
I do know the definition and declaration can be included in a single header file, I don't think this is how std:: is wrote. Otherwise, it will result in multiple copies of definition when included in different cpp files.
Please help me to understand how this works? Can I do something like this with my own project?
|
Yes, there is compiled code in the standard library. You don't have to compile it because the library comes already compiled with your compiler. And you don't explicitly link to it, because the compiler knows about it. So you don't see it mentioned anywhere when you do normal builds. If you set your compiler to some form of verbose mode you can see that the name of the standard library gets passed to the linker, which pulls the code it needs from the library.
|
73,678,596
| 73,681,926
|
Can't cast void pointer returned by RegGetValueA
|
I'm trying to access the registry using the RegGetValueA function, but I can't cast the void pointer passed to the function. I just get the (value?) of the pointer itself.
Here's my code:
LSTATUS res;
LPCSTR lpSubKey = "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{071c9b48-7c32-4621-a0ac-3f809523288f}";
LPCSTR lpValue = "InstallSource";
PVOID pvData = new PVOID;
LPDWORD pcbData = new DWORD;
res = RegGetValueA(
HKEY_LOCAL_MACHINE,
lpSubKey,
lpValue,
RRF_RT_ANY,
NULL,
pvData,
pcbData);
string* data = static_cast<string*>(pvData);
cout << data << "\n";
cout << pvData;
output:
000000000045A240
000000000045A240
Any help would be much appreciated.
link to documentation:
https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea
|
You are using the function incorrectly.
First off, you shouldn't be accessing Wow6432Node directly at all. The function has flags for accessing 32bit and 64bit keys when dealing with WOW64.
More importantly, you are giving the function a void* pointer that doesn't point at valid memory for your purpose. When reading a string value from the Registry, you must pre-allocate a character buffer of sufficient size, then pass the address of that buffer to the function. You can ask the function for the necessary buffer size.
The code should look more like the following instead:
LSTATUS res;
LPCSTR lpSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{071c9b48-7c32-4621-a0ac-3f809523288f}";
LPCSTR lpValue = "InstallSource";
char *pszData = NULL;
DWORD cbData = 0;
res = RegGetValueA( HKEY_LOCAL_MACHINE, lpSubKey, lpValue, RRF_RT_REG_SZ | RRF_SUBKEY_WOW6432KEY, NULL, NULL, &cbData);
if (res != ERROR_SUCCESS) ...
pszData = new char[cbData];
res = RegGetValueA( HKEY_LOCAL_MACHINE, lpSubKey, lpValue, RRF_RT_REG_SZ | RRF_SUBKEY_WOW6432KEY, NULL, pszData, &cbData);
if (res != ERROR_SUCCESS) ...
cout << pszData << "\n";
delete[] pszData;
|
73,678,674
| 73,678,794
|
Get a count of numbers in segments
|
The array has a large size up to 100000 and m is number of gets.
For example:
int array[] = {1, 2, 2, 3, 4, 5, 5, 5, 6, 7};
get(1, 4, array);
And the result:
1: 1
2: 2
3: 1
I wrote this but it uses a lot of memory:
for (int i=1; i<=n; i++) {
ma[a[i]]++;
pref[i] = ma;
}
map<int,int> ans = pref[r];
for (auto i: pref[l - 1]) {
ans[i.first] -= i.second;
}
for (auto i: ans) {
cout << i.first << ' ' << i.second << '\n';
}
|
What's wrong is you're computing the answer for all of the numbers. Instead, do this:
map<int, int> count(int[] array, int left, int right) {
map<int, int> result;
for (int i=left; i <= right; i++) {
result[array[i]]++;
}
return result;
}
It's pretty simple; it just iterates over all the indexes and increments the value. Of course, make sure that left and right are within the bounds of the array.
|
73,679,033
| 73,691,576
|
C++20 range from enum
|
can an enum be used as (or turned into) a C++20 range?
I am thinking about following use case, cartesian_product() is C++23 unfortunatey:
#include <algorithm>
using namespace std::ranges;
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATOE};
for (auto [fruit, vegetable] : views::cartesian_product(Fruit, Vegetable))
{
...
}
|
You can do this, it's just that you need the help of a library to turn the enum into a range of enumerator names. One such library is Boost.Describe:
#include <array>
#include <boost/describe.hpp>
#include <fmt/ranges.h>
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATO};
BOOST_DESCRIBE_ENUM(Fruit, APPLE, STRAWBERRY, COCONUT);
BOOST_DESCRIBE_ENUM(Vegetable, CARROT, POTATO);
template<class E>
constexpr auto enum_names() {
return []<template <class...> class L, class... T>(L<T...>)
-> std::array<char const*, sizeof...(T)>
{
return {T::name...};
}(boost::describe::describe_enumerators<E>());
}
int main() {
// prints fruits=["APPLE", "STRAWBERRY", "COCONUT"] vegetables=["CARROT", "POTATO"]
fmt::print("fruits={} vegetables={}\n", enum_names<Fruit>(), enum_names<Vegetable>());
}
Demo
|
73,679,355
| 73,680,362
|
Is there any way to append initializer list --> std::initializer_list<std::pair<std::string, std::string>>?
|
In my project there is need to append initializer list at runtime.
I have figured the way to have initializer_list std::initializer_list<std::pair<std::string, std::string>> at runtime in my project, but not able to figure out way to append this list if user passing multiple no. of pairs.
dummy code implementation of that part is below:
#include <iostream>
#include <string.h>
#include <initializer_list>
#define __FILENAME__ strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__
#define S1(x) #x
#define S2(x) S1(x)
#define LOCATION std::string(__FILENAME__) + ":" + std::string(S2(__LINE__)) + ":" + std::string(__PRETTY_FUNCTION__)
#define ATTR_PAIR std::pair<std::string, std::string>("Log.Details",LOCATION)
int main()
{
std::string s = "op";
std::string s1 = "de";
std::string s2 = "en";
auto pa = std::make_pair(s,s1);
auto pb = std::make_pair(s,s2);
auto list = {pb,pa};
std::initializer_list<std::pair<std::string, std::string>> L({list}) ;
std::initializer_list<std::pair<std::string, std::string>> I = {ATTR_PAIR,*(L .begin()),*(L.begin()+1)}; //is there any generic way to append this with as much pairs user passes in list
for(auto it=I.begin();it!=I.end();++it)
{
std::cout<<(it->first)<<std::endl;
std::cout<<(it->second)<<std::endl;
}
}
my need is to append initializer I with as much pair I have in list .
code which I wrote here, I have passed (L.begin()+1) to have 2nd pair. Is there any other generic way to do so???
|
The length of a std::initializer_list cannot be chosen dynamically at runtime and list's length here is not a compile-time usable property.
std::initializer_list is the wrong tool for this. It should only be used as parameters to functions or implicitly in e.g. a range-for loop. In any case only directly to store a {/*...*/} braced-initializer-list temporarily to be processed further e.g. into a proper container to copy elements from.
If you need a sequence container with runtime-determined dimensions, use std::vector instead. Elements can be added to it with e.g. push_back/emplace_back/insert/emplace member functions and it has a constructor taking an iterator range.
|
73,679,723
| 73,679,834
|
"undefined reference to `____: :___`" error for pure virtual functions when I seperate my files into cpp and header files
|
So I have the Book class that inherits from Publication.
Publication has two pure virtual functions which I implemented in Book.
The code worked before I tried seperating into header and cpp files
classes.h
#include <iostream>
#include <string>
using namespace std;
class Publication
{
protected:
// Common attributes
string title;
float price;
public:
// Two pure virtual functions that will need implementation in derived classes
virtual void getData() = 0;
virtual void putData() = 0;
};
class Book : public Publication
{
private:
int pages;
public:
void getData();
void putData();
};
classes.cpp
#include "classes.h"
// getData implementation - gets inputs from user
void Book::getData () {
cout << "Enter title: ";
cin >> title;
cout << "Enter price: ";
cin >> price;
cout << "Enter number of pages: ";
cin >> pages;
cout << endl;
}
// putData implementation - prints out Book info
void Book::putData() {
cout << "Title: " << title << endl;
cout << "Price: " << price << endl;
cout << "Pages: " << pages << endl;
}
main.cpp
#include <iostream>
#include <string>
#include "classes.h"
using namespace std;
int main() {
Book book1;
book1.getData();
book1.putData();
return 0;
}
This is one of the errors
: undefined reference to Book::getData()'
but it says it for the putData function as well
|
I realized I was just dumb and forgot that I need to compile both cpp files and not just main.cpp
Running g++ main.cpp task1.cpp caused no errors.
|
73,680,053
| 73,682,087
|
How to combine views::enumerate and views::filter?
|
I have a container that I want to filter.
I also need the index of the items later.
For that I want to use something like this:
auto items_to_remove = items | ranges::view::enumerate | ranges::view::filter(/*???*/);
What type do I have to use for the filter function?
Edit: Here is my code/ error message:
auto f = [](const auto& pair) {
return true;
};
auto items_to_remove = level.items | ranges::views::enumerate | ranges::views::filter(f);
|
Adding an enumerate::view makes the element that is passed to the filter a
ranges::common_pair<size_t, int&>&
So, just take the common_pair by const&.
auto f = [](const ranges::common_pair<size_t, int&>& pair) {
// filter on pair.first to filter on the index
// filter on pair.second to filter on the actual value in the vector
};
Demo
or simply:
auto f = [](auto&& pair) { ... }
Then
for (auto&&[idx, element] : v | views::enumerate | views::filter(f)) {
element += 100; // elements are mutable here
std::cout << idx << ' ' << element << '\n';
}
Demo
|
73,680,313
| 73,681,822
|
Read access violation while deleting multiple nodes from a linked list
|
I need to implement a doubly linked list in c++ for a small animation running on console. The linkedlist stores clouds and then they move through the console and as each cloud hits the end of screen, it needs to be deleted from linked list. As the cloud hits the end, it has a variable called alive which is set to false so it can be deleted.
I can't upload the full game code, but I have recreated the problem in dummy code by creating sample clouds where some of them have alive = true and alive = false. I have also updated the previous and next nodes of the cloud to be deleted but I still get an error:
Exception thrown: read access violation. temp was 0xFFFFFFFFFFFFFFFF.
Code below (include statements removed for simplicity)
Test.cpp
int main() {
Cloud* a = new Cloud('a');
a->alive = false;
Node* a1 = new Node(a);
Cloud* b = new Cloud('b');
b->alive = false;
Node* b1 = new Node(b);
LinkedList list;
list.Insert(a);
list.Insert(b);
Node* temp = list.head;
while (temp != nullptr) {
if (temp->data->alive == false) list.Delete(temp); // throws exception after deleting a single node.
temp = temp->next;
}
return 0;
}
LinkedList.cpp delete function
void LinkedList::Delete(Node* del) {
if (del == head) {
OutputDebugStringA("Cloud in head");
Node* temp = head;
head = head->next;
head->prev = nullptr;
delete temp;
return;
}
else {
Node* temp = head;
while (temp != tail->next) {
if (temp == del) {
if (temp->next != nullptr) {
OutputDebugStringA("Cloud in mid");
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
break;
}
else {
OutputDebugStringA("cloud at tail");
tail = temp->prev;
tail->next = nullptr;
break;
}
}
temp = temp->next;
}
delete temp;
temp = nullptr;
}
}
Node.cpp
#include "Node.h"
#include <iostream>
using namespace std;
Node::Node() {
this->data = nullptr;
}
Node::Node(Cloud* data) {
this->data = data;
}
Someone please point out where am I going wrong. Thanks
|
As @John Zwinck and @Sam Varshavchik pointed out that the implementation of delete method was flawed and temp became useless after the Delete function returned.
I fixed it by using another temp pointer and fixing the delete method to be O(1).
Delete Method
void LinkedList::Delete(Node* del) {
if (del == head) {
head = head->next;
head->prev = nullptr;
}
else if (del == tail) {
tail = del->prev;
tail->next = nullptr;
}
else {
del->prev->next = del->next;
del->next->prev = del->prev;
}
delete del;
}
Node deletion
Node* temp = cloud_list.head;
Node* next;
while (temp != nullptr) {
next = temp->next;
if (temp->data->alive == false) {
cloud_list.Delete(temp);
}
temp = next;
}
The deletion now works fine.
|
73,680,646
| 73,680,745
|
how to allow only one specific class to create other class instances
|
MyDataConatiner is kind of facade to MyData.
I Dont want to allow other classes to create Mydata .
it has some logic of lazy instantiation that I want to keep in MyDataConatiner .
thought about something like private ctor with friend class , but I am not sure.
or is it something with one of factory design patterns
|
One way is to make MyDataContainer a friend of MyData as shown below:
class MyData
{
//befriend MyDataContainer so that MyDataContainer can create object of type MyData
friend class MyDataContainer;
//private converting ctor that can be used by MyDataContainer but not normal users
MyData(int)
{
}
};
class MyDataContainer
{
public:
//add method(s) for creating MyData object
//other code here
};
|
73,680,994
| 73,686,358
|
Error when importing a class/structures from one dll to another dll (c++, lnk2019)
|
I have 2 DLLs. The first describes the LinkedList data structure. In the second, this structure is used.
LinkedList.h (from first .ddl):
#pragma once
#ifdef DS_EXPORTS
#define DS_LL_API __declspec(dllexport)
#else
#define DS_LL_API __declspec(dllimport)
#endif
#include "pch.h"
#include <iostream>
using namespace std;
class ListNode
{
public:
int val;
ListNode * next;
ListNode();
ListNode(int x);
ListNode(int x, ListNode * next);
void toString(const char * start, const char * sep, const char * end);
};
LinkedList.cpp (from first .dll):
#include "pch.h"
#include "LinkedList.h"
ListNode::ListNode() : val(0), next(nullptr) { }
ListNode::ListNode(int x) : val(x), next(nullptr) { }
ListNode::ListNode(int x, ListNode * next) : val(x), next(next) { }
void ListNode::toString(const char * start, const char * sep, const char * end)
{
ListNode * ln = this;
cout << start << ln->val;
while(ln->next != nullptr)
{
cout << sep << ln->next->val;
ln = ln->next;
}
cout << end << endl;
}
LeetCodeTasks.h (from second .dll):
#pragma once
#ifdef LCT_EXPORTS
#define LCT_API __declspec(dllexport)
#else
#define LCT_API __declspec(dllimport)
#endif
#include "pch.h"
#include <vector>
#include <unordered_map>
//#include "../DataStructures/LinkedList.h"
#include "LinkedList.h"
using namespace std;
extern LCT_API ListNode * task2_addTwoNumbers(ListNode * l1, ListNode * l2);
LeetCodeTasks.cpp (from second .dll):
#include "pch.h"
#include "LeetCodeTasks.h"
#pragma region Task 2
ListNode * task2_addTwoNumbers(ListNode * l1, ListNode * l2)
{
ListNode * result = new ListNode();
int number = 0;
if(l1 != nullptr)
{
number += l1->val;
}
if(l2 != nullptr)
{
number += l2->val;
}
result->val += number % 10;
if(l1 != nullptr && l1->next != nullptr && l2 != nullptr && l2->next != nullptr)
{
l1->next->val += number / 10;
result->next = task2_addTwoNumbers(l1->next, l2->next);
}
else if(l1 != nullptr && l1->next != nullptr)
{
l1->next->val += number / 10;
result->next = task2_addTwoNumbers(l1->next, nullptr);
}
else if(l2 != nullptr && l2->next != nullptr)
{
l2->next->val += number / 10;
result->next = task2_addTwoNumbers(nullptr, l2->next);
}
else if(number / 10 > 0)
{
result->next = new ListNode(number / 10);
}
return result;
}
#pragma endregion
But when assembling the 2nd and DLL, the following errors appear:
LNK2019 reference to the unresolved external character "public: __cdecl ListNode::ListNode(void)" (??0 ListNode@@QUEUE@XZ) in the function "class ListNode * __cdecl task2_addTwoNumbers(class ListNode *,class ListNode *)" (?task2_addTwoNumbers@@YAPEAVListNode@@PEAV1@0@Z).
LNK2019 reference to the unresolved external character "public: __cdecl ListNode::ListNode(int)" (??0ListNode@@QEAA@H@Z) in the function "class ListNode * __cdecl task2_addTwoNumbers(class ListNode *,class ListNode *)" (?task2_addTwoNumbers@@YAPEAVListNode@@PEAV1@0@Z).
I tried first to write struct instead of class - it didn't help.
For the second .dll in the project settings specified as additional directories of included files - the path to the headers from the first one .dll
Does anyone know how to solve this problem?
|
1.Follow drescherjm 's comment.
2.I noticed another problem:
Your project one did not generate lib file, so you have no way to add LinkedList.lib in Linker->input of project two's properties. But you still got the link errors.
I deduce that you did not actually add LinkedList.lib file in Linker->input->Additional Dependencies. You need to fix it.
|
73,681,554
| 73,681,595
|
C++: instantiating object that is declared in a header file
|
If an object is declared in a header file like this:
Object obj;
What would be the best way to instantiate it? A simple reassignment like this? Does this destroy the declared object and create a new one and can this lead to errors?
obj = Object(...);
Or should I use a pointer and create the object with new? This way i can be sure that only here the object gets created.
obj = new Object(...);
Or should the class have a init method, so the object does not get destroyed and recreated?
Would you do it any different if the object is a member of a class?
|
Object obj;
already instantiates the object. SO you really should not have it in a header file
you probably want
Object *obj;
ie a pointer to an object , then instantiate with 'new'.
But better would be std::unique_ptr<Object>
|
73,682,060
| 73,682,289
|
Compile error in SFML 2.5.1 sample code in Linux
|
Compile error
I was looking at a configuration video in yt for linux mint but it doesn't give me the same results in arch.
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
|
As the error message indicate, there is no constructor for sf::VideoMode which takes two int input for width and height. The constructor expect an argument of type Vector2u.
Create the Window as follows:
sf::RenderWindow window(sf::VideoMode({200, 200}), "SFML works!");
|
73,682,188
| 73,682,230
|
Why does C++ implicit casting work, but explicitly casting throws an error (specific example)?
|
I was trying to overload the casting operator in C++ for practice, but I encountered a problem and I can't figure out the issue. In the example, you can implicitly cast fine, but it causes an error when you try to explicitly cast.
struct B
{
B() = default;
B( B& rhs ) = default;
};
struct A
{
operator B()
{
return B();
}
};
int main()
{
A a;
B example = a; //fine
B example2 = static_cast<B>(a); //error
}
The error is:
error C2440: 'static_cast': cannot convert from 'A' to 'B'
message : No constructor could take the source type, or constructor overload resolution was ambiguous
The problem only appears if you define the copy constructor in the B structure. The problem goes away, though, if you define the move constructor, too, or make the copy constructor take in a const B& ( B( const B& rhs ) ).
I think the problem is that the explicit cast is ambiguous, but I don't see how.
I was looking at a similar problem, here, but in that case I could easily see how the multiple options for casting led to ambiguity while I can't here.
|
static_cast<B>(a);
This expression is an rvalue, more loosely described as a temporary value.
The B class has no suitable constructor. The B( B &rhs) constructor is not suitable, mutable lvalue references don't bind to temporaries, hence the compilation failure.
|
73,682,305
| 73,814,247
|
How to debug missing functions in vtable of base class
|
By using objects of the following structure(some bits simplified):
class RafkoAgent{
virtual std::vector<double> solve(std::vector<double>& in) = 0;
void solve(std::vector<double>& in, std::vector<double>& out){
out = solve(in);
}
};
class SolutionSolver : public RafkoAgent {
std::vector<double> solve(std::vector<double>& in){ /* ... */}
};
In some cases a segfault is being thrown.
In my understanding, this structure should be adequate, but in the example I tried it in(here), it throws a segfault and I can't seem to get to the bottom of it.
In the code, when I check the vtable of the 2 symbols I find the following difference:
150 solver->solve({1.0, 2.0});
(gdb) info vtbl solver
This object does not have a virtual function table
(gdb) info vtbl *solver
vtable for 'rafko_net::SolutionSolver' @ 0x555555692bf0 (subobject @ 0x5555556ad710):
[0]: 0x55555559ff42 <rafko_gym::RafkoAgent::get_step_sources[abi:cxx11]() const>
[1]: 0x5555555a016c <rafko_gym::RafkoAgent::[abi:cxx11]() const>
[2]: 0x5555555a030a <rafko_gym::RafkoAgent::get_input_shapes() const>
[3]: 0x5555555a0502 <rafko_gym::RafkoAgent::get_output_shapes() const>
[4]: 0x5555555a074a <rafko_gym::RafkoAgent::get_solution_space() const>
[5]: 0x5555555a4c8e <rafko_net::SolutionSolver::~SolutionSolver()>
[6]: 0x5555555a4cdc <rafko_net::SolutionSolver::~SolutionSolver()>
[7]: 0x5555555a0a80 <rafko_net::SolutionSolver::set_eval_mode(bool)>
[8]: 0x55555559e42a <rafko_net::SolutionSolver::solve(std::vector<double, std::allocator<double> > const&, rafko_utilities::DataRingbuffer<std::vector<double, std::allocator<double> > >&, std::vector<std::reference_wrapper<std::vector<double, std::allocator<double> > >, std::allocator<std::reference_wrapper<std::vector<double, std::allocator<double> > > > > const&, unsigned int, unsigned int) const>
(gdb) info vtbl *(rafko_gym::RafkoAgent*)solver
vtable for 'rafko_gym::RafkoAgent' @ 0x555555692bf0 (subobject @ 0x5555556ad710):
[0]: 0x55555559ff42 <rafko_gym::RafkoAgent::get_step_sources[abi:cxx11]() const>
[1]: 0x5555555a016c <rafko_gym::RafkoAgent::get_step_names[abi:cxx11]() const>
Which suggest to me that something is not quite right with the vtable for RafkoAgent. The actual segfault is thrown when it tries to access its virtual function, and instead of solve, gdb seem to step into get_step_names, which is at the end of RafkoAgent's displayed vtable.
An additional detail is that the whole project is a static library + tests. When I run the same code inside the CMake project of the library ( i.e.: where RafkoAgent and SolutionSolver is) the segfault does not occur. It does occur however in the linked example file, where I link the classes from a generated static library file (librafko.a)
The focus of the question is:
Is it by design for a base class to not contain its defined virtual functions in its own vtable, only the derived class? even if the derived class does not introduce additional virtual functions?
If what I'm seeing is faulty how might I be able to debug the root cause of this error?
|
The root cause of the problem was that there were compilation macros used in the exported header files.
The main hint for this was that in the same repository it worked flawlessly, but it failed by the exported library.
The faulty structure was as follows:
class A {};
class B
#if(compile_time_macro)
: public A
#endif
{};
So essentially the library object was built as if the inheritance was included, but since the exported headers did not contain the macro definition, the inheritance was not present there.
This resulted in a very hardly traceable problem.
Whenever you use macros BEWARE.
|
73,683,086
| 73,683,303
|
How to find the smallest number composed of only 1 that can divide by n, given n is a coprime of 10?
|
I'm writing a program with which to find the smallest number m composed of only the number "1" that can divide by a given number n. n must be a co-prime of 10.
For example:
n = 37 -> m = 111 (111/37 =3)
n = 11 -> m = 1111 (1111/11 = 101)
n = 91 -> m = 111111 (111111/91 = 1221)
My current code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n, m = 1;
cin>>n;
while (m % n != 0) {
m = m*10 + 1;
}
cout<<m;
}
I believe this is the right way to find m, but it runs into TLE (Time Limit Exceeded) problems, and I assume it's because:
The code takes too many loops to find a number m that satisfies the conditions.
There is no number m that satisfies the conditions.
Is there anyway to avoid TLE issues for this program? And is there anyway to mathematically find m based on n, or that number m does not exist?
I've found the solutions for Time Limit Exceeded error.
The solution was to reduce the steps in the while loop to:
while(m%n!=0)
{
m=(m*10+1)%n;
cout<<"1";
}
Despite this being solved, I am still curious about the way to find m mathematically (or to determine whether m exists), so any other inputs regarding this are appreciated.
|
For the new version you found, you can be sure that there's no solution if the new m you computed was already encountered previously - that means you're on an infinite loop.
However, since caching previous values of m can be too much for the scope of this problem, you can resort to the weaker condition: if the loop run for more than n times - since m is always smaller than n, it means that at least one m value must have already repeated.
#include <bits/stdc++.h>
using namespace std;
int main()
{
unsigned long int n = 12, m = 1;
unsigned int count = 0;
string result = "1";
while(m%n!=0 && count < n){
m=(m*10+1)%n;
result = result + "1";
count++;
}
cout << (m%n == 0 ? result : "no result") << endl;
}
The condition is weaker in the sense that you find out that there's no solution later, but the result is still correct.
|
73,683,313
| 73,683,581
|
Random matrix multiplication
|
I need to create at least 2 matrix 4x4, multiplicate them and display the result, but I'm getting this thing as as result img
I'm creating matrix a[i][j] and matrix b[k][l], and trying to pass the result to a new matrix called c[i][j]
Besides that, I need to make 2 kinds of matrix multiplication, one like this, and another one like this
Can you please please please help? Code below
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int matriz1() {
int a[4][4], i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
a[i][j] = rand() % 100 + 1;
}
}
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
std::cout << a[i][j] << '\t';
std::cout << '\n';
}
std::cout << '\n';
std::cout << "x" << std::endl;
std::cout << '\n';
std::cout << "Matriz 2:" << std::endl;
int b[4][4], k, l;
for (k = 0; k < 4; ++k)
{
for (l = 0; l < 4; ++l)
{
b[k][l] = rand() % 100 + 1;
}
}
for (k = 0; k < 4; ++k)
{
for (l = 0; l < 4; ++l)
std::cout << b[k][l] << '\t';
std::cout << '\n';
}
std::cout << '\n';
int c[4][4], m, n, x;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
for (k = 0; k < 4; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
cout << " RESULTADO!!!!!!!!!!!!!!!!!!!!!!" << endl;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
cout << c[i][j] << "\t";
}
cout << "\n";
}
return 0;
}
int main()
{
srand(time(0));
std::cout << "Matriz 1:" << std::endl;
std::cout << matriz1() << std::endl;
}
SOLVED IN THE COMMENTS! Stop disliking my post its my first post
|
A common "Beginner's Problem" is writing too much code. One consequence is that there are too many places where bugs and other flaws can hide.
This is in 'C', but the only 'C++' aspect of your code is using cout for output. printf() can also be used with C++.
#include <stdio.h>
#include <stdlib.h>
void fill4x4( int a[][4] ) {
for( int r = 0; r < 4; r++ )
for( int c = 0; c < 4; c++ )
a[r][c] = rand() % 100 + 1;
}
void show4x4( int a[][4] ) {
for( int r = 0; r < 4; r++ )
for( int c = 0; c < 4; c++ )
printf( "%5d%c", a[r][c], " \n"[c] );
puts( "" );
}
int showPair( int a, int b, int pos ) {
printf( "%2dx%-2d%c", a, b, " \n"[pos] );
return a * b;
}
void mult4x4( int a[][4], int b[][4], int d[][4], bool x ) {
for( int r = 0; r < 4; r++ )
for( int c = 0; c < 4; c++ )
// assign (=), not accumulate (+=)
// notice the 'exchange' of row/col access of 'b[][]'
if( x )
d[r][c] = showPair( a[r][c], b[r][c], c );
else
d[r][c] = showPair( a[r][c], b[c][r], c );
puts( "" ); show4x4( d );
}
int main()
{
srand(time(0));
int a[4][4]; fill4x4( a ); show4x4( a );
int b[4][4]; fill4x4( b ); show4x4( b );
int d[4][4];
mult4x4( a, b, d, true );
mult4x4( a, b, d, false );
return 0;
}
Copy, paste, compile and run this to see the (random) output.
EDIT: Pointed out by a question from the OP, here's a further compaction of one function that may-or-may-not be self-evident:
void mult4x4( int a[][4], int b[][4], int d[][4], bool x ) {
for( int r = 0; r < 4; r++ )
for( int c = 0; c < 4; c++ )
d[r][c] = showPair( a[r][c], x?b[r][c]:b[c][r], c );
puts( "" ); show4x4( d );
}
Further EDIT: A common problem for those with time to fill is mucking around, shrinking code that already works. Here's the result of some of that..
#include <stdio.h>
#include <stdlib.h>
char *fmt1 = "%5d%.2s";
char *fmt2 = "%2dx%-2d%.2s";
char *tail1 = " ::";
char *tail2 = " \n";
void show2x4x4( int a[][4], int b[][4] ) {
for( int r = 0, c; r < 4; r++ ) {
for( c = 0; c < 4; c++ ) printf( fmt1, a[r][c], &tail1[c+c] );
for( c = 0; c < 4; c++ ) printf( fmt1, b[r][c], &tail2[c+c] );
}
puts( "" );
}
int main() {
srand(time(0));
int r, c, v, a[4][4], b[4][4], d[4][4], e[4][4], *px, *py;
// fill 2 4x4 arrays of random ints as if both were 1x16
for( px = &a[0][0], py = &b[0][0], v = 0; v < 4 * 4; v++ ) {
int num = rand();
*px++ = num % 100; // two digits only
*py++ = num / 100 % 100;
}
show2x4x4( a, b ); // display
// show and perform the calc of the product matrices
for( r = 0; r < 4; r++ ) {
for( c = 0; c < 4; c++ ) {
printf( fmt2, a[r][c], b[r][c], &tail1[c+c] );
d[r][c] = a[r][c] * b[r][c];
}
for( c = 0; c < 4; c++ ) { // note b[] swaps col & row
printf( fmt2, a[r][c], b[c][r], &tail2[c+c] );
e[r][c] = a[r][c] * b[c][r];
}
}
puts( "" );
show2x4x4( d, e ); // show both products
return 0;
}
Output
29 66 71 20 : 35 88 22 22
35 80 36 85 : 53 1 28 54
12 14 12 71 : 95 98 92 19
62 61 89 17 : 94 63 32 43
29x35 66x88 71x22 20x22 :29x35 66x53 71x95 20x94
35x53 80x1 36x28 85x54 :35x88 80x1 36x98 85x63
12x95 14x98 12x92 71x19 :12x22 14x28 12x92 71x32
62x94 61x63 89x32 17x43 :62x22 61x54 89x19 17x43
1015 5808 1562 440 : 1015 3498 6745 1880
1855 80 1008 4590 : 3080 80 3528 5355
1140 1372 1104 1349 : 264 392 1104 2272
5828 3843 2848 731 : 1364 3294 1691 731
|
73,683,516
| 73,683,846
|
"error: too many arguments to function" when trying to access vector elements in a function call
|
I'm writing a program to populate a vector from a list of numbers in a file, and then check the list to see how many numbers appear more than once. The program works when I hard code the array size based on the number of lines in the file. But I want to use a vector to automate the sizing of the array for each file since there are many files to process and each is unique in length.
I'm confused by this error message because I'm pretty certain I have 3 args in the function declaration and definition. The error is attached to line 63, and g++ highlights the closing brace of (i) and (j).
4 #include <iostream>
5 #include <fstream>
6 #include <string>
7 #include <iomanip>
8 #include <vector>
9 using namespace std;
10
11
12 void duplicateSort(vector<int> &list, int length, int& fpy);
13 void printToScreen(int size, int fpy);
14 void printToFile(int size, int fpy, ofstream &outFile);
15
16
17 int main() {
18 //declare vars
19 ifstream inFile;
20 ofstream outFile;
21 string serNumber;
22 //const int size = 8995;
23 vector<int> list;
24 int fpy = 0;
25 string path;
26
27 cout << "Enter a file path: " << endl;
28 cin >> path;
29
30 inFile.open(path);
31 //outFile.open("exubt_2022_fpy.txt");
32 if (!inFile.is_open()) {
33 cout << "Bad file path!" << endl;
34 return 1;
35 }
36 list[0] = 0;
37
38 //read source file and populate array
39 while(!inFile.eof()) {
40 inFile.ignore(200, '_');
41 inFile.ignore(20, '_');
42 getline(inFile, serNumber, '.'); //fetch a line of data
43 int num = stoi(serNumber); //convert string data to int
44 inFile.ignore(3);
45
46 list.push_back(num); // add the next number to the back of the vector
47 }
48
49 duplicateSort(list, list.size(), fpy);
50 printToScreen(list.size(), fpy);
51 //printToFile(list.size(), fpy, outFile);
52
53 inFile.close();
54 //outFile.close();
55
56 return 0;
57 }
58
59 void duplicateSort(vector<int> &list(), int length, int& fpy) { //sort the list for fpy
60 int match = 0;
61 for (int i = 0; i < length; i++) {
62 for (int j = 0; j < length; j++) {
63 if(list(i) == list(j))
64 match++;
65 if (match == 1) {
66 fpy++;
67 match = 0;
68 }
69 }
70 }
71 }
72 void printToScreen(int size, int fpy) {
73 cout << "Total number of units tested = " << size << endl;
74 cout << "Total number of passed on first try = " << fpy << endl;
75 cout << "FPY = " << static_cast<double>(fpy) * 100 / size << "%" << endl;
76 }
77
78 void printToFile(int size, int fpy, ofstream &outFile) {
79 outFile << "Total number of units tested = " << size << endl;
80 outFile << "Total number of passed on first try = " << fpy << endl;
81 outFile << "FPY = " << static_cast<double>(fpy) * 100 / size << "%" << endl;
82 }
83
|
In C++, () is a function call operator and is used to call the function. For example, when you write main(), you are calling the function main which in turn causes the main function to start executing.
To access an element of a vector, you should use subscript operator [] not function call operator ().
I've highlighted the mistakes in your duplicateSort sort function below:
// function argument should just list the name without `()` operator
// vvvvvvv
void duplicateSort(vector<int> &list(), int length, int& fpy) {
//sort the list for fpy
int match = 0;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
// vvvvvvv vvvvvvv to access element of a vector use [] operator
if(list(i) == list(j))
match++;
if (match == 1) {
fpy++;
match = 0;
}
}
}
}
To make your program work, change the function as follows:
void duplicateSort(vector<int> &list, int length, int& fpy) { //sort the list for fpy
int match = 0;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if(list[i] == list[j])
match++;
if (match == 1) {
fpy++;
match = 0;
}
}
}
}
|
73,683,693
| 73,683,796
|
How to construct derived class from base?
|
Is there a way to cast base class to derived, calling default constructor?
I'm receiving network data, writing it to packets, then calling protocol function which I wish to parse data differently.
class BasePacket {
protected:
std::vector<char> data;
public:
BasePacket(){data.reserve(2048);}
BasePacket(char* _data, int len){ data.assign(&data[0], &data[len]); }
};
class ActionPacket : public BasePacket {
public:
char Action;
char Job;
ActionPacket(){
Action = data[0];
Job = data[1];
}
};
I would like to do something like:
void ProcessPacket(BasePacket& packet){
if (packet.data[0] == 1){
auto t = (ActionPacket)packet;
if(t.Job == 1){
//dosmth
}
}
if (packet.data[0] == 2){
auto t = (OtherPacket)packet;
if(t.smth){
//do another smth
}
}
}
|
If your instance is initially a BasePacket object, why not just code like ActionPacket::ActionPacket(BasePacket&)? That's because ActionPacket have some members that BasePacket doesn't have, reallocation seems inevitable. Just like this:
class ActionPacket
{
ActionPacket(BasePacket& basePacket) :BasePacket(basePacket), Action(data[0]), Job(data[1]) {};
};
// assuming there is a legal BasePacket object called basePacket
auto actionPacket = ActionPacket{basePacket};
BUT, if you are sure that this BasePacket object will ONLY be used for constructing ActionPacket here and will never be used afterwards, you can write ActionPacket::ActionPacket(BasePacket&&) and use std::move like this:
class ActionPacket
{
ActionPacket(BasePacket&& basePacket) :BasePacket(std::move(basePacket)), Action(data[0]), Job(data[1]) {};
};
// assuming there is a legal BasePacket object called basePacket
auto actionPacket = ActionPacket{std::move(basePacket)};
This will be more efficient since std::vector is moved but not re-constructed.
If your instance is initially an ActionPacket object, and there are no virtual methods, static_cast is acceptable; But if there are some virtual methods, dynamic_cast is what you want.
|
73,683,986
| 73,684,344
|
How do you find the number of occurences of a certain word in a sentence when reading in the sentence character by character?
|
For example, if I wanted to find the number of times that the word "MY" appears in a user-inputted sentence, how would I do that? Is it even possible to do this if I'm reading in the sentence one character at a time with a while-loop?
Sample input would be something like: "My house is here"
My current output is:
Number of words.........4
Number of uppercase letters.........1
Number of lowercase letters........12
Number of vowels.........6
Number of substring MY.........0
where number of substring MY should be 1.
Here's what I currently have:
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
bool isvowel(char c) {
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
return true;
} else {
return false;
}
}
int main() {
char c;
int words = 0;
int upperCount = 0;
int lowerCount = 0;
int vowels = 0;
int my = 0;
cout << "Enter a sentence: ";
while (cin.get(c), c != '\n') {
if (isupper(c)) {
upperCount++;
}
if (islower(c)) {
lowerCount++;
}
if (isspace(c)) {
words++;
}
if (isvowel(c) == true) {
vowels++;
}
if (c == 'M' || c == 'm') {
if (c+1 == 'Y' || c+1 == 'y') {
my++;
}
}
}
cout << left << "Number of words" << setfill('.') << setw(10) << right << words + 1 << endl;
cout << left << "Number of uppercase letters" << setfill('.') << setw(10) << right << upperCount << endl;
cout << left << "Number of lowercase letters" << setfill('.') << setw(10) << right << lowerCount << endl;
cout << left << "Number of vowels" << setfill('.') << setw(10) << right << vowels << endl;
cout << left << "Number of substring MY" << setfill('.') << setw(10) << right << my << endl;
system("Pause");
return 0;
}
|
This can be done in many ways, you almost have one. I will not give you the exact solution but you can try something like this: (written in Java)
// String sentence = "My house is here";
// word = "My"
private int getWordCount(String sentence, String word) {
char[] charArr = sentence.toCharArray();
String currWord = "";
int count = 0;
for(char c : charArr) {
if(c != ' ') { currWord += c; } // if c is not space it gets appended to the current word
else {
if(currWord.toLowerCase().equals(word.toLowerCase())) {
count++;
}
currWord = "";
}
}
return count;
}
|
73,684,176
| 73,684,314
|
clang constexpr compile error in lambda, gcc and msvc ok. clang bug?
|
I ran across a compile error in clang with this code. I don't see any problem with it and it works in msvc and gcc. Am I missing something or is it a clang bug?
#include <iostream>
#include <string>
#include <type_traits>
constexpr bool do_tests()
{
// prints error message at runtime if test is false
auto verify = [](bool test, std::string message = "error") {
if (!std::is_constant_evaluated() && !test)
std::cout << message << '\n';
return test;
};
return verify(1 == 1, "test");
};
int main()
{
constexpr bool b = do_tests();
std::cout << b << '\n';
}
compiler explorer
Inexplicable error message from clang:
basic_string.h:356:10: note: assignment to member '_M_local_buf' of union with no active member is not allowed in a constant expression
|
There is no problem with the code and Clang also compiles it correctly if you use libc++ (-stdlib=libc++). Compiler explorer by default uses libstdc++ for Clang (-stdlib=libstdc++). There simply seems to be a compatibility issue between the two. My guess is that libstdc++ is implementing the constexpr string in a way that is technically not allowed in constant expressions, but GCC tends to be less strict in that regard than Clang is, so that Clang fails with the implementation while GCC doesn't have a problem with it.
To be more precise in libstdc++ the implementation of std::string contains an anonymous union with one member being a _CharT array named _M_local_buf. Then libstdc++ is doing the following if the evaluation happens in a constant expression evaluation (from https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/basic_string.h#L355)
for (_CharT& __c : _M_local_buf)
__c = _CharT();
in order to set the union member _M_local_buf to active and zero it.
The problem is that prior to this loop no member of the union has been set to active and setting a member (subobject) through a reference, rather than directly by name or through member access expressions, is technically not specified in the standard to set a member to active. As a consequence that technically has undefined behavior, which is why Clang (correctly) doesn't want to accept it as constant expression. If the member was set as active beforehand, e.g. with an extra line _M_local_buf[0] = _CharT(); it would be fine.
Now of course it seems a bit silly that setting _M_local_buf[0] directly is fine, but setting it through a reference __c isn't, which is probably why GCC still accepts that as a constant expression and I guess there is probably a CWG issue about this.
There is a libstdc++ bug report relating to a very similar issue here, but that is already supposed to be fixed for a while.
It seems that the commit https://github.com/gcc-mirror/gcc/commit/98a0d72a610a87e8e383d366e50253ddcc9a51dd has (re-)introduced the particular issue you are seeing here. Before the commit the member was set active correctly. Might be worth it to open an issue about this, although as mentioned above Clang is being very pedantic here and as the linked bug report also says, the standard should probably be changed to allow this.
|
73,685,070
| 73,685,287
|
How to download a zip file from a github repo using libcurl?
|
I have upload a zip file compressed with WinRAR containing a txt file into my github test Repo, how I could download the zip file using curl?
I tried:
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
void Download(std::string url)
{
CURL *curl_handle;
static const char *pagefilename = "data.zip";
FILE *pagefile;
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
/* set URL to get here */
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
/* Switch on full protocol/debug output while testing */
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
/* disable progress meter, set to 0L to enable and disable debug output */
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
/* send all data to this function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
/* open the file */
pagefile = fopen(pagefilename, "wb");
if(pagefile) {
/* write the page body to this file handle */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
/* get it! */
CURLCode res;
res = curl_easy_perform(curl_handle);
/* close the header file */
fclose(pagefile);
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
return;
}
Download("https://github.com/R3uan3/test/files/9544940/test.zip");
CURLCode res return (CURLE_OK) but it create a file data.zip of 0 bytes, what's wrong?
|
The issue
I checked with
curl -I https://github.com/R3uan3/test/files/9544940/test.zip
It gets
HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...
In other words: this is a redirect and you did not ask libcurl to follow redirects - so you only get that first response stored (which has a zero byte body).
The fix
You can make libcurl follow the redirect by adding this line to your code:
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
|
73,685,911
| 73,691,238
|
Is there a way to remove the last template parameter of variadic template methods?
|
I'm working on creating a simple reflector in C++11, it stores function pointers of instances functions as:
static std::unordered_map<std::string, std::pair<void(EmptyClass::*)(void), int>>* methods;
template<typename ClassType, typename returnType, typename... Args>
static void RegistFunction(std::string name, returnType(ClassType::* func)(Args... args)) {
(*methods)[name] = std::make_pair((void(EmptyClass::*)())func, sizeof...(Args));
}
template<typename ReturnType, typename ClassType, typename... Args>
static ReturnType ExecuteFunction(ClassType* object, std::string name, Args... args) {
if (object == NULL) return;
ReturnType(ClassType:: * func)(Args...) = (ReturnType(ClassType::*)(Args...))(*methods)[name].first;
return (object->*func)(std::forward<Args>(args)...);
}
But when I want to call ExecuteFunction, the number of arguments may be more than the number that function pointer actually accepts. So I need to remove some arguments from the tail of argument list, but it seems I can only remove from head.
template<typename ReturnType, typename ClassType, typename Arg, typename... Args>
static ReturnType ExecuteFunction(ClassType* object, std::string name, Arg arg, Args... args) {
if (sizeof...(Args) + 1 > (*methods)[name].second) {
return ExecuteFunction<ReturnType>(std::forward<ClassType*>(object), std::forward<std::string>(name), std::forward<Args>(args)...);
}
if (object == NULL) return;
ReturnType(ClassType:: * func)( Arg, Args...) = (ReturnType(ClassType::*)(Arg, Args...))(*methods)[name].first;
return (object->*func)(std::forward<Arg>(arg), std::forward<Args>(args)...);
}
Is there any solution to remove arguments at the tail of variadic method template?
|
Here's a C++11 implementation depending only on std::string and std::unordered_map. Some mandatory remarks:
As mentioned, this is extremely brittle due to inferring the function type by the provided arguments. This is UB waiting to happen.
method really shouldn't be a pointer.
If your return type is not assignable, this will break spectacularly.
The class pointer really should be a reference instead.
If you think the implementation is insane, then yes, it is indeed, and you should give up on being fully generic.
A C++11 implementation of std::index_sequence and friends can be found here.
See it in action.
template<typename...>
struct typelist {};
template<size_t, typename, typename, typename, typename>
struct call;
template<size_t N, typename R, typename C, typename... Accum, typename Head, typename... Tail>
struct call<N, R, C, typelist<Accum...>, typelist<Head, Tail...>>
: call<N, R, C, typelist<Accum..., Head>, typelist<Tail...>>
{
};
template<typename R, typename C, typename... Accum, typename Head, typename... Tail>
struct call<sizeof...(Accum), R, C, typelist<Accum...>, typelist<Head, Tail...>>
{
template<typename... Ts>
int operator()(Ts&&...)
{
return 0;
}
template<typename... Ts>
int operator()(R& ret, void (EmptyClass::* g)(), C& obj, Accum&... args, Ts&&...)
{
auto f = (R (C::*)(Accum...))g;
ret = (obj.*f)(std::move(args)...);
return 0;
}
};
template<typename R, typename C, typename... Args, size_t... Is>
R switcher(int i, index_sequence<Is...>, void (EmptyClass::* g)(), C& obj, Args&... args)
{
R ret{};
int unused[] = {(i == Is ?
call<Is, R, C, typelist<>, typelist<Args..., void>>{}(ret, g, obj, args...)
: 0)...};
(void)unused;
return ret;
}
template<typename C, typename R, typename... Args>
void reg(std::string name, R (C::* func)(Args... args)) {
(*methods)[name] = std::make_pair((void (EmptyClass::*)())func, sizeof...(Args));
}
template<typename R, typename C, typename... Args>
R exec(C* obj, std::string name, Args... args) {
if(obj == nullptr)
throw "a tantrum";
auto& info = (*methods)[name];
auto g = info.first;
size_t i = info.second;
if(i > sizeof...(Args))
throw "a fit";
return switcher<R>(i, make_index_sequence<sizeof...(Args) + 1>{}, g, *obj, args...);
}
|
73,686,187
| 73,702,823
|
QuickFix C++ - How to established Trading session from client APP?
|
I have build my quickfix C++ source code with the SSL support using below command. My quickfix library got build successfully.
On Linux (with system openssl),
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DHAVE_SSL=ON -DCMAKE_INSTALL_PREFIX:PATH="install-path" .. make -j 4 install
This is my Initiator code -
if (isSSL.compare("SSL") == 0)
initiator = new FIX::ThreadedSSLSocketInitiator ( application, storeFactory, settings, logFactory );
else
initiator = new FIX::SocketInitiator( application, storeFactory, settings, logFactory );
But while running this getting linking issue. What is the problem ?
CMakeFiles/TradingClient.dir/tradeclient.cpp.o: In function `main':
/mnt/d/TradingClient/tradeclient.cpp:47: undefined reference to `FIX::ThreadedSSLSocketInitiator::ThreadedSSLSocketInitiator(FIX::Application&, FIX::MessageStoreFactory&, FIX::SessionSettings const&, FIX::LogFactory&)'
collect2: error: ld returned 1 exit status
This my CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(TradingClient)
add_definitions(-DHAVE_SSL=1)
set(CMAKE_CXX_STANDARD 14)
set(quickfix_lib "/usr/lib/libquickfix.so")
add_executable(TradingClient Application.h Application.cpp tradeclient.cpp)
target_link_libraries(TradingClient ${quickfix_lib} )
if you go inside quickfix/src/C++/CMakeLists.txt
if (HAVE_SSL)
set (quickfix_SOURCES ${quickfix_SOURCES}
SSLSocketAcceptor.cpp
SSLSocketConnection.cpp
SSLSocketInitiator.cpp
ThreadedSSLSocketAcceptor.cpp
ThreadedSSLSocketConnection.cpp
ThreadedSSLSocketInitiator.cpp
UtilitySSL.cpp)
endif()
these files get build only with SSL . It means my quickfix library is correctly build because object files for these files got generated.
Although object files gets generated as part of library, still getting this linking issue that its not able to find the reference for these methods ThreadedSSLSocketInitiator()
|
but this is not related to compilation issue .Its quickfix source code bug.
I found one blog related to that this file has missing entry
#cmakedefine HAVE_SSL 1
I have added in this file
cat cmake_config.h.in
#ifndef CONFIG_H_IN
#define CONFIG_H_IN
#cmakedefine HAVE_EMX
#cmakedefine HAVE_CXX17
#cmakedefine HAVE_STD_SHARED_PTR
#cmakedefine HAVE_SHARED_PTR_IN_TR1_NAMESPACE
#cmakedefine HAVE_STD_TR1_SHARED_PTR_FROM_TR1_MEMORY_HEADER
#cmakedefine HAVE_STD_UNIQUE_PTR
#cmakedefine HAVE_SSL 1
#endif
|
73,686,877
| 73,687,824
|
Why is the syntax of the destructor ~classname?
|
The syntax of the destructor is ~classname. This results in the need to explicitly write the type of object in the destructor call. To avoid this, C++17 introduced std::destroy_at.
So, what was Bjarne Stroustrup's original rationale for choosing the ~classname syntax for the destructor? If the syntax does not depend on the types, std::destroy_at is not needed.
|
Constructors and destructors were a part of C++ from the very earliest days. (They predated the name "C++.") They predated templates as well as the standard container types like vector that templates made possible. In those early days there was little or no allowance for manual construction/destruction as a separate operation from new and delete (e.g. there was no placement-new). Nested classes were also not supported.
All in all, there was no question of ever needing to refer to the destructor except as part of its definition, and no question that there would be any doubt or complexity in forming the destructor's identifier.
Naming the constructor after the class fits with C's general tendency for declarations to resemble the usage of the things they declare (e.g. int *a(int b) results in something where *a(b) is well-formed). The destructor is conceptually linked to the constructor, so it would be weird for the class name to show up in the constructor but not the destructor. And with no support for operator overloading (at the time) beyond operator=, there was no question of confusing ~classname with an overloaded operator~. So it was a simple, low-stakes, mildly witty syntax detail.
|
73,686,952
| 73,689,453
|
Unexpected behaviour from multiple bitwise shift operators in an expression
|
I noticed that a program that I was writing was not working correctly so I wrote a simple test to check if the problem was the binary shifting.
The code is the following:
#include <iostream>
#include <Windows.h>
#include <bitset>
using namespace std;
int main(){
BYTE byte = 0b10010000; //This is 2^7 + 2^4 = 144
cout << "This is the binary number 10010000: " << endl << "Numerical value: " << (unsigned short int) byte << endl << "Binary string: " << bitset<8>(byte) << endl;
byte = byte << 1;
cout << "Shifted left by 1 with << 1:" << endl << "Numerical value: " << (unsigned short int) byte << endl << "Binary string: " << bitset<8>(byte) << endl;
byte = byte >> 5;
cout << "Shifted right by 5 with >> 5: " << endl << "Numerical value: " << (unsigned short int) byte << endl << "Binary string: " << bitset<8>(byte) << endl;
byte = 0b10010000;
byte = (byte << 1) >> 5; //Expect to store 00000001 inside byte
cout << "But what happens if I do it all in one line? " << endl << "Numerical value: " << (unsigned short int) byte << endl << "Binary string: " << bitset<8>(byte) << endl;
return 0;
}
Output produced
By running it, the following output is produced:
This is the binary number 10010000:
Numerical value: 144
Binary string: 10010000
Shifted left by 1 with << 1:
Numerical value: 32
Binary string: 00100000
Shifted right by 5 with >> 5:
Numerical value: 1
Binary string: 00000001
But what happens if I do it all in one line?
Numerical value: 9
Binary string: 00001001
What I was expecting
I expected the last messages printed by cout would be:
But what happens if I do it all in one line?
Numerical value: 1
Binary string: 00000001
But surprisingly enough, this wasn't the case.
Can someone explain to me why does this happen? I tried checking microsoft documentation but found nothing.
Additional info:
The type BYTE is defined here: https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types
|
You are experiencing the effects of integer promotion.
The operation byte << 1 does not produce an unsigned char, despite byte being of that type. The rationale is that hardware usually cannot perform a number of operations on small types (below a machine word) so C++ inherited from C the concept of promoting data types in operations to larger types.
So since the result is not 8 bits but, probably, 32 bits, the most significant bit is not shifted out but preserved. After you shift the 32 bit value back and implicitly convert it back to an unsigned char the bit is back in your output.
|
73,686,971
| 74,124,253
|
Azure TTS generating garbled result when requesting Opus encoding
|
The following sample code (C++, Linux, x64) uses the MS Speech SDK to request a text-to-speech of a single sentence in Opus format with no container. It then uses the Opus lib to decode to raw PCM. Everything seems to run with no errors but the result sounds garbled, as if some of the audio is missing, and the result Done, got 14880 bytes, decoded to 24000 bytes looks like this might be a decoding issue rather than an Azure issue as I'd expect a much higher compression ratio.
Note that this generates a raw PCM file, play back with: aplay out.raw -f S16_LE -r 24000 -c 1
#include <stdio.h>
#include <string>
#include <assert.h>
#include <vector>
#include <speechapi_cxx.h>
#include <opus.h>
using namespace Microsoft::CognitiveServices::Speech;
static const std::string subscription_key = "abcd1234"; // insert valid key here
static const std::string service_region = "westus";
static const std::string text = "Hi, this is Azure";
static const int sample_rate = 24000;
#define MAX_FRAME_SIZE 6*960 // from Opus trivial_example.c
int main(int argc, char **argv) {
// create Opus decoder
int err;
OpusDecoder* opus_decoder = opus_decoder_create(sample_rate, 1, &err);
assert(err == OPUS_OK);
// create Azure client
auto azure_speech_config = SpeechConfig::FromSubscription(subscription_key, service_region);
azure_speech_config->SetSpeechSynthesisVoiceName("en-US-JennyNeural");
azure_speech_config->SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat::Audio24Khz16Bit48KbpsMonoOpus);
auto azure_synth = SpeechSynthesizer::FromConfig(azure_speech_config, NULL);
FILE* fp = fopen("out.raw", "w");
int in_bytes=0, decoded_bytes=0;
// callback to capture incoming packets
azure_synth->Synthesizing += [&in_bytes, &decoded_bytes, fp, opus_decoder](const SpeechSynthesisEventArgs& e) {
printf("Synthesizing event received with audio chunk of %zu bytes\n", e.Result->GetAudioData()->size());
auto audio_data = e.Result->GetAudioData();
in_bytes += audio_data->size();
// confirm that this is exactly one valid Opus packet
assert(opus_packet_get_nb_frames((const unsigned char*)audio_data->data(), audio_data->size()) == 1);
// decode the packet
std::vector<uint8_t> decoded_data(MAX_FRAME_SIZE);
int decoded_frame_size = opus_decode(opus_decoder, (const unsigned char*)audio_data->data(), audio_data->size(),
(opus_int16*)decoded_data.data(), decoded_data.size()/sizeof(opus_int16), 0);
assert(decoded_frame_size > 0); // confirm no decode error
decoded_frame_size *= sizeof(opus_int16); // result size is in samples, convert to bytes
printf("Decoded to %d bytes\n", decoded_frame_size);
assert(decoded_frame_size <= (int)decoded_data.size());
fwrite(decoded_data.data(), 1, decoded_frame_size, fp);
decoded_bytes += decoded_frame_size;
};
// perform TTS
auto result = azure_synth->SpeakText(text);
printf("Done, got %d bytes, decoded to %d bytes\n", in_bytes, decoded_bytes);
// cleanup
fclose(fp);
opus_decoder_destroy(opus_decoder);
}
|
I've received no useful response to this question (I've also asked here and here and even tried Azure's paid support) so I gave up and switched from Audio24Khz16Bit48KbpsMonoOpus to Ogg48Khz16BitMonoOpus which means the Opus encoding is wrapped in an Ogg container, requiring the rather cumbersome libopusfile API to decode. It was kind of a pain to implement but it does the job.
|
73,687,220
| 73,687,984
|
How can I pass a member function pointer type to a template?
|
I am trying to delegate a method call using a nested std::invoke. Sample code:
class Executor
{
public:
bool Execute(bool someFlag);
};
template <class TMemberFunction, class TInstance, typename TResponse>
class Invoker
{
public:
TResponse Invoke(TMemberFunction* function, TInstance* instance, bool someFlag) {
return std::invoke(function, instance, someFlag);
}
};
void Main()
{
// Create an executor
Executor executor;
bool someFlag = true;
// How can I pass the member function type here?
Invoker<???, Executor, bool> invoker;
// Invoke member method
bool response = invoker.Invoke(&Executor::Execute, &executor, someFlag);
}
What's the proper way to pass the member function's type to the Invoker template?
Edit: sample code corrections.
|
You might write your Invoker class like:
template <typename TMemberFunction>
class Invoker;
template <class C, typename Ret, typename... Args>
class Invoker<Ret (C::*) (Args...)>
{
public:
Ret Invoke(Ret (C::*method) (Args...), C* instance, Args... args) {
return std::invoke(method, instance, std::forward<Args>(args)...);
}
};
template <class C, typename Ret, typename... Args>
class Invoker<Ret (C::*) (Args...) const>
{
public:
Ret Invoke(Ret (C::*method) (Args...) const, const C* instance, Args... args) {
return std::invoke(method, instance, std::forward<Args>(args)...);
}
};
// other specializations to handle combination of volatile, ref, c-ellipsis
and than use it:
int main()
{
Executor executor;
Invoker <bool (Executor::*)(bool)> invoker;
bool response = invoker.Invoke(&Executor::Execute, &executor, true);
// ..
}
|
73,687,747
| 73,687,870
|
How to convert c-style define of "<>::value" to "c++ template"
|
I have a 100% working code, which uses C style #defines, but should be converted to c++ style (using=) because this is the style of the rest of the code.
I am not proficient in C++ and struggling to convert the ::value notation.
My code checks if container (like vector/set/map) and its element use the same allocator.
template <typename Cont, typename elem>
using allocIsRecursive = typename std::uses_allocator<elem, typename Cont::allocator_type>;
template <typename Cont>
using allocIsTrivial = typename std::uses_allocator<Cont, std::allocator<char>>;
// Here are 2 defines which I wrote and am struggling to convert....
#define allocShouldPropagate(Cont, elem) \
(allocIsRecursive<Cont, typename Cont::elem>::value && !allocIsTrivial<Cont>::value)
#define allocShouldPropagateMap(Map) (allocShouldPropagate(Map, key_type) || allocShouldPropagate(Map, mapped_type))
*~~~~~~~~~~~~~~~~~~~~~
More context:
The code is used when inserting new element into a container via default empty constructor. If container should be propagated, an allocator aware constructor is used instead.
Example for vector:
template <typename C>
std::enable_if_t<allocShouldPropagate(C, value_type), typename C::value_type>
defaultVectorElement(C& c) {
return typename C::value_type{c.get_allocator()};
}
template <typename C>
std::enable_if_t<!allocShouldPropagate(C, value_type), typename C::value_type>
defaultVectorElement(C& c) {
return typename C::value_type{};
}
Note: std::scoped_allocator_adaptor<> does something similar to simple containers but it does not work well for complicated containers, like maps, hashtables, + it has a measurable cpu penalty.
|
Is this what you are looking for?
template <typename Cont, typename elem>
constexpr bool allocIsRecursive_v = std::uses_allocator<elem, typename Cont::allocator_type>::value;
template <typename Cont>
constexpr bool allocIsTrivial_v = std::uses_allocator<Cont, std::allocator<char>>::value;
template <typename Cont, typename elem>
constexpr bool allocShouldPropagate_v = allocIsRecursive_v<Cont, typename Cont::elem> && !allocIsTrivial_v<Cont>;
template <typename Map>
constexpr bool allocShouldPropagateMap_v = allocShouldPropagate_v<Map, typename Map::key_type> || allocShouldPropagate_v<Map, typename Map::value_type>;
Then in your usecase you'd change allocShouldPropagate(C, value_type) to allocShouldPropagate_v<C, typename C::value_type>.
|
73,688,015
| 73,688,950
|
How to get the compositor instance while handling XamlCompositionBrushBase.OnConnected in a WinUI-3 desktop app
|
Following this c++ example i'm trying to create a custom brush in a WinUI 3 desktop application but i cannot find out how to get a compositor instance from within the OnConnected Method.
The example uses
Microsoft::UI::Xaml::Window::Current().Compositor()
but Current (and CoreWindow) are always null for desktop apps.
How can i get the compositor instance needed to create brushes?
|
Ok, as often it gets easy as soon as the matching documentation is found:
In XAML apps, we recommend that you call
ElementCompositionPreview.GetElementVisual(UIElement) to get a
Composition Visual, and get the Compositor from the visual's
Compositor property. In cases where you don't have access to a
UIElement (for example, if you create a CompositionBrush in a class
library), you can call CompositionTarget.GetCompositorForCurrentThread
to get the Compositor instead.
Related issue.
Related Issue.
|
73,688,057
| 73,689,847
|
Cannot use consteval functions inside initializer list on MSVC
|
Consider that minimized code snippet:
#include <vector>
class Bar
{
public:
constexpr Bar() {}
};
consteval Bar foo()
{
return Bar();
}
int main()
{
std::vector<Bar> bars{ foo(), foo() };
}
This doesn't compile on latest MSVC compiler (Visual Studio 2022 version 17.3.3), but does on Clang or GCC.
Compiler Explorer
Is the code somewhere ill formed, or it is a bug in MSVC?
|
From the comments, it looks like this is indeed a bug in MSVC.
Therefore I filled in a bug report on Visual Studio Community.
https://developercommunity.visualstudio.com/t/Cannot-use-consteval-functions-returning/10145209
|
73,688,375
| 73,688,644
|
Unable to call dynamic library in Unity 3D
|
Wrote a library for displaying system messages in C++
.h
#pragma once
#ifndef WINDOW_DEFINDE_DEBUG
#define WINDOW_DEFINDE_DEBUG
#include <Windows.h>
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef BUILD_LIBRARY
#define SHARED_LIBRARY_DECLSPEC __declspec(dllexport)
#else
#define SHARED_LIBRARY_DECLSPEC __declspec(dllimport)
#endif
int SHARED_LIBRARY_DECLSPEC DebugWindowInformation(std::string message, std::string caption);
int SHARED_LIBRARY_DECLSPEC DebugWindowQuestion(std::string message, std::string caption);
int SHARED_LIBRARY_DECLSPEC DebugWindowWarning(std::string message, std::string caption);
int SHARED_LIBRARY_DECLSPEC DebugWindowError(std::string message, std::string caption);
#ifdef __cplusplus
}
#endif
#endif
.cpp
#include "window_debug.h"
#define BUILD_LIBRARY
int SHARED_LIBRARY_DECLSPEC DebugWindowInformation(std::string message, std::string caption)
{
std::wstring _message = std::wstring(message.begin(), message.end());
std::wstring _caption = std::wstring(caption.begin(), caption.end());
return MessageBox(NULL, (LPCWSTR)_message.c_str(), (LPCWSTR)_caption.c_str(),
MB_ICONINFORMATION | MB_OK | MB_DEFBUTTON1);
}
int SHARED_LIBRARY_DECLSPEC DebugWindowQuestion(std::string message, std::string caption)
{
std::wstring _message = std::wstring(message.begin(), message.end());
std::wstring _caption = std::wstring(caption.begin(), caption.end());
return MessageBox(NULL, (LPCWSTR)_message.c_str(), (LPCWSTR)_caption.c_str(),
MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON3);
}
int SHARED_LIBRARY_DECLSPEC DebugWindowWarning(std::string message, std::string caption)
{
std::wstring _message = std::wstring(message.begin(), message.end());
std::wstring _caption = std::wstring(caption.begin(), caption.end());
return MessageBox(NULL, (LPCWSTR)_message.c_str(), (LPCWSTR)_caption.c_str(),
MB_ICONWARNING | MB_OK | MB_DEFBUTTON1);
}
int SHARED_LIBRARY_DECLSPEC DebugWindowError(std::string message, std::string caption)
{
std::wstring _message = std::wstring(message.begin(), message.end());
std::wstring _caption = std::wstring(caption.begin(), caption.end());
return MessageBox(NULL, (LPCWSTR)_message.c_str(), (LPCWSTR)_caption.c_str(),
MB_ICONERROR | MB_OK | MB_DEFBUTTON1);
}
I'm trying to call the library functions through Unity, nothing happens. No errors, nothing at all. Maybe I'm doing something wrong?
C#
namespace Assets.Scripts.InvokeCallFunc
{
public static class CallFunc
{
[DllImport(@"C:\Users\mrxit\Downloads\King Of Kings 3\Project\eh_handler32_64.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int DebugWindowInformation([MarshalAs(UnmanagedType.BStr)] string message, [MarshalAs(UnmanagedType.BStr)] string caption);
[DllImport(@"C:\Users\mrxit\Downloads\King Of Kings 3\Project\eh_handler32_64.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int DebugWindowQuestion([MarshalAs(UnmanagedType.BStr)] string message, [MarshalAs(UnmanagedType.BStr)] string caption);
[DllImport(@"C:\Users\mrxit\Downloads\King Of Kings 3\Project\eh_handler32_64.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int DebugWindowWarning([MarshalAs(UnmanagedType.BStr)] string message, [MarshalAs(UnmanagedType.BStr)] string caption);
[DllImport(@"C:\Users\mrxit\Downloads\King Of Kings 3\Project\eh_handler32_64.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int DebugWindowError([MarshalAs(UnmanagedType.BStr)] string message, [MarshalAs(UnmanagedType.BStr)] string caption);
}
}
Later, I try to call these functions in my code. For a test. Nothing comes out in the messages on Unity. I threw the library into Assets and into the root project and into Plugins. All the same.
|
C# cannot marshal System.String as std::string because there different classes.
UnmanagedType.BStr in C# is BSTR in Windows SDK.
And you've set SetLastError = true, so when nothing comes out, you should call Marshal.GetLastWin32Error to get error.
In fact you can use this method to call MessageBox.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
|
73,689,747
| 73,690,534
|
Why calling future.get() retrieved from async leads to unexpected output order
|
Consider the following code:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <future>
std::mutex mutex;
int generate()
{
static int id = 0;
std::lock_guard<std::mutex> lock(mutex);
id++;
std::cout << id << '\n';
return id;
}
int main()
{
std::vector<std::future<int>> vec;
std::vector<int> result;
for(int i = 0; i < 10; ++i)
{
vec.push_back(std::async(std::launch::async,generate));
}
for(int i = 0; i < 10; ++i)
{
result.push_back(vec[i].get());
}
std::cout << "\n result:";
for(const auto res : result)
{
std::cout << res << " ";
}
}
Which produces following output:
1
2
3
4
5
6
7
8
9
10
result:1 2 3 6 4 5 7 8 9 10
As you can see, the output inside generate() function has correct (from 1 to 10) order. But when iterating over the result vector I'm getting different order each run. Why is this happening and how can I synchronize such code?
|
What you're seeing in the final output is the order in which the threads produced their results.
Consider these three threads as a simplified version:
+- -+ +- -+ +- -+
Thread | 1 | | 2 | | 3 |
+- -+ +- -+ +- -+
Result | | | | | |
+- -+ +- -+ +- -+
Now, no matter which order these execute and acquire the mutex in, the output will be
1 2 3
because id is static, and the first "locker" increments it and prints "1", then the second increments it and prints "2", and so on.
Let's assume that Thread 3 gets the mutex first, then 1, then 2.
That leads to this situation:
+- -+ +- -+ +- -+
Thread | 1 | | 2 | | 3 |
+- -+ +- -+ +- -+
Result | 2 | | 3 | | 1 |
+- -+ +- -+ +- -+
And when you print the results in "vector order", you will see
2 3 1
If you want threads to execute in some predetermined order, you need to synchronize them further.
|
73,689,914
| 73,691,046
|
How do I check whether an IntegerVector contains NA values in Rcpp?
|
I wish to check that an Rcpp IntegerVector provided to a C++ function does not contain NA values.
Following another answer, I have written the below:
IntegerMatrix stop_if_na(const IntegerVector I) {
if (Rcpp::is_true(Rcpp::any(Rcpp::IntegerVector::is_na(I)))) {
Rcpp::stop("`I` contains NA values");
}
But I see a compilation error:
note: candidate: 'template<bool NA, class T> bool Rcpp::is_na(const Rcpp::sugar::SingleLogicalResult<NA, T>&)'
38 | inline bool is_na( const Rcpp::sugar::SingleLogicalResult<NA,T>& x){
| ^~~~~
note: template argument deduction/substitution failed:
<file>.cpp:22:48 note: 'const IntegerVector' {aka 'const Rcpp::Vector<13, Rcpp::PreserveStorage>'} is not derived from 'const Rcpp::sugar::SingleLogicalResult<NA, T>'
22 | if (Rcpp::is_true(Rcpp::any(Rcpp::is_na(I)))) {
| ^
When I remove IntegerVector:: (as suggested by user20650 and Dirk Eddelbuettel) I see
error: matching function for call to 'is_na(const IntegerVector&)
20 | if (Rcpp::is_true(Rcpp::any(Rcpp::is_na(I)
|
template argument deduction/substitution failed:
<file>.cpp:20:48:note: 'const IntegerVector{aka 'const note: ndidate: 'template<bool NA, class T> bool Rcpp::is_na(const Rcpp::sugar::SingleLogicalResult<NA, T>&)
38 | inline bool is_nast Rcpp::sugar::SingleLogicalResult<NA,T>& x){
| ^~~~~
note: template argument deduction/substitution failed:
<file>.cpp:20:48:note: 'const IntegerVector{aka 'const Rcpp::Vector<13, Rcpp::PreserveStorage> is not derived from 'const Rcpp::sugar::SingleLogicalResult<NA, T>
20 | if (Rcpp::is_true(Rcpp::any(Rcpp::is_na(I)
| ^
(As the C++ function is exported from a package, I can't rely on the calling R function to perform this test.)
sessionInfo() output
R Under development (unstable) (2022-07-19 r82607 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)
Matrix products: default
locale:
[1] LC_COLLATE=English_United Kingdom.utf8 LC_CTYPE=English_United Kingdom.utf8
[3] LC_MONETARY=English_United Kingdom.utf8 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.utf8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] htmlwidgets_1.5.4 compiler_4.3.0 microbenchmark_1.4.9 magrittr_2.0.3
[5] fastmap_1.1.0 cli_3.3.0 profvis_0.3.7 tools_4.3.0
[9] htmltools_0.5.3 rstudioapi_0.13 stringi_1.7.8 stringr_1.4.0
[13] digest_0.6.29 rlang_1.0.4
packageVersion("Rcpp") = 1.0.9
|
This is so core a feature that we had it more or less since day one, and I am a little surprised that you did not come across the very early Rcpp Gallery posts Working with Missing Values by Hadley from Dec 2012.
Note that the more interesting features are 'Sugar' functions:
> Rcpp::cppFunction("LogicalVector foo(NumericVector x) {return is_finite(x);}")
> foo(c(1.0, Inf, -Inf, NA, NaN, 42))
[1] TRUE FALSE FALSE FALSE FALSE TRUE
>
There are a few related predicates you may want to look into.
Your suggested function also works if you just remove the ::IntegerVector in the call:
> Rcpp::cppFunction("void stop_if_na(const IntegerVector IV) {
+ if (Rcpp::is_true(Rcpp::any(Rcpp::is_na(IV)))) {
+ Rcpp::stop(\"`I` contains NA values\");
+ }
+ }")
> stop_if_na(1:5)
> stop_if_na(c(1:5, NA, 7:9))
Error: `I` contains NA values
>
For ease of re-use my code snippet follows.
Rcpp::cppFunction("LogicalVector foo(NumericVector x) { return is_finite(x); }")
foo(c(1.0, Inf, -Inf, NA, NaN, 42))
Rcpp::cppFunction("void stop_if_na(const IntegerVector IV) {
if (Rcpp::is_true(Rcpp::any(Rcpp::is_na(IV)))) {
Rcpp::stop(\"`I` contains NA values\");
}
}")
stop_if_na(1:5)
stop_if_na(c(1:5, NA, 7:9))
|
73,689,916
| 73,690,555
|
Build initializer list for array by repeating n times
|
I have a std:array something like this:
class MyClass {
private:
std::array<MyComplexType, 10> myArray;
}
In the constructor, I need to do the following:
MyClass::MyClass() : myArray({
MyComplexType(func(const_arg1, const_arg2, const_arg3).method(const_arg4)),
... repeated 8 more times...
MyComplexType(func(const_arg1, const_arg2, const_arg3).method(const_arg4))
})
Now, I want the 10 to be a compile-time constant that I can modify without having to copy&paste more (or less) of those initializers. They are all the same, I just need a "repeat n times". Everything up to and including C++17 is fair game.
I am 99.9% certain this should be doable with some template magic, but so far I came up with nothing that worked. Any ideas?
(And if it is impossible with templates, maybe with macros? Though I would hate having to go that direction...)
|
If you want to use a std::array you are going to need to build a helper function, namely a delegating constructor. Your default constructor will then call the delegate to actually initialize the member. That can look like
class MyClass {
public:
// default c'tor, create sequence of 10 integers
MyClass() : MyClass(std::make_index_sequence<10>{})
private:
// delegate, take a sequence and expand the initializer of myArray sizeof...(Is) times
template <std::size_t... Is>
MyClass(std::index_sequence<Is...>) :
myArray{ (Is, MyComplexType(func(const_arg1, const_arg2, const_arg3).method(const_arg4)))... } {}
std::array<MyComplexType, 10> myArray;
}
You can instead change myArray to be a vector instead and that would let you simplify the code to
class MyClass {
public:
MyClass() :
myData(MyComplexType(func(const_arg1, const_arg2, const_arg3).method(const_arg4)), 10) {}
private:
std::vector<MyComplexType> myData;
}
|
73,690,149
| 73,848,790
|
Why are reference members of closure types needed?
|
[expr.prim.lambda.capture]/12:
An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference. If declared, such non-static data members shall be of literal type.
The closure types have direct access to objects, so why are the reference members sometimes needed? It even only requires the members to be of literal type, why?
|
This wording is talking about the struct layout of the closure type. A lambda-expression corresponds to a struct-whose-name-you-don't-know which is basically
class Unnameable {
~~~data members~~~
public:
auto operator()(~~~args~~~) const { ~~~body~~~ }
};
where all of the ~~~ bits are filled in based on the form of the lambda. For example, the lambda [=](int x) { return x+y; } (where y is an int captured from the outer scope) is going to correspond to a struct layout like this:
class Unnameable {
int y;
public:
auto operator()(int x) const { return x+y; }
};
When the capture of y happens by copy, this transformation is pretty obvious. (The circumstances under which capture-by-copy happens are described a few lines above the part you quoted.) But, when the capture of y happens by reference, the transformation is not obvious. The compiler could just lower it into
class Unnameable {
int& y;
public:
auto operator()(int x) const { return x+y; }
};
but then class Unnameable wouldn't be copy-assignable, and in fact the closure object does need to be copy-assignable [Oops — no, closures are not assignable! So actually I'm not sure why this wouldn't Just Work. But see the clever technique below, anyway]. So, the compiler actually lowers it into something more like
class Unnameable {
int *py;
public:
auto operator()(int x) const { return x + *py; }
};
This is why the wording is so coy about exactly what "additional unnamed non-static data members are declared in the closure type for entities captured by reference." All it guaranteed is that "If declared, such non-static data members shall be of literal type" (i.e., they won't accidentally make the closure object non-constexpr-friendly).
Now, the wording in the Standard actually allows a "sufficiently smart compiler" to go even further — although no vendor actually does, AFAIK. Suppose the lambda in question is this one:
int a = 1, b = 2;
auto lam = [&]() { return a + b; };
std::function<int()> f = lam;
a = 3;
assert(f() == 5);
Since the compiler happens to know the layout of a and b on the function's stack frame, it is totally permitted for the compiler to generate a closure type with this struct layout:
class Unnameable {
int *p; // initialized with &a, which happens to be &b-1
public:
auto operator()() const { return p[0] + p[1]; }
};
The Standard could forbid this implementation by saying something like, "For each entity captured by reference, an unnamed non-static data member is declared in the closure type. If the entity is of type T, then the type of such a data member is 'pointer to remove_cvref_t<T>.'" But that would forbid this kind of clever implementation technique, so, they just left it unspecified.
|
73,690,647
| 73,690,832
|
Base class default constructor in derived class constructor initializer list
|
I have seen a lot of times people adding the default constructor of base class in the derived class constructor initializer list like so
DerivedClass::DerivedClass(int x) : BaseClass(), member_derived(x)
{
//Do something;
}
Derived class constructor by default calls the default constructor of base class. Is the BaseClass() in the above initializer list redundant?
|
It depends on declaration of base class. Constructor of derived class actually initializes base class. It involves default constructor call if such is present. If base class is trivial, it wouldn't be initialized. Consider this code:
#include <iostream>
struct Base {
int c;
};
class Derived : public Base {
public:
Derived() : Base()
{}
};
int main()
{
Derived d;
std::cout << d.c << std::endl;
}
If you would comment : Base() out, you may get compiler warning, or a random value printed.
prog.cc: In function 'int main()':
prog.cc:17:20: warning: 'd.Derived::<anonymous>.Base::c' is used uninitialized [-Wuninitialized]
17 | std::cout << d.c << std::endl;
| ^
prog.cc:16:13: note: 'd' declared here
16 | Derived d;
in this case : Base() ensures value initialization of Base
|
73,690,983
| 73,713,805
|
cxxrt::bad_alloc despite large EPC
|
I am running the following piece of code inside an SGX enclave:
void test_enclave_size() {
unsigned int i = 0;
const unsigned int MB = 1024 * 1024;
try {
for (; i < 10000; i++) {
char* tmp = new char[MB];
}
} catch (const std::exception &e) {
std::cout << "Crash with " << e.what() << " " << i << std::endl;
}
}
On my dev machine with the standard 128 MB EPC this throws a bad cxxrt::bad_alloc after 118 MB, which makes sense because I believe only 96 MB is guaranteed to be available for enclave programs. However, when running this code on a Standard_DC32s_V3, which has 192 GB of EPC memory, I get the exact same result. I assumed that because the EPC is advertised to be extremely large, I should be able to allocate far more than 128 MB.
I have thought of a couple of reasons why this might be happening:
While the EPC is now 192 GB in size, each process is still limited to 128 MB.
There is something in the kernel that needs to be enabled for me to take advantage of this large EPC.
I am misunderstanding what Azure is advertising.
I wanted to see if anyone has a good idea of what is happening before contact Azure support, since this might be a user error.
Edit:
It turns out my second reason was the closest. As X99 pointed out, when developing an enclave application there is a configuration file that defines several factors such as the number of thread contexts, whether debugging is enabled, and max heap/stack size. My maximum heap size in my configuration was set to about 118 MB, which explains why I started to get bad allocations past this amount. Once I increased the number, the issue went away. Size note: if you are on Linux, the drivers support paging. This means you can use as much memory as you wish if you can afford to suffer the paging overhead.
If you are using Open Enclave as your SDK, this configuration file (example) is what you should be editing. In this example, the maximum heap and stack are 1024 pages, which is about 4MB. This page may be useful to you as well!
|
If the machine you're running your enclave on has more than 128Mb of EPC AND will allow you to go further (because of a BIOS setting), there is one more setting you must fiddle with, in your Enclave.config.xml file:
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>0</ISVSVN>
<StackMaxSize>0x40000</StackMaxSize>
<HeapMaxSize>0x100000</HeapMaxSize>
<TCSNum>10</TCSNum>
<TCSPolicy>1</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug>
<MiscSelect>0</MiscSelect>
<MiscMask>0xFFFFFFFF</MiscMask>
</EnclaveConfiguration>
To be more specific, the HeapMaxSize value. See the SGX developper reference, page 58/59.
|
73,690,998
| 73,694,596
|
Redirect cerr using rdbuf: set it once and forget it until app ends
|
I am attempting to redirect cerr to a file at the start of a program, then at the end of the program set it back to normal. This is along the lines of the accepted answer of Use cout or cerr to output to console after it has been redirected to file
I am running into strange behavior in C++Builder for this. The environment seems to want me to refresh the stream redirection every time the program wants to output something.
I created the following test app to demonstrate the problem. If I comment out the #define on the first line, I get memory access violations. When the #define is uncommented, it seems to work fine while the program is executing; however, in a larger program, I believe I have also gotten the same memory access violations after the application terminates (works fine during execution with that #define in there – I still need to explore that one some more to track it down).
//#define MAKE_WORK
#include <vcl.h>
#pragma hdrstop
#include <fstream>
#include "TestRdbuf.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
std::streambuf* origBuff;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
std::ofstream oFile("ErrorLog.txt");
origBuff = std::cerr.rdbuf();
std::cerr.rdbuf(oFile.rdbuf());
std::cerr << "Started: " << Now() << std::endl;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
#ifdef MAKE_WORK
std::ofstream oFile("ErrorLog.txt", std::ios_base::app);
std::cerr.rdbuf(oFile.rdbuf());
#endif
std::cerr << "Closing:" << Now() << std::endl;
std::cerr.rdbuf(origBuff);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
#ifdef MAKE_WORK
std::ofstream oFile("ErrorLog.txt", std::ios_base::app);
std::cerr.rdbuf(oFile.rdbuf());
#endif
std::cerr << "Debug log time: " << Now() << std::endl;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btnShowFileClick(TObject *Sender)
{
TMemo * Memo = new TMemo(pnlBody);
Memo->Parent = pnlBody;
Memo->Align = TAlign::alClient;
Memo->Font->Size = 12;
Memo->Lines->LoadFromFile("ErrorLog.txt");
Memo->ReadOnly = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
#ifdef MAKE_WORK
std::ofstream oFile("ErrorLog.txt", std::ios_base::app);
std::cerr.rdbuf(oFile.rdbuf());
#endif
std::cerr << "Exit clicked: " << Now() << std::endl;
Application->Terminate();
}
//---------------------------------------------------------------------------
|
First off, DO NOT use the Form's OnCreate event in C++. It is a Delphi idiom that introduces undefined behavior in C++, as it can be triggered before the Form's constructor, so use the actual constructor instead. Likewise, the Form's OnDestroy event can be triggered after the Form's destructor, so use the actual destructor instead.
Second, more importantly, oFile is a local variable. You are setting cerr to share the same streambuf object as oFile, but then oFile goes out of scope afterwards and is destroyed, which also destroys its streambuf object, leaving cerr holding a dangling pointer to invalid memory, hence the Access Violations.
You need to keep the ofstream object alive while cerr is sharing its streambuf object, eg:
#include <vcl.h>
#pragma hdrstop
#include <fstream>
#include "TestRdbuf.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
std::ofstream oFile;
std::streambuf* origBuff;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
oFile.open("ErrorLog.txt");
origBuff = std::cerr.rdbuf();
std::cerr.rdbuf(oFile.rdbuf());
std::cerr << "Started: " << Now() << std::endl;
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
std::cerr << "Closing:" << Now() << std::endl;
std::cerr.rdbuf(origBuff);
oFile.close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
std::cerr << "Debug log time: " << Now() << std::endl;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btnShowFileClick(TObject *Sender)
{
TMemo *Memo = new TMemo(pnlBody);
Memo->Parent = pnlBody;
Memo->Align = TAlign::alClient;
Memo->Font->Size = 12;
Memo->Lines->LoadFromFile("ErrorLog.txt");
Memo->ReadOnly = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
std::cerr << "Exit clicked: " << Now() << std::endl;
Application->Terminate();
}
//---------------------------------------------------------------------------
|
73,691,670
| 73,691,841
|
Simple C++ multithreading example is slower
|
I am currently learning basic C++ multithreading and I implemented a very small code to learn the concepts. I keep hearing multithreading is faster so I tried the below :
int main()
{
//---- SECTION 1
Timer timer;
Func();
Func();
//---- SECTION 2
Timer timer;
std::thread t(Func);
Func();
t.join();
}
And below is the Timer,
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
//To get duration in MilliSeconds
float ms = duration.count() * 1000.0f;
std::cout << "Timer : " << ms << " milliseconds\n";
}
When I implement Section 1 (the other commented out), I get times of 0.1ms,0.2ms and in that range but when I implement Section 2, I get 1ms and above. So it seems that Section 1 is faster even though it is running on the main thread but the Section 2 seems to be slower.
Your answers would be much appreciated. If I am wrong in regards to any concepts, your help would be helpful.
Thanks in advance.
|
Multithreading can mean faster, but it does not always mean faster. There are many things you can do in multithreaded code which can actually slow things down!
This example shows one of them. In this case, your Func() is too short to benefit from this simplistic multi threading example. Standing up a new thread involves calls to the operating system to manage these new resources. These calls are quite expensive when compared with the 100-200us of your Func. It adds what are called "context switches," which are how the OS changes from one thread to another. If you used a much longer Func (like 20x or 50x longer), you would start to see the benefits.
How big of a deal are these context switches? Well, if you are CPU bound, doing computations as fast as you can, on every core of the CPU, most OSs like to switch threads every 4 milliseconds. That seems to be a decent tradeoff between responsiveness and minimizing overhead. If you aren't CPU bound (like when you finish your Func calls and have nothing else to do), it will obviously switch faster than that, but it's a useful number to keep in the back of your head when considering the time-scales threading is done at.
If you need to run a large number of things in a multi-threaded way, you are probably looking at a dispatch-queue sort of pattern. In this pattern, you stand up the "worker" thread once, and then use mutexes/condition-variables to shuffle work to the worker. This decreases the overhead substantially, especially if you can queue up enough work such that the worker can do several tasks before context switching over to the threads that are consuming the results.
Another thing to watch out for, when starting on multi threading, is managing the granularity of the locking mechanisms you use. If you lock too coarsely (protecting large swaths of data with a single lock), you can't be concurrent. But if you lock too finely, you spend all of your time managing the synchronization tools rather than doing the actual computations. You don't get benefits from multi threading for free. You have to look at your problem and find the right places to do it.
|
73,692,981
| 73,722,142
|
Only last wxStaticBitmap is showing
|
The same image is meant to be shown in different locations but only the second one is shown, why?
void AppFrame::OnButtonClicked(wxCommandEvent& evt) {
Tiles* knots = new Tiles(panel, 1);
string tile = knots->firstTile();
ImagePanel* drawPane = new ImagePanel(panel, tile, wxBITMAP_TYPE_PNG);
wxStaticBitmap* image1 = new wxStaticBitmap(panel, wxID_ANY, drawPane->getImage(),wxPoint(Background::defaultStartX, Background::defaultStartY), wxSize(100, 100));
wxStaticBitmap* image2 = new wxStaticBitmap(panel, wxID_ANY, drawPane->getImage(),wxPoint(Background::defaultStartX+100, Background::defaultStartY), wxSize(100, 100));
}
|
You don't position your ImagePanel and depending on its size it can overlap the first bitmap. Generally speaking, using hard-coded position in pixels is strongly discouraged, you should let the controls use their natural size and position them using sizers as already mentioned in a comment.
|
73,693,001
| 73,693,166
|
How to use std::replace_if to replace elements with its incremented value?
|
I am trying to write a std::replace_if function that takes in a string and replaces all the vowels with a consonant on its right.
How to capture the current iterating character from the string and replace it with its incremented value using a lambda within std::replace_if function
Example :
input : aeiou
output : bfjpv
Assume all characters to be lowercase
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str;
std::cin >> str;
std::replace_if(
str.begin(), str.end(), [&](char c)
{ return std::string("aeiou").find(c) != std::string::npos; },
[&](char c)
{ return static_cast<char>(c + 1); });
std::cout << str;
}
|
std::replace_if cannot do what you want. It accepts only a single new value.
To do what you want either use std::for_each:
std::for_each(
str.begin(),
str.end(),
[](char& c) {
if (std::string("aeiou").find(c) != std::string::npos) {
c = c + 1;
}
}
);
Demo
Or use a normal loop:
for (char& c : str) {
if (std::string("aeiou").find(c) != std::string::npos) {
c = c + 1;
}
}
Demo
|
73,693,061
| 73,693,643
|
What's the best way to pass a r-value/temporary collection to a function taking a std::span?
|
I've been trying to start using std::span<const T> in places where I would have previously used const std::vector<T>&. The only sticking point I have is illustrated in the following:
#include <iostream>
#include <vector>
#include <span>
#include <numeric>
double mean1(std::span<const double> vals) {
return std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size();
}
double mean2(const std::vector<double>& vals) {
return std::accumulate(vals.begin(), vals.end(), 0.0) / vals.size();
}
int main() {
std::vector<double> foo = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
auto v = mean1(foo);
std::cout << v << "\n";
v = mean2( { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } );
std::cout << v << "\n";
v = mean1({ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } ); // << this is an error
std::cout << v << "\n";
}
I know that passing std:vector{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } would work but that is pretty verbose. initializer_list is even more verbose. Just wondering if I am missing something obvious here.
The specific error from Visual Studio is
C2664 'double mean1(std::span<const double,18446744073709551615>)':
cannot convert argument 1 from 'initializer list' to 'std::span<const
double,18446744073709551615>'
I think, basically, std::span doesn't have a constructor that takes an initializer list.
|
you can use
mean1( {{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }} );
which invoke the raw array constructor.
if you want to specify the type, I'd suggest
mean1( std::initializer_list{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } )
which prevent the potential construction of another container. (which still construct a initializer_list anyway)
|
73,693,805
| 73,693,839
|
Why simple code doesn`t work corectly c++?
|
#include <iostream>
bool check_number(unsigned short int a, unsigned short int b) {
if ((a || b == 30) || a + b == 30) {
return true;
}
return false;
}
int main() {
std::cout << check_number(15, 16) << std::endl;
std::cin.get();
return 0;
}
Why I get "true" result? Why not false, we know that 15 + 16 is 31
|
if ((a || b == 30) is not "either a or b equal 30" it is "either (a) or (b equals 30)". As a is non-zero it is true when converted to bool.
So you have
if ((true || other condition) || just_another_condition)
and because || is short-circuiting the condition as a whole is true.
If you actually wanted "either a equals 30 or b equals 30" that is (a == 30) || (b == 30).
Last but not least, if you have code like this:
if (condition) {
return true;
} else {
return false;
}
Then this is just return condition;
|
73,694,162
| 73,694,408
|
How to make `this` pointer constant expression?
|
This is a follow-up question is my previous question: Why are member functions returning non-static data members not core constant expressions?
The reduced version of the example mentioned in that question is:
struct S {
const bool x = true;
constexpr bool f() { return x; }
};
int main() {
S s{};
static_assert(s.f()); // error: 's' is not a constexpr;
}
The applicable wording from the standard is N4861: [expr.const]/(5.1):
An expression E is a core constant expression unless the evaluation
of E, following the rules of the abstract machine
([intro.execution]), would evaluate one of the following:
(5.1) this ([expr.prim.this]), except in a constexpr function ([dcl.constexpr]) that is being evaluated as part of E;
As far as I can parse, the expression E is s.f() and it evaluates this since s.f() returns a non-static member this->x. But that falls under the "except" part: the member function s.S::f() is constexpr function that's being evaluated as part of s.f(). If I parsed correctly, I'm expecting s.f() to be constant expression and the assertion success.
However, this bullet doesn't specify a requirement that says that s has to be a constant expression. I can't understand why declaring s as constexpr compiles the program even though there's no requirement, defined in this bullet, for s to be constexpr.
I'm just applying the wording (5.1) in my example but I can't see that constexpr is required here unless I'm missing any other rule.
|
Because return x; performs lvalue-to-rvalue conversion, the whole kaboodle is not a core constant expression:
An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following:
an lvalue-to-rvalue conversion unless it is applied to
a non-volatile glvalue that refers to an object that is usable in constant expressions, or
a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of E;
lvalue-to-rvalue conversion is applied to this->S::x, which is generally forbidden, and neither of the exceptions apply to permit it.
The more relevant exception applies if x (which resolves to this->S::x) is an object that is usable in constant expressions. But it only would be if the struct S object were usable in constant expressions:
a non-mutable subobject or reference member of any of the above.
That requires it to be potentially-constant:
A variable is potentially-constant if it is constexpr or it has reference or const-qualified integral or enumeration type.
A constant-initialized potentially-constant variable is usable in constant expressions at a point P if ...
And S s{}; is not potentially-constant. So it is not usable in constant expressions, and neither are its subobjects.
To answer the title question, this is not a core constant expression, because it is the address of an object with automatic storage duration; that address may change at runtime. This is completely irrelevant for the static_assert in the question code: Being a constant pointer value is neither necessary nor sufficient for a this pointer to be "usable in constant expressions", which in turn is not sufficient for the object found through the pointer to be usable in constant expressions.
|
73,695,128
| 73,696,159
|
How to download a zip file from github repo and read her content in memory?
|
I have uploaded a zip file compressed with 7-zip option add to .zip containing only a file with the name text.txt into this GitHub repo, how I could read the content of the file text.txt without writing it to disk?
I'm downloading the zip to memory using curl:
#include <curl/curl.h>
static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb,
void* userp) {
size_t realsize = size * nmemb;
auto& mem = *static_cast<std::string*>(userp);
mem.append(static_cast<char*>(contents), realsize);
return realsize;
}
std::string Download(const std::string& url)
{
CURL* curl_handle;
CURLcode res;
std::string chunk;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &chunk);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
// added options that may be required
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L); // redirects
curl_easy_setopt(curl_handle, CURLOPT_HTTPPROXYTUNNEL, 1L); // corp. proxies etc.
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L); // we want it all
// curl_easy_setopt(curl_handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << '\n';
} else {
std::cout << chunk.size() << " bytes retrieved\n";
}
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
return chunk;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::string link = "https://github.com/R3uan3/test/raw/main/text.zip";
auto data = Download(link);
}
While searching for a lib capable of uncompressing the zip on memory, I found this one: libzip (any lib is welcome).
Searching for examples I found this answer, however he's loading a zip from disk to memory and reading it content.
How I could read the zip downloaded with curl that is on the string data?
When I visualize the content of data in the debugger it shows PK, I tried passing it to zip *z, but z returns null
//Open the ZIP archive
int err = 0;
zip *z = zip_open(data.c_str(), 0, &err);
//Search for the file of given name
const char *name = "text.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, name, 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
|
I'm ignoring everything about curl in the question because we've verified that you've got the zip file stored in memory correctly.
How I could read the zip ... that is on the string data?
Since you have the whole zip file stored in memory, you need to create a zip_source from chunk.data() and open the archive using that zip_source - and then open the individual files in the archive.
Here's how (without error checking - you need to add that):
{
// ...
zip_error_t ze; // for errors
// create a zip_source from the data you've stored in memory
zip_source_t* zs = zip_source_buffer_create(chunk.data(), chunk.size(), 0, &ze);
// open the archive from the zip_source
zip_t* zip = zip_open_from_source(zs, ZIP_CHECKCONS | ZIP_RDONLY, &ze);
// read how many files you've got in there
zip_int64_t entries = zip_get_num_entries(zip, 0);
std::cout << entries << '\n';
// loop over the entries in the archive
for(zip_int64_t idx = 0; idx < entries; ++idx) {
std::cout << zip_get_name(zip, idx, ZIP_FL_ENC_STRICT) << '\n';
// open the file at this index
zip_file_t* fp = zip_fopen_index(zip, idx, 0);
// process the file
zip_int64_t len;
char buf[1024];
while((len = zip_fread(fp, buf, sizeof buf)) > 0) {
std::cout << "read " << len << " bytes\n";
// do something with the `len` bytes you have in `buf`
}
zip_fclose(fp); // close this file
}
zip_close(zip); // close the whole archive
}
|
73,695,763
| 73,696,520
|
How could I do a robust mapping of multiple data types?
|
I am trying to convert a long list of key and value pairs into a map so that I can just iterate over it instead of defining each of them line-by-line, but I have a mix of data types for the values (uint8_t, uint16_t, uint32_t, and uint64_t).
Here's a sample of the data I am trying to build a mapping of:
static constexpr uint8_t data1{0x01};
static constexpr uint16_t data2{0x0002};
static constexpr uint32_t data3{0x00000003};
static constexpr uint64_t data4{0x0000000000000004};
I tried doing a union and a struct:
union/struct dtypes {
uint8_t i;
uint16_t j;
uint32_t k;
uint64_t l;
};
Then here's my attempt at creating the map:
std::map<std::string, dtypes> mymap = {{"data1", 0x01},
{"data2", 0x0002},
{"data3", 0x00000003},
{"data4", 0x0000000000000004}};
Then I try to do a for loop to populate a vector of uint8_t's (call it vec):
for (auto iter = mymap.begin(); iter != mymap.end(); ++iter) {
byte_pushback(vec, iter->second)
};
But the error message I am getting is:
error: could not convert "'{{"data1", 0}, {"data2", 2}, and so on..' from '<brace-enclosed initializer list>' to 'std::map<std::__cxx11::basis_string<char>, dtypes>'
{"data4", 0x0000000000000004}};
^
|
<brace-enclosed initializer list>
How could I do this properly?
This byte_pushback() function breaks the uint16_t, uint32_t, uint64_t into a bunch of uint8_ts and does a push back, so data2 would be {0x00, 0x02}.
|
You should initialize the map like this.
std::map<std::string, dtypes> mymap = {
{"data1", {.i = 0x01}},
{"data2", {.j = 0x0002}},
{"data3", {.k = 0x00000003}},
{"data4", {.l = 0x0000000000000004}},
};
Using an union or struct with properly named members helps to simplify implementations of encoding and decoding fields and is good for the readability.
|
73,696,093
| 73,696,146
|
C++ Switch statement using strings
|
I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C++ so I'm still learning and this code is not completed yet but can anyone please help me with this?
int main()
{
// Declare Constant variables
const float DISC_GOLF_RETAIL = 14.96;
const float ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const float DISCOUNT2 = .16;
const float DISCOUNT3 = .24;
const float DISCOUNT4 = .32;
const double DEC = 100;
// Declare variables
double quantity;
double pricePerDisc;
double totalSavings;
double total;
char userInput;
float discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
// Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
// Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (discType)
{
case 1: userInput=='u' || 'U';
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
break;
case 2: userInput=='g' || 'G';
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
cout << "------------Receipt------------" << endl;
if (quantity>5 && quantity<=9)
{
discount = DISCOUNT1 / DEC;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>10 && quantity<=19)
{
discount = DISCOUNT2;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>20 && quantity<=29)
{
discount = DISCOUNT3;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>= 30)
{
discount = DISCOUNT4;
}
totalSavings = (pricePerDisc * quantity) * discount;
total = quantity * pricePerDisc - totalSavings;
cout << "Disc Type: " << discType << endl;
cout << "Quantity: " << quantity << endl;
cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
<< pricePerDisc << endl;
cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
<< totalSavings << endl;
cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
|
For single char responses, you can use the switch/case statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string is usually consists of more than one character.
|
73,696,408
| 73,707,739
|
How to format double as hex?
|
How can one format double as hex?
double t = 1.123;
fmt::format("{:x}", t);
It throws exception "invalid type specifier".
I would like to get string 3ff1f7ced916872b
|
You can use std::bit_cast to cast double into an appropriately sized integer and format that in hexadecimal, e.g. assuming IEEE754 double:
double t = 1.123;
auto s = fmt::format("{:x}", std::bit_cast<uint64_t>(t));
// s == "3ff1f7ced916872b"
godbolt: https://godbolt.org/z/ehKTrMz7M
|
73,697,257
| 73,697,608
|
How 0061 736d represents \0asm?
|
I just started to learn web assembly . I found this text
"In binary format The first four bytes represent the Wasm binary magic
number \0asm; the next four bytes represent the Wasm binary version in
a 32-bit format"
I am not able to understand this . Can anyone explain me this
|
\0 is a character with code 0 (the first 00 in 00617369), the remaining three are literal characters a, s and m. With codes 97, 115 and 109 respectively, or 61, 73 and 6d in hex.
|
73,697,852
| 73,716,727
|
Cannot connect to Windows server active directory lightweight service
|
Am working with windows server I want to create active directory lightweight service user by c++ ie, By c++ using ldap connection. My server runs in virtual box and i set the network adapter to be bridged network and it connects to the network just fine.
Now when i used the code from microsoft documentation the ldap bind is not connecting .The error am getting is an operation error occured.
#include "atlbase.h"
#include "activeds.h"
int main(int argc, char* argv[])
{
HRESULT hr;
IADsContainer* pCont;
IDispatch* pDisp = NULL;
IADs* pUser;
// Initialize COM before calling any ADSI functions or interfaces.
CoInitialize(NULL);
hr = ADsGetObject(L"LDAP://ABC.local",
IID_IADsContainer,
(void**)&pCont);
if (!SUCCEEDED(hr))
{
return 0;
}
//-----------------
// Create a user
//-----------------
hr = pCont->Create(CComBSTR("user"), CComBSTR("cn=jeffsmith"), &pDisp);
// Release the container object.
pCont->Release();
if (!SUCCEEDED(hr))
{
return 0;
}
hr = pDisp->QueryInterface(IID_IADs, (void**)&pUser);
// Release the dispatch interface.
pDisp->Release();
if (!SUCCEEDED(hr))
{
return 0;
}
// Commit the object data to the directory.
pUser->SetInfo();
// Release the object.
pUser->Release();
CoUninitialize();
}
This is the code am using to check for successful connection. Any help will be really useful thank you.
|
You're asking for a container (IID_IADsContainer), but the path you give it is to the root of the domain (LDAP://ABC.local). Try specifying the distinguished name of the OU you want to put the user in. For example, if you want to put the user in the Users OU, which is at the root of the domain, it would look like this:
hr = ADsGetObject(L"LDAP://ABC.local/OU=Users,DC=ABC,DC=local",
IID_IADsContainer,
(void**)&pCont);
You can read more about the format of the LDAP path here: LDAP ADsPath
|
73,698,196
| 73,698,285
|
Error on Operation of numbers and user input values in cpp
|
I am a begineer in C++ ! While playing with just learned skils i m trying to create a program that calculates your age by your Birth year passed in command line. I dont know why the program didn't even compile !
MY CODE :
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
if (argc < 2){
cout<<"Your Age is 2022-<YOB> \n";
return 3;
}
int age;
age = 2022-argc[1]
cout<<"Your Age is "<<age<<endl;
return 0;
}
ERROR:
./main.cpp:10:18: error: subscripted value is not an array, pointer, or vector
age = 2022-argc[1]
~~~~^~
1 error generated.
make: *** [Makefile:9: main] Error 1
exit status 2
|
The problem is that argc is an int, so we can't use operator[] with it.
To solve this you can use argv and std::istringstream as shown below:
int main(int argc, char *argv[])
{
if(argc < 2){
std::cout <<"Your age is 2022-<YOB>\n";
return 0;
}
std::istringstream ss(argv[1]);
int age = 0;
//convert string arg to int age
ss >> age;
std::cout<<"Your age is: "<<age<<std::endl;
}
|
73,698,496
| 73,698,900
|
What's the name of all the square brackets?
|
In C++, we have square brackets in different places and I think it's sometimes important to distinguish them when talking to other developers. While I can call all of them "square brackets", I think they have better names, depending on what they do.
I am thinking of
array declaration, like int arr[1024];
array assignment, like arr[13] = 17;
array access, like int x = arr[13];
map (and other container) access, like int y = map["key"];
captures in lambdas, like auto lambda = [&](){return 23 + arr[13];};
the ones in delete[]
those of attributes like [[deprecated("for reasons")]]
the separation of a pair into its parts like auto [x, y] = std::make_pair(1, 2);
IMHO, the array assignment and array access brackets are called subscript operator. What about all the others? Do they have good names?
|
(2), (3), (4) — arr[13] — It's an operator. So, "subscript operator" or "square brackets operator"? To further point out the lhs type, "{map,vector,array} subscript operator"?
(1) — int arr[1024]; — The grammar doesn't seem to have a name specifically for the brackets. The whole arr[1024] is an "(array) declarator".
My colleague called the array declaration brackets (1.) "subscript operator" and I felt that this is the wrong term
I would point out that it's not an operator, without suggesting an other term. Just call them brackets.
(5) — [...](){} — This is commonly called a "lambda capture list". The grammar calls it a "lambda-introducer", but the term feels rather obscure.
(6) — delete[] — The whole thing is an array delete (expression). The brackets themselves don't have a separate name.
(7) — [[nodiscard]] — The whole thing is an "attribute" (the grammar calls it an "attribute-specifier", or "...-seq" for a list of attributes). The double brackets themselves don't seem to have a separate name.
(8) — auto [x, y] — The whole thing is a "structured binding (declaration)", or a "decomposition declaration" (I've only seen the latter in Clang error messages, not in the standard). The brackets themselves don't have a separate name here. The thing enclosed in brackets is called an identifier-list in the grammar.
|
73,698,528
| 73,741,651
|
Import .dll for NWJS module causes '#import of type library is an unsupported Microsoft feature'
|
I have a legacy module for our app. It uses external dll from other software. If I run this command
nw-gyp rebuild --target=0.34.3 --msvs_version=2019 --target_arch=ia32 --arch=ia32
it produces some warnings, but compiles (where 0.34.3 is a nw.js version)
But if I run this command
nw-gyp rebuild --target=0.68.0 --msvs_version=2019 --target_arch=ia32 --arch=ia32
I receive following errors
clang-cl : warning : argument unused during compilation: '/Gm-' [-Wunused-command-line-argument]
clang-cl : warning : argument unused during compilation: '/external:W3' [-Wunused-command-line-argument]
..\src\atol8.cpp(2,2): error : #import of type library is an unsupported Microsoft feature
..\src\atol8.cpp(27,2): error : unknown type name 'CLSID'
..\src\atol8.cpp(28,2): error : unknown type name 'IDispatch'
..\src\atol8.cpp(29,2): error : use of undeclared identifier 'FprnM1C'
..\src\atol8.cpp(30,2): error : unknown type name 'DISPPARAMS'
As I understand, main error is that compiler can't import external library, throws #import of type library is an unsupported Microsoft feature and it causes other errors.
atol8.cpp code
#import "D:\Program Files (x86)\ATOL\Drivers8\Bin\FprnM1C.dll" raw_interfaces_only
#include <node.h>
#include <iostream>
#include <locale>
#include <string>
#include <wchar.h>
std::locale ru("rus_rus.1251");
namespace Atol8Drv {
using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
using v8::HandleScope;
using v8::Array;
using v8::Integer;
using v8::Boolean;
CLSID clsid;
IDispatch *pWApp;
FprnM1C::IFprnM45 *pMiDrv;
/** other code is not relevant **/
I am not a C programmer and the person who originally wrote this module is not available, but as I remember there should be a parameter for the nw-gyp or node-gyp and I can't nor remember or google how to resolve this error.
I'm ready to answer your questions and provide additional information if required.
|
Finally, I found a way to compile this module. The problem is in clang.
If I try to compile it with --clang=false option - it works perfectly.
So, if someone in the future will stuck with the same error, command for compilation should be:
nw-gyp rebuild --target=0.68.0 --msvs_version=2019 --target_arch=ia32 --arch=ia32 --clang=false
|
73,698,531
| 73,698,917
|
C++ error: The right operand of '*' is a garbage value
|
I finally completed my code and when I submit it I received a couple errors. It keeps telling me
73:15 Incorrect spacing around >=.
73:31 Incorrect spacing around <=.
for this line, I've tried putting it together and no change
if (quantity >=5 && quantity <=9)
I have checked my entire code multiples times (my program shows dots where spaces are) and I cannot find any extra or unplanned spaces.
The error message The right operand of '*' is a garbage value is emitted in regards to this line:
totalSavings = pricePerDisc * quantity * discount;
Can anyone help me out please?
int main()
{
//Declare Constant variables
const double DISC_GOLF_RETAIL = 14.96;
const double ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const double DISCOUNT2 = .16;
const double DISCOUNT3 = .24;
const double DISCOUNT4 = .32;
//Declare variables
int quantity;
double pricePerDisc;
double totalSavings;
double afterSavings;
double total;
char userInput;
double discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
//Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
//Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (userInput)
{
case 'u':
case 'U':
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
break;
case 'g':
case 'G':
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
cout << "Enter the number of Disc-Golf Disc(s): ";
cin >> (quantity);
cout << endl;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
if (quantity <= 0)
{
cout << quantity << " is an invalid number of discs.\n";
return 0;
}
if (quantity >=5 && quantity <=9)
{
discount = DISCOUNT1 / 100;
}
else if (quantity >=10 && quantity <=19)
{
discount = DISCOUNT2;
}
else if (quantity >=20 && quantity <=29)
{
discount = DISCOUNT3;
}
else if (quantity >=30)
{
discount = DISCOUNT4;
}
totalSavings = pricePerDisc * quantity * discount;
afterSavings = pricePerDisc - (pricePerDisc * discount);
total = quantity * pricePerDisc - totalSavings;
cout << "------------Receipt------------" << endl;
cout << " Disc Type: " << discType << endl;
cout << " Quantity: " << quantity << endl;
cout << fixed << setprecision(2);
cout << "Price per Disc: " << "$ " << setw(12) << afterSavings << endl;
cout << " Total Savings: " << "$ " << setw(6) << "-" << totalSavings
<< endl;
cout << " Total: " << "$ " << setw(12) << total << endl;
return 0;
}
|
If you are asking why is there are The right operand of '*' is a garbage value error, I think it is because program thinks that pricePerDisc/quentity/discount are not initialized.
It happens because you are using switch(case) that is unrecommended in C++. Compiler/IDE not looking inside of switch(case) (you have initialization of previous variables in it) and this is why he keeps thinking, that you don't initialize any of pricePerDisc/quentity/discount variables (when you are not initializing variables there are just garbage in it).
If you want to silence this warning/error - simply initialize some default numbers in your declaration. For example:
int quantity = 0;
double pricePerDisc = 0.0;
double totalSavings = 0.0;
double afterSavings;
double total;
char userInput;
double discount = 0.0;
Hope it helps!
|
73,698,942
| 73,713,495
|
Fastest way to process http request
|
I am currently working on creating a network of multisensors (measuring temp, humidity ect). There will be tens or in some buildings even hundreds of sensors measuring at the same time. All these sensors send their data via a http GET request to a local esp32 server that processes the data and converts it into whatever the building's contol system can work with (KNX, BACnet, MODbus). Now I stress tested this server and found out that it can process around 1400 requests per minute before the sender gets no response anymore. This seems like a high amount but if a sensor sends its data every 2 seconds it means there will be a limit of around 45 sensors. I need to find a way how to process such a request quicker, this is the code I currently use:
server.on("/get-data", HTTP_GET, [](AsyncWebServerRequest *request)
{handle_get_data(request); request->send(200); });
void handle_get_data(AsyncWebServerRequest *request)
{
packetval++;
sensorData.humidity = request->arg("humidity").toFloat();
sensorData.temperature = request->arg("temperature").toFloat();
sensorData.isMovement = request->arg("isMovement");
sensorData.isSound = request->arg("isSound");
sensorData.luxValue = request->arg("luxValue").toDouble();
sensorData.RSSI = request->arg("signalValue").toInt();
sensorData.deviceID = request->arg("deviceID");
sensorData.btList = request->arg("btList");
if (deviceList.indexOf(sensorData.deviceID) == -1)
{
deviceList += sensorData.deviceID;
activeSensors++;
}
if (sensorData.isMovement || sensorData.isSound)
{
sendDataFlag = true;
}
}
I use the AsyncTCP library.
Now I measured the execution time of the function handle_get_data() and it turns out it is only ~175uS which is very quick. However the time between two calls of handle_get_data() is around 6ms which is really slow but it still doesnt explain why I can only process 1400 per minute or 24 per second (6ms = 155Hz why is my limit 24Hz?). Other than that I do not use any other code during the processing of a request, is it perhaps a limitation in the library? Is there another way to process such a request?
A request looks like this: http://192.168.6.51:80/get-data?humidity=32.0&temperature=32.0&isMovement=1&isSound=1&luxValue=123&RSSI=32&deviceID=XX:XX:XX:XX:XX:XX&btList=d1d2d3d4d5d6d7
If there is really nothing I can do I can always switch to a raspberry pi to process everything but I would rather stick to esp32 since I want to easily create an own PCB.
Thanks for all the help!
|
Creating a websocket instead of using http requests solved the issue for me:
AsyncWebSocket ws("/ws");
void setup()
{
ws.onEvent(onWsEvent);
server.addHandler(&ws);
}
AsyncWebSocketClient *wsClient;
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
if (type == WS_EVT_DATA)
{
AwsFrameInfo *info = (AwsFrameInfo *)arg;
String msg = "";
packetval++;
if (info->final && info->index == 0 && info->len == len)
{
if (info->opcode == WS_TEXT)
{
for (size_t i = 0; i < info->len; i++)
{
msg += (char)data[i];
}
}
}
sensorData.humidity = msg.substring(msg.indexOf("<hum>") + 5, msg.indexOf("</hum>")).toFloat();
sensorData.temperature = msg.substring(msg.indexOf("<tem>") + 5, msg.indexOf("</tem>")).toFloat();
sensorData.isMovement = (msg.substring(msg.indexOf("<isMov>") + 7, msg.indexOf("</isMov>")) == "1");
sensorData.isSound = (msg.substring(msg.indexOf("<isSnd>") + 7, msg.indexOf("</isSnd>")) == "1");
sensorData.luxValue = msg.substring(msg.indexOf("<lux>") + 5, msg.indexOf("</lux>")).toDouble();
sensorData.RSSI = msg.substring(msg.indexOf("<RSSI>") + 6, msg.indexOf("</RSSI>")).toInt();
sensorData.deviceID = msg.substring(msg.indexOf("<dID>") + 5, msg.indexOf("</dID>"));
sensorData.btList = msg.substring(msg.indexOf("<bt>") + 4, msg.indexOf("</bt>"));
if (deviceList.indexOf(sensorData.deviceID) == -1)
{
deviceList += sensorData.deviceID;
activeSensors++;
}
if (sensorData.isMovement || sensorData.isSound)
{
sendDataFlag = true;
}
}
}
This will process more than 11000 packets per minute (200kb/s). The execution time of void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) takes ~500uS now which means there is definitly optimising to do in this function but the time between two calls is reduced all the way to 1ms.
|
73,699,355
| 73,700,725
|
perfect forwarding with brace enclosed initialiser list
|
For personal education I am coding up a basic implementation of a hash table (although the below is probably relevant to any container that is holding types that can be list initialised) and want to use modern elements of c++ as best as I understand them - in particular in this case, perfect forwarding.
In doing so I have found I can't figure out a particular case - writing an insert function that achieves perfect forwarding while taking a brace enclosed initialiser list. Failing to write this prevents using perfect forwarding when trying to emulate the std::unordered_map like insertion style container.insert({key,value}).
To be specific, I have some hash table class which stores keys and values as std::pair<T,U> objects in (for example) lists at buckets stored in a vector (for a hash+chaining approach)
template<typename T,typename U, typename func = std::hash<T> >
class HashTable{
std::vector<std::list<std::pair<T,U> > > data;
...
public:
template<typename V>
bool insert(V &&entry)
{
//insert into the table by forwarding entry as
... = std::forward<V>(entry);
return true; //plus some logic for failed insertion if key already exists
}
};
I then test my container by inserting with both lvalues and rvalues through calls such as
std::pair<int32_t,std::string> example = {12,"bike"};
myHashTableObject.insert(example); //example 1
myHashTableObject.insert(std::pair<int32_t,std::string>(15,"car")); //example 2
myHashTableObject.insert({28,"bus"}); //example 3
Examples 1 and 2 compile and work fine, but example 3 does not with compiler error (for example using the default type for the third template argument func - but the error is analgous for user provided hashes)
error: no matching function for call to ‘HashTable<int, std::__cxx11::basic_string<char> >::insert(<brace-enclosed initializer list>)’
which seems reasonable - it can't figure out how to interpret what type of object the initialisation list is supposed to construct.
An easy "solution" is to forget perfect forwarding and just overload the insert function to accept a right-hand reference and a const regular reference to a std::pair<T,U>. But it feels like there should be a better way.
Is there an obvious way to inform the compiler that, despite being a template variable V in order to achieve perfect forwarding, it should be some kind of reference to a std::pair<T,U> argument?
How do common implementations of containers in STL achieve this? Or do they just overload?
|
{..} has not type, and so cannot be deduced in insert.
You might work around that by providing default template type:
template<typename V = std::pair<T, U>> // default to handle {..}
bool insert(V&& entry)
{
... = std::forward<V>(entry);
// ..
return true;
}
Demo
|
73,699,502
| 73,699,593
|
unique_lock same mutex in different thread
|
i am looking at this piece of code:
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
bool flag;
std::mutex m;
void wait_for_flag() {
// std::cout << &m << std::endl;
// return;
std::unique_lock<std::mutex> lk(m);
while (!flag) {
lk.unlock();
std::cout << "unlocked....." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "sleeping....." << std::endl;
lk.lock();
std::cout << "locked by " << std::this_thread::get_id() << "....."
<< std::endl;
}
}
int main(int argc, char const *argv[]) {
std::thread t(wait_for_flag);
std::thread t2(wait_for_flag);
std::thread t3(wait_for_flag);
std::thread t4(wait_for_flag);
std::thread t5(wait_for_flag);
t.join();
t2.join();
t3.join();
t4.join();
t5.join();
return 0;
}
I am new to this, and I thought mutex can only be acquired by one thread. I got two questions:
why there is no deadlock among those threads, e.g. if thread A runs lk.unlock(), then thread B runs lk.lock() and then thread A runs lk.lock().
what does it mean we define a new unique_lock in every thread associating to the same mutex lock (which is called m in here)
Thanks
|
Because right after acquiring a lock on the mutex each thread calls lk.unlock(); and now other thread can acquire a lock on the mutex. Only if a thread tries to lock an already locked mutex (by a different thread) it has to wait for the mutex to be free. As any thread in your code eventually calls lk.unlock(); there is always a chance for a different thread to get a lock on the mutex and there is no deadlock.
A deadlock would occur for example if you have two mutexes and two threads try to lock them in different order:
// thread A
std::unique_lock<std::mutex> lk1(mutex1);
std::unique_lock<std::mutex> lk2(mutex2); // X
// thread B
std::unique_lock<std::mutex> lk2(mutex2);
std::unique_lock<std::mutex> lk1(mutex1); // X
Here it can happen that thread A locks mutex1, thread B locks mutex2 and then both wait in X for the other thread to release the other mutex, but this will never happen. Its a deadlock.
2.
A lock is merely a slim RAII type. Its only purpose is to call lock on the mutex when created and unlock when destroyed. You can write the same code without the lock, by manually locking / unlocking the mutex, but when there is an exception while a mutex is locked it will never be unlocked.
|
73,700,117
| 73,700,231
|
How to pass only selected arguments to a function?
|
Let's suppose I have a struct X and I want to fill out all fields depending on some conditions.
I'd like to distinguish which parameter I want to pass to a function and based on provided parameters create and then return that object. I'm curious if I should use variadic templates in c++?
Pseudo code.
#include <iostream>
using namespace std;
struct X
{
string a;
string b;
string c;
}
X generateTransaction(const string& e, const string& f, const string& g)
{
X one;
if (e)
one.a = e;
if (f)
one.b = f;
if (g)
one.c = g;
return one;
}
int main()
{
generateTransaction(e = "first");
generateTransaction(e = "abc", f = "second");
generateTransaction(g = "third");
generateTransaction(e = "test", g = "third");
generateTransaction("m", "n", "o");
return 0;
}
|
You can pass parameters as std::optional and then check if it has value. Something like:
X generateTransaction(const std::optional<std::string> &e,
const std::optional<std::string> &f,
const std::optional<std::string> &g)
{
X one;
if (e.has_value())
{
one.a = e.value();
}
if (f.has_value())
{
one.b = f.value();
}
if (g.has_value())
{
one.c = g.value();
}
return one;
}
int main()
{
generateTransaction("first", {}, {});
generateTransaction("abc", "second", {});
generateTransaction({}, {}, "third");
generateTransaction("test", {}, "third");
generateTransaction("m", "n", "o");
return 0;
}
|
73,700,142
| 73,700,755
|
Can the ctor be marked noexcept based on allocator type?
|
How should I make sure that a constructor is noexcept if the allocator does not throw?
Here is an MRE:
#include <iostream>
#include <array>
#include <vector>
#include <memory_resource>
#include <concepts>
#include <cstddef>
template < std::unsigned_integral T, class Allocator = std::allocator<T> >
class Foo
{
std::vector<T, Allocator> vec;
public:
Foo( const size_t size, const T value,
const Allocator& alloc = Allocator { } ) noexcept( noexcept( Allocator { } ) )
: vec { size, value, alloc }
{
}
};
int main( )
{
Foo<unsigned> my_foo { 10, 505 };
auto buffer { std::array<std::byte, 50> { } };
std::pmr::monotonic_buffer_resource rsrc { buffer.data( ), buffer.size( ) };
Foo< unsigned, std::pmr::polymorphic_allocator<unsigned> > my_foo_pmr { 10, 505, &rsrc };
std::cout << std::boolalpha
<< noexcept( std::pmr::polymorphic_allocator<unsigned> { } ) << '\n' // true
<< noexcept( std::allocator<unsigned> { } ) << '\n' // true
<< std::noboolalpha;
}
First of all, I wonder why does noexcept( std::allocator<unsigned> { } ) return true? Is std::allocator<unsigned> exception safe? Like a vector with this allocator never throws? And what about the pmr allocator that has a stack-based buffer? Can it throw?
Secondly, what is the proper way of ensuring that the above class's ctor is marked noexcept if it actually never throws?
|
First of all, I wonder why does noexcept( std::allocator<unsigned> { } ) return true?
Because constructing a std::allocator<unsigned> does not throw.
Secondly, what is the proper way of ensuring that the above class's ctor is marked noexcept if it actually never throws?
The proper way is to not mark it as noexcept because it may throw. The vector constructor you are calling is not noexcept. Only std::vectors default constructor is noexcept( noexcept(Allocator()), but you are calling a different constructor. With a pmr allocator I suppose nothing is different, because when size is too big then being able to construct the allocator without exceptions does not help to avoid running out of memory once you allocate too many elements.
|
73,700,469
| 73,700,518
|
Pass block of statements as arguement to the function call
|
Consider the following example:
func(cond, block_A, block_B) {
if(cond) {
block_A; // Run all the statements in the block A
} else {
block_B; // Run all the statements in the block B
}
}
int main() {
block_A = {
y = 1;
std::cout << (y);
// statement continues ...
}
block_B = {
z = 1;
std::cout << (z);
// statement continues ...
}
func(true, block_A, block_C);
}
Is there any way to pass a block of statements as an argument to the function call?
|
You can pass callables to func and use lambda expressions:
#include <iostream>
template <typename F,typename G>
void func(bool cond, F a, G b) {
if(cond) {
a(); // Run all the statements in the block A
} else {
b(); // Run all the statements in the block B
}
}
int main() {
auto block_A = [](){
int y = 1;
std::cout << y;
};
auto block_B = [](){
int z = 1;
std::cout << z;
};
func(true, block_A, block_B);
}
|
73,700,487
| 73,700,653
|
CPP how to format strings to align to the right side
|
I am looking for a simple CPP solution to align a string to the right size.
What do I mean by this?
here is an example:
the normal output would be
hello [message]
foo [message]
I would like it to output like this:
hello [message]
foo [message]
note: this is not for aligning a table but rather to know how to align a message by adding certain spaces to the left (or smth).
|
Like this ?
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setw(10) << "Hello" << " [message]" << std::endl ;
std::cout << std::setw(10) << "foo" << " [message]" << std::endl ;
}
|
73,701,833
| 73,742,038
|
What is the optimal way to synchronize frames in ffmpeg c/c++?
|
I made a program that read's n number of video's as input, draws those videos to the GLFW window and finally encodes it all as a singular video output. The problem is frames of each video in question can be different, it's dependent on the user's input.
For example: the user can put two video's which has an FPS of 30 and 59, and can want an output 23,797. The problem is those video's are not in sync with each other, thus on the output we can see that the input video's are either faster or slower.
Duration of each video is also dependent on the input. For example, in accordance to the previous example, the first input might be 30 second and the second can be 13 second, while the output is 50 seconds.
I mostly read the frames similar to a moving png rather than a solid video since there are no iframe and bframes. There are just data I get from the GLFW window.
As an example, let's say we give one video as input which has an FPS of 30 and duration of 30, and our output has an FPS of 23.797 and duration of 30. I have 2 function's skip_frame and wait_frame which respectively either read's a frame twice so we skip a frame or don't read the frame on that iteration. Those function's are used depending on the situation, whether it's output < input or output > input.
Here is what my code roughly looks like:
while(current_time < output_duration){
for(auto input_video: all_inputs){
for(int i = 0; i < amount_to_read_from_input(); i++){
frame = input_video.read_frame();
}
}
GLFW_window.draw_to_screen(frame);
encoder.encode_one_video_frame(GLFW_window.read_window());
}
Basically skip_frame and wait_frame are both inside amount_to_read_from_input() and return 2 or 0 respectively.
So far I have tried multiplying duration with fps for both input and output. Then getting the result of their subtraction. Going from our previous example we get 900 - 714 = 186.
Then I divide the result to the output fps like so: 714 / 186 = 3.8. Meaning that I have to skip a frame every 3.8 iterations. (I skip a frame every 3 iterations and save the residual 0.8 for the next iter.)
But it's still a seconds or two behind. (Like it ends at 29 seconds for a 30 second output.) and the audio is out-of-sync. Ffmpeg handles my audio so there are no errors on that part.
Also seen this question but I don't think I can utilize ffmpeg's function's here since im reading from a glfw window and it comes down to my algorithm.
The problem is what is the math here?
What can I do to make sure these frames are stabilized on almost every input/output combination?
|
For those who are struggling in a similar situation: The problem was my encoder's time base: I was passing it as an int rather than a formatted AVRational. My fps variable was a float, and when I pass that to my encoder it rounds it to the closest integer. As an example I was passing 23.797 and it rounded to 23. So whatever algorithm I write it was always wrong since my algorithms were wired to calculate for 23.797 while ffmpeg was trying to encode for 23.
Changing time_base = (AVRational){ 1, fps}; to time_base = av_d2q(1 / STREAM_FRAME_RATE, std::numeric_limits<int>::max()); caused all my algorithm's to work as intended.
I'm still not sure whether there is a standard for calculating this or not, my way of doing it worked for me just fine.
|
73,701,904
| 73,702,893
|
float outputs differently in different consoles
|
I am running the same OpenGL executable in CLion and cmd, but they show different outputs. CLion shows the right number, cmd shows inf and sometimes the number. cout does the same.
(I've mitigated all ogl calls from the code since they're unnecessary)
The code to that is:
int i = 0;
auto lastTime = std::chrono::high_resolution_clock::now();
while ... {
auto currentTime = std::chrono::high_resolution_clock::now();
if (i % 10000 == 0) {
auto deltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(currentTime - lastTime).count();
printf("FPS: %10.0f\n", 1.0f / deltaTime);
}
i++;
lastTime = currentTime;
}
CLion left, cmd right
|
As Peter pointed out, the problem is that some iterations take less time than the resolution of the clock being used and that time in turn depends on the environment where the program is executed.
A solution to such problems could be to measure the time for X iterations (10000 in the following example) and then calculate the average time:
int i = 0;
auto lastTime = std::chrono::high_resolution_clock::now();
while ... {
if (++i == 10000) {
auto currentTime = std::chrono::high_resolution_clock::now();
auto deltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(currentTime - lastTime).count();
deltaTime /= 10000.0f; //average time for 1 iteration
printf("FPS: %10.0f\n", 1.0f / deltaTime);
lastTime = currentTime;
i = 0; //reset counter to prevent overflow in long runs
}
}
|
73,702,189
| 73,702,247
|
Template a member variable in a class
|
I am doing some refactoring on some older/messy code. I am trying to improve things little by little. Because it fit the project, I started implementing CRTP (for static polymorphism) on some class, let's call it sensor. Through CRTP, there is now a real and a fake implementation.
Now, I am trying to put templates in a class (interface_actions) that uses sensor. I arrived at something like that:
class interface_actions
{
public:
template <class implementation>
interface_actions(sensor<implementation> detector)
: _detector(detector)
{}
// Lots of stuff that I don't want to touch
private:
#if (SOMETHING)
sensor<real> _detector;
#else
sensor<fake> _detector;
#endif
};
As you can see, I did not know what to do with _detector without having to make the entire class a template, so I used the preprocessor ...
This is more of an architectural question I guess, but how would you go about making _detector take sensor without making the entire class a template?
It seems to me that I would have to fundamentally rewrite this part of the code, but maybe there is a simpler way?
|
you can use std::conditional_t:
class interface_actions
{
std::conditional_t<SOMETHING, sensor<real>, sensor<fake>> _detector;
};
if SOMETHING yields true, _detector will be of type sensor<real>, sensor<fake> otherwise.
but this only works if SOMETHING is outside of the scope of class interface_actions, otherwise you have to make the class take a template. As pptaszni suggested you could make a default template parameter to "hide" the template argument, so your old code that says interface_actions object; won't be affected:
template<bool is_real = true>
class interface_actions
{
std::conditional_t<is_real, sensor<real>, sensor<fake>> _detector;
};
int main() {
interface_actions foo;
static_assert(std::is_same_v<decltype(foo._detector), sensor<real>>);
}
|
73,702,736
| 73,702,935
|
C++ implicit cast - How to force a warning
|
I am following a C++ training and I found out a behavior I find weird in C++ when learning about explicit keyword.
About the following snippet, it will compile and execute without any error or warning (compile with G++).
When calling Foo(5), it will automatically do an implicit conversion and actually call Foo(A(5)).
I know I can forbid this behavior by making the constructor of A explicit : explicit A(int a); but my question is :
Is there a way to make G++ warn about implicit conversion like that if I forgot to do so?
I tried g++ with -Wall -Wextra, I saw stuff on -Wconversion on SO but still build without any warnings.
Looking on the internet I found out some warnings seem to exist for C and ObjC, but not for C++...
Source: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
The snippet:
#include <iostream>
class A{
public:
A(int a)
{
m_a = a;
};
int m_a;
};
void Foo(A a)
{
std::cout << "Hello : " << a.m_a << std::endl;
}
int main(int argc, char** argv)
{
Foo(5); // No Warning ?
return 0;
}
Output
Hello : 5
|
Is there a way to make G++ warn about implicit casts like that if I forgot to do so?
No, the fact that you have a choosen to have a non-explicit conversion constructor says that you want implicit conversion from int to Foo allowed.
If that is not desirable, then you always have the option of making this converting ctor explicit to forbid this completely. No way to have it both ways.
Now I realize that for code protection I should make all my CTORs explicit to avoid this, which I find a bit cumberstone
You pay for what you use.
|
73,703,378
| 73,718,381
|
Yaml node.size() returns 0
|
I've been experimenting with serialization and to get the hang of it I made a simple Test. I first call a function to Serialize my custom Color struct (a simple struct having the == operator and floats for r, g, b, and alpha values), this works, I can look into the file on my computer and the values are there:
YAML::Emitter out;
out << YAML::BeginSeq;
out << "Material";
out << YAML::BeginMap;
out << YAML::Key << "color";
out << YAML::Value << material.color;
out << YAML::EndMap;
out << YAML::EndSeq;
std::ofstream fout("assets/SerializationTest/Test.mat");
fout << out.c_str();
I have the overload operator<< for my Color struct that looks like this:
YAML::Emitter& operator<<(YAML::Emitter& out, const Color& col) {
out << YAML::Flow;
out << YAML::BeginSeq << col.r << col.g << col.b << col.a << YAML::EndSeq;
return out;
}
and the convert struct that looks like this:
template<>
struct convert<Copper::Color> {
static Node encode(const Copper::Color& col) {
Node node;
node.push_back(col.r);
node.push_back(col.g);
node.push_back(col.b);
node.push_back(col.a);
return node;
}
static bool decode(const Node& node, Copper::Color& col) {
if(!node.IsSequence() || node.size() != 4) return false;
col.r = node[0].as<float>();
col.g = node[1].as<float>();
col.b = node[2].as<float>();
col.a = node[3].as<float>();
return true;
}
};
Then I try to Load the File like this:
YAML::Node data = YAML::LoadFile("assets/SerializationTest/Test.mat");
Color col = data["color"].as<Color>();
But for some reason there is an error, I've figured out that in the decode function node.size() returns 0, I tracked the issue down and found out that it was caused because the variable m_isDefined from the file node_data.cpp is false. I tried to look this issue up but everywhere I looked it was either a completely different case or the questions wasn't even related to this. Any Ideas why this might be happening ?
|
Your code constructs the following YAML:
- Material
- color: [1, 2, 3, 4] # don't know the actual values
You can't do data["color"] on this structure because the root node is a sequence. Do
data[1]["color"]
instead.
|
73,703,496
| 73,703,817
|
Show video while saving it
|
I have a folder full of images, I need to save these images into the video while doing so I want to show the user the video being played from these images (frames). I can run two separate processes one for the saving and one for the showing but this is not what I am looking for, I want to do both in one step. If you know a solution please let me know.
My code uses C++ with OpenCV but feel free to share with me any code written with any language, or event a concept.
I use gStreamer, ffmpeg as well for the video generation, so I am not looking how to save a video or how to show the video I am looking for a process that can do both in one operation.
|
here's my quick brew using SFML. You have to link SFML and include the include folder. Simply set directory to your target folder, I use std::filesystem to add all files from that folder to a std::vector<std::string>.
#include <SFML/Graphics.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <filesystem>
void add_frame_to_video(std::string path) {
//your encoding stuff ...
}
int main() {
auto dimension = sf::VideoMode(1280u, 720u);
sf::RenderWindow window;
window.create(dimension, "Video Rendering");
sf::Texture frame_texture;
std::vector<std::string> frame_paths;
std::string directory = "resources/";
for (auto i : std::filesystem::directory_iterator(directory)) {
frame_paths.push_back({ i.path().string() });
}
std::size_t frame_ctr = 0u;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
if (frame_ctr >= frame_paths.size()) {
window.close();
return EXIT_FAILURE;
}
const auto& current_frame = frame_paths[frame_ctr];
add_frame_to_video(current_frame);
if (!frame_texture.loadFromFile(current_frame)) {
std::cout << "Error: couldn't load file \"" << current_frame << "\".\n";
window.close();
return EXIT_FAILURE;
}
sf::Sprite frame_sprite;
frame_sprite.setTexture(frame_texture);
++frame_ctr;
window.clear();
window.draw(frame_sprite);
window.display();
}
}
this will create a window that shows each picture per frame using sf::Texture to load and sf::Sprite to display the image. If no more frames are available, the window gets closed and the program terminates. If you want to add time between frames, you can set e.g. window.setFramerateLimit(10); to have 10 frames / second.
|
73,703,611
| 73,706,601
|
print callstack on every C++ exception throw in lldb
|
I'm using lldb and I'd like to catch all C++ based exceptions and print the callstack of the current thread for each breakpoint automatically, and continue.
This will stop on all exceptions break set -E C++, but how can set an automation that will print the callstack (bt command) and automatically continue?
Thnaks
|
These are all available as options to the break set command (see help break set for even more options). You want:
break set -E C++ -G 1 -C "bt"
You can also change the commands on a breakpoint after creation with the breakpoint command add command.
|
73,703,746
| 73,703,833
|
Is there a way for a class template to deduce the size of a parameter pack passed to the constructor?
|
If I have a class template like such:
template<typename T, size_t N>
struct foo
{
template<std::same_as<T>... Ts>
foo(Ts... ts);
}
Is there any way whatsoever to deduce the template parameter N from the size of the parameter pack passed to the foo constructor? So that foo can be instantiated like so:
auto f = foo(10,10,10); // foo<int, 3>
Or is it simply impossible? Is there no getting around having to type foo<int, 3>(10,10,10)?
|
Yes, a deduction guide for this is straight-forward:
template<typename T, typename... Ts>
requires (std::same_as<T, Ts> && ...) // optional
foo(T, Ts...) -> foo<T, sizeof...(Ts)+1>;
or
template<typename T, std::same_as<T>... Ts>
foo(T, Ts...) -> foo<T, sizeof...(Ts)+1>;
|
73,704,628
| 73,704,736
|
Why is the destructor of a function parameter not called at the end of the function, but at the end of the full expression making the function call?
|
Consider the following example:
#include <iostream>
struct A
{
int n = 0;
A() { std::cout << "A()" << std::endl; }
A(const A&) { std::cout << "A(const A&)" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
int f(A a) { std::cout << "f()" << std::endl; return 1; }
int main()
{
A a;
std::cout << f(a) << " was returned from f(A)" << std::endl;
std::cout << "leaving main..." << std::endl;
}
I expect the output of this program to be:
A()
A(const A&)
f()
~A()
1 was returned from f(A)
leaving main...
~A()
because when the function returns, its parameters should have already been destroyed. For example, if we have the following function:
A* g(A a) { std::cout << "g()" << std::endl; return &a; }
Dereferencing the returned pointer is undefined behavior:
std::cout << g(a)->n << std::endl; // undefined behavior
But the output is:
A()
A(const A&)
f()
1 was returned from f(A)
~A()
leaving main...
~A()
I'm looking for an explanation of this behavior.
|
Why is destructor for a function parameter not called at the end of the function but at the end of the full expression containing the function call?
According to [expr.call]/7
It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression.
The initialization and destruction of each parameter occurs within the context of the calling function.
So the standard allows either behaviour.
I'm looking for an explanation of this behaviour.
It's permitted by the standard, and that's how whichever compiler you tested chose to organize its code.
|
73,704,733
| 73,704,827
|
Deducing type of template value parameter
|
I was wondering if the type of a value template parameter could be deduced or obmitted when writing something similar to this:
enum class MyEnum {A, B}
enum class MyOtherEnum {X, Y}
template <typename T, T value>
struct GenericStruct {};
When using MyGenericStruct both T and value have to be passed, but T would be deducible from context typename T = decltype(value) except that value is not yet defined. template <auto value> isn't working either.
Is there any way to simply write MyGenericStruct<MyEnum::A> instead of MyGenericStruct<MyEnum, MyEnum::A> without usage of macros?
|
If you can use C++17, you can use auto as the type of the non-type template parameter. That gives you
template <auto value>
struct GenericStruct {};
Now, value will have its type deduced by its initializer just like if you had declared a variable with type auto and gives you the desired syntax of GenericStruct<MyEnum::A> foo; as seen in this live example.
|
73,704,804
| 73,836,415
|
Adjust translation speed of QML DragHandler
|
my question is about using a QML DragHandler to move a QML Item. I have successfully implemented position through dragging (when holding the Ctrl modifier) like so:
DragHandler {
dragThreshold: 0
acceptedModifiers: Qt.ControlModifier
}
Now I would like to add another handler that allows me to precisely position the element. Other software does this throught the use of the shift modifier. So what I want to do is move the element not by the pixel amount that the mouse moves, but an amount smaller than that. Ideally I would want to do something like this:
DragHandler {
dragThreshold: 0
acceptedModifiers: Qt.ShiftModifier
onActiveTranslationChanged: {
activeTranslation *= 0.5;
}
}
Unfortunatelly activeTranslation is read-only and I don't see any other property I could use and I can't think of any other way to do it... Does anybody have an idea?
Thank you very much in advance!
|
Unfortunately Qt doesn't provide any way to change the drag speed AFAIK.
But this is a way to achieve it:
Rectangle
{
id: theDraggableElement
width: 100
height: width
color: "red"
DragHandler
{
id: dragHandlerFast
dragThreshold: 0
acceptedModifiers: Qt.ControlModifier
target: theDraggableElement
}
}
Item
{
id: invisibleItemForSlowDragging
width: theDraggableElement.width
height: theDraggableElement.height
Binding { restoreMode: Binding.RestoreBinding; when: !dragHandlerSlow.active; target: invisibleItemForSlowDragging; property: "x"; value: theDraggableElement.x }
Binding { restoreMode: Binding.RestoreBinding; when: !dragHandlerSlow.active; target: invisibleItemForSlowDragging; property: "y"; value: theDraggableElement.y }
DragHandler
{
id: dragHandlerSlow
dragThreshold: 0
acceptedModifiers: Qt.ShiftModifier
target: invisibleItemForSlowDragging
onTranslationChanged:
{
theDraggableElement.x = invisibleItemForSlowDragging.x - dragHandlerSlow.translation.x / 2
theDraggableElement.y = invisibleItemForSlowDragging.y - dragHandlerSlow.translation.y / 2
}
}
}
I have tested this with Qt 5.15.2.
|
73,705,774
| 73,705,841
|
How can std::reference_wrapper<int> use operator+= if std::reference_wrapper doesn't have operator+=?
|
Thank you all, I didn't even know about user-defined conversion function and how it works.
Why is it possible to use std::reference_wrapper<int>::operator+=, if such an operator does not exist, are there some implicit conversions?
#include <iostream>
#include <functional>
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
template <typename C>
void test(C c)
{
c += 1;
}
int main()
{
int a = 3;
test(a);
std::cout << a << std::endl;
test(std::ref(a));
std::cout << a << std::endl;
}
Output:
3
4
To check that template works perfectly fine:
void test_2(std::reference_wrapper<int> c)
{
c += 1;
}
int main()
{
int a = 3;
test_2(std::ref(a));
std::cout << a << std::endl;
}
Output:
4
Still works as before. How is that possible?
Funny thing, that in auto d = b + c, d has an integer type.
int main()
{
auto b = std::ref(a);
auto c = std::ref(a);
auto d = b + c;
std::cout << type_id_with_cvr<decltype(d)>).pretty_name() << std::endl;
}
Output:
int
|
It's because it's implicitly convertible to a reference to T:
/* constexpr [c++20] */ operator T& () const noexcept;
In your case, it's implicitly convertible to an int&.
This ability to be implicitly convertible to an int& is also what would make it possible for you to define your function to take an int& while passing it a std::reference_wrapper<int>:
void test_2(int& c) // <--+
{ // |
c += 1; // |
} // |
int main() { // |
// ... // |
test_2(std::ref(a)); // >--+
}
|
73,706,697
| 73,706,809
|
Difference between template specialization and SFINAE with std::enable_if?
|
If I have a template function in C++, and want it to behave in a different manner in presence of a specific template parameter, I will use a template specialization:
#include <iostream>
#include <type_traits>
template<typename T> void myFunction(T&& input) {
std::cout << "The parameter is " << input << '\n';
}
template<> void myFunction<int>(int&& input) {
std::cout << "Double of the parameter is " << 2 * input << '\n';
}
int main() {
myFunction(24.2);
myFunction(24);
myFunction("Hello");
}
Use of std::enable_if<bool B> from <type_traits> enables to activate a similar behaviour for some specific template types. Any other type would cause a substitution error.
#include <iostream>
#include <type_traits>
template<typename T, std::enable_if_t<std::is_integral_v<T>>* = nullptr >
void myFunction(T&& input) {
std::cout << "Double of the parameter is " << 2 * input << '\n';
}
template<typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr >
void myFunction(T&& input) {
std::cout << "The parameter is " << input << '\n';
}
int main() {
myFunction(24.2);
myFunction(24);
// myFunction("Hello"); // compile-time substitution error
}
My question is: what is really the gain of using the fancier std::enable_if specialization, in place of the standard template specialization?
Are they really alternatives, or std::enable_if is exclusively for template metaprogramming?
|
These 2 approaches are executed on different stages.
First is overload resolution - on this stage template specialization is not used. Only generic template function prototype is in use.
On the other hand SFINAE approach drops the overloads that failed to be substituted silently on this stage leaving only one candidate based on enable_if conditions.
Second step is template instantiation - here the body of your function is created - and it will use body provided by most specialized template.
|
73,706,974
| 73,707,256
|
When using VS2022 (v17.0.1.0), the complier can not recognize "string", and sends me an error. When I replace the string by const char*, it works
|
I have tried searching on Google, only to find nothing.
And it seems the manual also doesn't work.
Here is my code:
account.h
#include <string>
#include "Date.h"
class SavingsAccount
{
public:
void show();
void deposit(Date now_date, double money, string ways);
void withdraw(Date now_date, double money, const char* ways);
void settle(Date new_date);
SavingsAccount(Date date_new, const char* id_new, double rate_new);
void accountshow();
static double getTotal();
static SavingsAccount* point;
static int sum_account;
static double sum_money;
private:
const char* id;
double balance = 0;
double rate = 0;
int lastDate = 0;
Date date;
double interest = 0;
};
account.cpp
#include <iostream>
#include <string>
#include "account.h"
#include "Date.h"
using namespace std;
double SavingsAccount::sum_money = 0;
void SavingsAccount::deposit(Date now_date, double money, string ways) //<--- here is the problem
{
interest += balance * (now_date - date) * rate / 366;
date = now_date;
date.show();
cout << "\t#" << id << "\t" << money << "\t" << money + balance << "\t"<<ways << endl;
balance += money;
sum_money += money;
}
void SavingsAccount::withdraw(Date now_date, double money, const char* ways) //取款
{
interest += balance * (now_date - date) * rate / 366;
date = now_date;
date.show();
cout << "\t#" << id << "\t-" << money << "\t" << balance - money << "\t" << ways << endl;
balance -= money;
sum_money -= money;
}
void SavingsAccount::settle(Date new_date) //结算利息
{
interest += balance * (new_date - date) * rate / 366;
interest = (int(interest * 100 + 0.5)) / 100.0;
sum_money += interest;
date = new_date;
date.show();
cout << "\t#" << id << "\t" << interest << "\t" << interest + balance << " interest"<<endl;
balance += interest;
interest = 0;
}
void SavingsAccount::accountshow()
{
this->date.show();
cout << "\t" << "#" << id << " created" << endl;
}
void SavingsAccount::show()
{
cout << id << "\tBalance: " << balance;
}
SavingsAccount::SavingsAccount(Date date_new, const char* id_new, double rate_new) : id(id_new)
{
date = date_new;
rate = rate_new;
//sum_account++;
balance = 0;
interest = 0;
accountshow();
}
double SavingsAccount::getTotal()
{
return sum_money;
}
bank.cpp:
#include "account.h"
#include <iostream>
using namespace std;
int main()
{
Date date(2008, 11, 1);
SavingsAccount accounts[] = {
SavingsAccount(date, "S3755217", 0.015),
SavingsAccount(date, "02342342", 0.015)
};
const int n = sizeof(accounts) / sizeof(SavingsAccount);
string works = "salary";
accounts[0].deposit(Date(2008, 11, 5), 5000, works);
accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");
cout << endl;
for (int i = 0; i < n; i++) {
accounts[i].settle(Date(2009, 1, 1));
accounts[i].show();
cout << endl;
}
cout << "Total: " << SavingsAccount::getTotal() << endl;
return 0;
}
Because of the limited length for this, I did not show the Date.h and Date.cpp, and there is nothing wrong with it. But I will show it to you if you need.
Here is the problem, and I translate the error the VS tells me into English:
VS also says:
'void SavingsAccount::deposit(Date,double,std::string)' there is no overloading member function declared in SavingsAccount
But when I replace the string by const char*, just like what I write in the withdraw() function, it works without any problem.
So, could you please tell me how can I use string to finish this problem? Because const char* is so uncomfortable to be used.
|
In account.h, you have #include <string>, but you do not have using namespace std; (and rightly so), so the compiler doesn't know what string is. You have to use std::string instead, eg:
void deposit(Date now_date, double money, std::string ways);
Or, use using std::string, at least (not recommended in a header, though):
using std::string;
...
void deposit(Date now_date, double money, string ways);
In account.cpp and bank.cpp, you have using namespace std; after #include <string>, so the compiler can work out what string is without needing you to qualify it with std::.
|
73,707,192
| 73,707,735
|
C++ - Pass member functions of any class to another class
|
I am in the process of writing a template class that would implement a Listener interface for every component that would need it within my application. I want a component to be able to listen to changes to an individual field within a listened object. The fields of each object are represented by an enum, and I've got a simple Notifier/Publisher that works great as such:
template <typename EFieldsEnum>
class AbstractNotifier
{
public:
void addListener(EFieldsEnum listenedField, INotifierListener<EFieldsEnum>* listener)
{
if (_listeners.find(listenedField) == _listeners.cend())
{
std::unordered_set<INotifierListener<EFieldsEnum>*> listeners;
listeners.insert(listener);
_listeners.emplace(listenedField, listeners);
}
else
{
_listeners.find(listenedField)->second.insert(listener);
}
}
void notify(EFieldsEnum updatedField)
{
for (INotifierListener<EFieldsEnum>* listener : _listeners[updatedField])
{
listener->onUpdate(updatedField);
}
}
protected:
std::unordered_map<EFieldsEnum, std::unordered_set<INotifierListener<EFieldsEnum>*>> _listeners;
};
I am trying to change the method signature slightly, in order for each listening component to register by passing a void() method that would be called as a callback, rather than implement the onUpdate generic method followed by a switch case. Ideally, I would want my listening components (say, Component1) to register without having to define a specific Listener interface for each type of Notifier that I will have, as such :
notifier.addListener(FieldEnum::MyField1, this, &Component1::onMyField1Updated);
and then Component2 could also register as such :
notifier.addListener(FieldEnum::MyField1, this, &Component2::someOtherMethod);
without Component1 and Component2 needing to implement a common interface. Would this be possible? I am struggling to figure out what type is expected to generically represent the member method that is passed through :
class IListener {};
void (IListener::*ListenerCallback)();
template <typename EFieldsEnum>
class AbstractNotifier
{
public:
void addListener(EFieldsEnum listenedField, IListener* listener, ListenerCallback listenerCallback)
{
std::pair<IListener*, ListenerCallback> pairToAdd = std::make_pair<IListener*, ListenerCallback>(listener, ListenerCallback);
if (_listeners.find(listenedField) == _listeners.cend())
{
std::unordered_set<std::pair<IListener*, ListenerCallback>> listenersAndCallbacks;
listenersAndCallbacks.insert(pairToAdd);
_listeners.emplace(listenedField, listenersAndCallbacks);
}
else
{
_listeners.find(listenedField)->second.insert(pairToAdd);
}
}
void notify(EFieldsEnum updatedField)
{
for (const std::pair<IListener*, ListenerCallback>& listenerAndCallback : _listeners[updatedField])
{
IListener* listener = listenerAndCallback.first;
ListenerCallback listenerCallback = listenerAndCallback.second;
listener->*listenerCallback();
}
}
protected:
std::unordered_map<EFieldsEnum, std::unordered_set<std::pair<IListener*, ListenerCallback>>> _listeners;
};
|
Use std::function<void()>
Here's a somewhat simplified version of your AbstractNotifier that will accept callbacks from any class (or no class at all):
template <typename EFieldsEnum>
class AbstractNotifier
{
public:
void addListener(EFieldsEnum listenedField, std::function<void()> listenerCallback)
{
listeners_[listenedField].push_back(listenerCallback);
}
// Helper method template to wrap member function pointers
template <typename Listener>
void addListener(EFieldsEnum listenedField, Listener* listener, void(Listener::*listenerCallback)())
{
addListener(listenedField, [=]() { (listener->*listenerCallback)(); });
}
void notify(EFieldsEnum updatedField)
{
for (auto& callback : listeners_[updatedField])
{
callback();
}
}
protected:
std::unordered_map<EFieldsEnum, std::vector<std::function<void()>>> listeners_;
};
Demo
Note that I gave up the "uniqueness" constraint that your current implementation has and used a std::vector. This is because it's difficult to impossible to really compare std::functions, and it's easy to have very different looking std::functions that end up calling back to the same underlying code.
i.e. All three of the following end up calling the same member function, but hold totally different types and can't be easily compared:
// Different lambdas, so different types
std::function<void()> f1([&someObject]() { someFunc.foo(); });
std::function<void()> f2([&someObject]() { someFunc.foo(); });
std::function<void()> f3(std::bind(&SomeType::foo, someObject));
|
73,707,348
| 73,707,521
|
Meaning of "->second" and self-made comments
|
I am trying to write a description of each of the actions in the code by commenting on things performed in the code.
Could you please help me understand what does "createdCode->second" do and re-check if my made comments about the other parts are correct?
Here is the code:
#include <map>
#include <string>
#include <iostream>
int main() {
// Stores everything that is that specific std namespace and dumps it in the global namespace as characters in key-value pairs and declares them as strings.
std::map<char, std::string> natoAlphabet = {
{'A', "Alfa"}, {'B', "Bravo"}, {'C', "Charlie"},
{'D', "Delta"}, {'E', "Echo"}, {'F', "Foxtrot"},
{'G', "Golf"}, {'H', "Hotel"}, {'I', "India"},
{'J', "Juliet"}, {'K', "Kilo"}, {'L', "Lima"},
{'M', "Mike"}, {'N', "November"}, {'O', "Oscar"},
{'P', "Papa"}, {'Q', "Quebec"}, {'R', "Romeo"},
{'S', "Sierra"}, {'T', "Tango"}, {'U', "Uniform"},
{'V', "Victor"}, {'W', "Whiskey"}, {'X', "Xray"},
{'Y', "Yankee"}, {'Z', "Zulu"}, {'0', "Zero"}
};
// Declare the input & Open Terminal
char ch;
std::cin >> ch;
// Created a variable that has a complicated type and find the element from declared characters in the array as strings.
auto createdCode = natoAlphabet.find(ch);
// Execute the If Statement that checks if inputed values will match the information in the natoAlphabet array.
// If it does not match - output "Not recognized:".
if (createdCode == natoAlphabet.end())
std::cout << "Not recognized." << std::endl;
else
std::cout << createdCode->second << std::endl;
return 0;
}
|
find returns an iterator. When you are confused by types, I suggest to stay away from auto for a moment. auto is not to ignore what the actual type is (at least to my understanding).
std::map<char,std::string>::iterator iter = natoAlphabet.find(ch);
If find cannot find the element then it returns natoAlphabet.end(), the end iterator that refers to an element one past the last element. So actually it does not refer to an element in the map. It is just used to denote the end of the map. find uses it to indicate that the element was not found:
if (iter == natoAlphabet.end())
std::cout << "Not recognized." << std::endl;
When the element is found, then the iterator refers to a std::pair<const char,std::string>, because thats the type of elements in a std::map<char,std::string>. You get a reference to the key via iter->first and a reference to the mapped value via iter->second. Hence,
else
std::cout << iter->second << std::endl;
Prints the std::string for the key ch when there is an element with that key in the map.
For more details I refer you to https://en.cppreference.com/w/cpp/container/map
PS: Unless you need the map to be sorted you shoud rather use std::unorderd_map.
|
73,708,226
| 73,708,435
|
gst_parse_launch there is no proper conversion function from string to gchar
|
I have a simple code with c++ using gstreamer to read rtsp video.
I'm new to gstreamer, I couldn't concatenate gst_parse_launch() with a URL_RTSP variable for my rtsp links.
here is no variable URL_RTSP, that works:
/* Build the pipeline */
pipeline = gst_parse_launch("rtspsrc protocols=tcp location=rtsp://user:pass@protocol:port/cam/realmonitor?channel=1&subtype=0 latency=300 ! decodebin3 ! autovideosink", NULL);
/* Start playing */
gst_element_set_state (pipeline, GST_STATE_PLAYING);
with the variable URL_RTSP, doesn't work:
/*Url Cams*/
std::string URL_RTSP = "rtsp://user:pass@protocol:port/cam/realmonitor?channel=1&subtype=0";
/* Build the pipeline */
pipeline =
gst_parse_launch("rtspsrc protocols=tcp location="+ URL_RTSP + " latency=300 ! decodebin3 ! autovideosink", NULL);
/* Start playing */
gst_element_set_state (pipeline, GST_STATE_PLAYING);
Error when I try to use with variable, gst_parse_launch() get the error:
there is no proper conversion function from "std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>" to "const gchar *"
|
gst_parse_launch takes a const gchar* as the first argument:
GstElement* gst_parse_launch (const gchar* pipeline_description, GError** error)
But, what you provide,
"rtspsrc protocols=tcp location="+ URL_RTSP +
" latency=300 ! decodebin3 ! autovideosink"
results in a std::string. I suggest creating the std::string first, then use the c_str() member function to pass it a const char*.
std::string tmp =
"rtspsrc protocols=tcp location=" + URL_RTSP +
" latency=300 ! decodebin3 ! autovideosink";
pipeline = gst_parse_launch(tmp.c_str(), nullptr);
|
73,708,679
| 73,709,470
|
How to properly wrap a two dimensional vector using %template
|
I'm trying to make a basic csv parser in c++ for a particular csv schema, and I'm trying to wrap the function for Python, but I keep getting a "StdVectorTraits not found" warning after wrapper generation. The wrapper is still able to be compiled using g++, but when I try to import the underlying shared object using the object.py script, I get "ImportError: undefined symbol: _Z8myVectorRNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"
This is the swig interface file:
%module parser;
%include "/usr/share/swig4.0/std/std_vector.i";
%include "/usr/share/swig4.0/std/std_iostream.i";
%include "/usr/share/swig4.0/std/std_sstream.i";
%include "/usr/share/swig4.0/std/std_string.i";
%include "/usr/share/swig4.0/std/std_basic_string.i";
%{
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
std::vector<std::vector<double>> myVector(std::string&);
%}
%template(doubleVector) std::vector<double>;
%template(doubleVecVector) std::vector<std::vector<double>>;
std::vector<std::vector<double>> myVector(std::string& path)
{
std::ifstream file;
std::string read;
std::vector<std::vector<double>> data;
file.open(path);
for (int i = 0; i < 21; i++)
{
std::getline(file, read);
}
for (int i = 0; i < 32; i++)
{
std::vector<double> line;
std::getline(file, read);
std::stringstream ss(read);
for (int j = 0; j < 48; j++)
{
std::getline(ss, read, ',');
line.push_back(std::stof(read));
}
data.push_back(line);
}
file.close();
return data;
}
Error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/../test.ipynb Cell 1 in <cell line: 1>()
----> 1 import parser
File ~/../parser.py:15, in <module>
13 from . import _parser
14 else:
---> 15 import _parser
17 try:
18 import builtins as __builtin__
ImportError: /home/../_parser.so: undefined symbol: _Z8myVectorRNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
|
The function definition should be between %{ and %}. Everything between %{/%} is included directly in the generated wrapper. The function prototype should be at the end of the file after the %template declarations to direct SWIG to generate a wrapper for that function.
Since the function body is in the wrong place it isn't defined hence the undefined symbol error.
Stripped down example:
test.i
%module test
%{
#include <vector>
std::vector<std::vector<double>> myVector()
{
return {{1.0,1.5},{2.0,2.5}};
}
%}
%include <std_vector.i>
%template(doubleVector) std::vector<double>;
%template(doubleVecVector) std::vector<std::vector<double>>;
std::vector<std::vector<double>> myVector();
Demo:
>>> import test
>>> test.myVector()
((1.0, 1.5), (2.0, 2.5))
|
73,708,720
| 73,709,559
|
Call a non-default constructor for a concept
|
I am making a dependency injection system via static polymorphism with C++20 concepts, so I have this example
I have an interface contract for a Logger:
template <typename TLogger>
concept ILogger = requires(TLogger engine) {
{ engine.LogInfo(std::declval<std::string>()) } -> std::same_as<void>;
{ engine.LogError(std::declval<int>(), std::declval<std::string>()) } -> std::same_as<void>;
};
A particular implementation of that interface with 2 ctors, a default and a non-default:
class MyLoggerImplementation
{
public:
MyLoggerImplementation() : x(0)
{
}
MyLoggerImplementation(int code) //non default constructor
{
x = code;
}
//Interface methods
public:
void LogInfo(std::string errorMessage)
{
std::cout << std::format("Info: {}!\n", errorMessage);
}
void LogError(int errorCode, std::string errorMessage)
{
std::cout << std::format("Error: {}! with code: {}\n", errorMessage, errorCode);
}
// private members
private:
int x;
};
Then my DatabaseAccessor has a dependency to a Logger:
template<ILogger Logger>
class DatabaseAccessor
{
public:
DatabaseAccessor() { }
public:
bool QueryAll()
{
logger.LogInfo("querying all data");
//...
return true;
}
// Injected services
private:
Logger logger;
};
And then when I try to instantiate a DatabaseAccessor and I inject the Logger dependency with MyLoggerImplementation it will call the default constructor:
int main()
{
DatabaseAccessor<MyLoggerImplementation> db; // this will instantiate with the default constructor
// DatabaseAccessor<MyLoggerImplementation(10)> db; // ???
db.QueryAll();
}
How can I instantiate MyLoggerImplementation with that non-default constructor?
|
You could take an instance of the logger as a parameter:
template <ILogger L>
class DatabaseAccessor
{
L logger;
public:
explicit DatabaseAccessor(L logger) : logger(std::move(logger)) { }
};
If you need something more involved than this (like your logger isn't move-constructible), then instead of taking an L you take a function that returns an L:
template <class F, class T>
concept FactoryFor = std::invocable<F> and std::same_as<std::invoke_result_t<F>, T>;
template <ILogger L>
class DatabaseAccessor
{
L logger;
public:
template <FactoryFor<L> F>
explicit DatabaseAccessor(F factory) : logger(f()) { }
};
This approach has advantages over just forwarding arguments into the logger:
it works just fine when you add another member you need to initialize
it allows for using braced-init-lists to initialize the logger
it's clearer on the call-site (consider DatabaseAccessor<OstreamLogger> da(std::cout); - what's the accessor doing with cout vs DatabaseAccessor da(OstreamLogger(std::cout));)
Note that this:
template <typename TLogger>
concept ILogger = requires(TLogger engine) {
{ engine.LogInfo(std::declval<std::string>()) } -> std::same_as<void>;
{ engine.LogError(std::declval<int>(), std::declval<std::string>()) } -> std::same_as<void>;
};
could really be:
template <typename TLogger>
concept ILogger = requires (TLogger engine, int i, std::string s) {
{ engine.LogInfo(s) } -> std::same_as<void>;
{ engine.LogError(i, s) } -> std::same_as<void>;
};
The two aren't exactly identical (I'm passing in lvalues while you're passing in rvalues), but I doubt that distinction will matter in your use-case.
|
73,709,270
| 73,709,334
|
Template type deduction C++
|
I am getting an error qualified-id in declaration before ‘<’ token from the following code:
// g++ -std=c++20 example.cpp
#include <iostream>
template <typename U = int>
struct Example {
template <typename T>
static void execute() {
std::cout << "Hey" << std::endl;
}
};
int main() {
Example::execute<float>();
}
When I include the type for Example, such as Example<int>::execute<float>() it compiles successfully. Shouldn't the compiler be able to deduce the type since I specified it as default value?
|
Class template argument deduction only applies when creating objects.
That is Example e; will deduce Example<int> e; via the default argument.
You are not creating an object though, and Example is not a class. You must include a template argument list. In this case, it can be empty though, since the template argument includes a default:
Example<>::execute<float>();
|
73,710,730
| 73,712,997
|
How can both CRect and CRect* be input arguments to GetClientRect?
|
Beginner question.
In Win32API, the second parameter of ::GetClientRect is LPRECT, but It receives both CRect and CRect*.
I tried to see how LPRECT is defined, but it seems just an ordinary pointer to struct:
typedef struct tagRECT
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;
And CRect inherits tagRECT:
class CRect :public tagRECT {...}
Using MFC, CWnd::GetClientRect works the same way:
CRect rect;
GetClientRect(&rect); // works
GetClientRect(rect); // works too.
How is this possible? Please let me know if I am missing some basic concepts of C++.
|
During overload resolution1 the compiler builds a set of candidate functions that match the arguments. If none of the functions' signatures exactly match the arguments the compiler will then try to apply implicit conversions, at most one per argument.
That's what makes both calls possible, though the implicit conversion is different in either case:
GetClientRect(&rect);
In this function call expression, &rect has type CRect*, with CRect publicly deriving from RECT, so an implicit pointer conversion from CRect* to RECT* (aka LPRECT) is done.
GetClientRect(rect);
Here, on the other hand, rect has type CRect. C++ doesn't provide any built-in conversions from CRect to RECT*, so user-defined conversions are considered. Specifically, there's a conversion operator CRect::operator LPRECT that produces a RECT* pointer given a CRect object.
It is of crucial importance to appreciate, that both function call expressions do different things. In the second case the compiler literally injects a call to operator LPRECT() prior to calling GetClientRect(). There's nothing in the language that mandates that the conversion operator must behave any given way, and it's down to library authors to provide a sane implementation.
In this case, operator LPRECT() behaves as one would expect, and both function calls have the same observable behavior. Now that you have two ways to do the same thing, guidance is required to make a judicious choice:
While there are no strict rules on which of the options to use, it's down to opinion. I would recommend GetClientRect(&rect) for a few reasons:
Easier to understand for readers of the code
Pointer arguments are frequently used as [out] parameters where implementations write their results
Less ambiguous: GetClientRect(rect) looks like pass-by-value, or maybe the object is bound to a reference. In reality, neither one it is, and the (invisible) conversion operator is called instead
No more expensive than the version that uses the conversion operator
1 Overload resolution is a core language feature. The set of rules driving this part of the language, however, make it anything but basic. It's something you'll eventually have to learn, but it's a very steep learning curve. The cppreference.com link gives you a glimpse at the complexity involved.
|
73,711,949
| 73,712,373
|
Object created in Python via Pybind11 not recognized as a derived class by C++ functions
|
The minimum code to reproduce the issue is as follows:
aaa.hpp
#include <string>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <cassert>
#include <utility>
template <typename D>
class BaseClass{
/* The base class. */
protected:
bool skip_nan = true;
};
template <typename D>
class DerivedClass : public BaseClass<D>{
public:
explicit DerivedClass(bool skip_nan_){ this->skip_nan = skip_nan_; }
};
aaa_py.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "aaa.hpp"
namespace py = pybind11;
template <typename D>
void fff(BaseClass<D>& rs){
}
PYBIND11_MODULE(aaa_py, m) {
m.def("fff_float", &fff<float>);
py::class_<DerivedClass<float>>(m, "DerivedClass_float").def(py::init<bool>(), py::arg("skip_nan")=true);
}
test.py
import aaa_py as rsp
ds = rsp.DerivedClass_float()
rsp.fff_float(ds)
Error:
Traceback (most recent call last):
File "usage_example_python.py", line 8, in <module>
rsp.fff_float(ds)
TypeError: fff_float(): incompatible function arguments. The following argument types are supported:
1. (arg0: BaseClass<float>) -> None
Invoked with: <aaa_py.DerivedClass_float object at 0x000002C9EAF57308>
Basically the error is saying that function fff_float expects somebody from BaseClass<float>, but receives DerivedClass<float>. If I change the function to accept DerivedClass<D>&, then there would be no errors. Or, if I create an instantiation of DerivedClass<float> directly in c++ and pass it to the float_fff, there would also be no issues. So it seems that the issue is that for an object created in Python, somehow the information about its base class is lost. How can I deal with this?
|
You need to declare BaseClass<float> in Python and tell pybind11 that DerivedClass_float extends it.
PYBIND11_MODULE(MyModule, m)
{
m.def("fff_float", &fff<float>);
// declare base class - this simply expose to Python, it's impossible to
// construct a BaseClass_float in Python since no constructor is provided
py::class_<BaseClass<float>>(m, "BaseClass_float");
// tell pybind11 that DerivedClass<float> extends BaseClass<float>
py::class_<DerivedClass<float>, BaseClass<float>>(m, "DerivedClass_float")
// ^^^^^^^^^^^^^^^^
.def(py::init<bool>(), py::arg("skip_nan") = true);
}
|
73,712,346
| 73,712,400
|
Why is the c++ program outputting a wrong negative number
|
#include <iostream>
int main() {
int woe; // weight on earth
int wom = woe * 2; // weight on mars
std::cout << "Enter your weight on earth: \n";
std::cin >> woe;
std::cout << "Your weight on mars would be " << wom << " Pounds\n";
}
Hello everyone I just started to learn c++ and when I try to multiply the variable "woe" by 2 it prints a big negative number like "-2123145280 Pounds" when I input 100. please help thank.
|
When you just define an integer variable without assignment in C++ it takes a random number, then you are just doubling that random number in wom variable and after that you take input. A more correct version of your code is:
#include <iostream>
int main() {
int woe = 0; // weight on earth
std::cout << "Enter your weight on earth: \n";
std::cin >> woe;
int wom = woe * 2; // weight on mars
std::cout << "Your weight on mars would be " << wom << " Pounds\n";
}
|
73,712,592
| 73,712,706
|
Why unordered_map not showing correct index values of a vector?
|
I have a string "codeforces" and now when i am storing characters of this string as key in an unordered map and index of occurrence of that character in a vector inside unordered map as value , then it is not showing correct indexes .
In this string "codeforces" character 'c' is occurring at index 1 and 8 , i would like to store character c as key in map and corresponding indexes of occurrences inside vector as value in unordered map . But when i am doing this it is not showing correct value . Can any body tell me why is this happening ?
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string x = "codeforces";
unordered_map<char,vector<int>> data;
for(int i = 1;i <= x.size();i++){
data[x[i]].push_back(i);
}
for(auto it : data){
if(it.first == 'c'){
vector<int> out = it.second;
for(int j = 0;j < out.size();j++){
cout<<out[j]<<" ";
}
cout<<endl;
}
}
return 0;
}
Output should be like this (for character 'c') -> 1 8 .
But it is showing -> 7 .
|
your for loop has a wrong range. You start at element 1 and because of <= only stop at the size of codeforces + 1, which is out of bounds.
When iterating arrays the index starts at 0 and should end at size() - 1. This can be easily achieved by saying < size() as the less operator will result in false if the index is at size() - therefore size() - 1 is the last iteration step.
You have two options, either go from 1 to size() and access [i - 1]
for(int i = 1; i <= x.size(); i++){
data[x[i - 1]].push_back(i);
}
or go from 0 to size() - 1 and push_back(i + 1)
for(int i = 0; i < x.size(); i++){
data[x[i]].push_back(i + 1);
}
I recommend the latter, as it's the common way to iterate arrays.
read here why you should avoid writing using namespace std;.
|
73,713,812
| 73,714,056
|
Open with linux context menu opens the app twice QT
|
I have done the command line processing in my QT application so I can set it as default for audio files. But while I try to open an audio file with my QT application again, it opens a new window.
Is there a way to make it so it opens the new file in the same window, if that file is open from a file manager with my application?
|
write a file whenever your app starts. Proceed or exit according to the contents of the file.
or try make your app single instance?
https://github.com/itay-grudev/SingleApplication
|
73,713,872
| 73,714,245
|
How to use 'std::enable_if_t' inside templated class, without introducing second template argument
|
I have a 100% working code, of Vector wrapper which does resizing differently for various types of vectors. However, when defining std::enable_if_t, I use
template <typename C = Vec>
instead of using 'Vec' directly. Is there a way to reuse template argument 'Vec' of the class for its resizeListTo() method?
Full code:
template <class Vec>
class MyVectorWrapeer<Vec> {
private:
template <typename C = Vec>
std::enable_if_t<someCondition<C, typename C::value_type>, void>
static inline resizeListTo(C& c, uint32_t size) { /*Some Code*/ }
template <typename C = Vec>
std::enable_if_t<!someCondition<C, typename C::value_type>, void>
static inline resizeListTo(C& c, uint32_t size) { /*Different Code*/ }
public:
static void deserializeVector(Vec* dst) {
...
resizeListTo(*dst, size);
...
}
I mean, something like
template <>
std::enable_if_t<someCondition<Vec, typename Vec::value_type>, void>
static inline resizeListTo(Vec& c, uint32_t size) {
(The above code obviously does not compile)
|
In C++20, you have requires to add constraint to the method:
template <class Vec>
class MyVectorWrapeer<Vec>
{
private:
static void resizeListTo(Vec& c, uint32_t size) requires(someCondition<Vec>)
{ /*Some Code*/ }
static void resizeListTo(Vec& c, uint32_t size) requires(!someCondition<Vec>)
{ /*Different Code*/ }
};
From your example, you want different implementations, so tag dispatch:
template <class Vec>
class MyVectorWrapeer<Vec>
{
private:
static void resizeListTo_impl(Vec& c, uint32_t size, std::true_type) { /*Some Code*/ }
static void resizeListTo_impl(Vec& c, uint32_t size, std::false_type) { /*Different Code*/ }
static void resizeListTo(Vec& c, uint32_t size)
{
resizeListTo_impl(c, size, std::bool_constant<someCondition<Vec>>{});
}
};
or since C++17, if constexpr (regular if might even do the job pre-c++17 if both branches are compilable):
template <class Vec>
class MyVectorWrapeer<Vec>
{
private:
static void resizeListTo(Vec& c, uint32_t size)
{
if constexpr (someCondition<Vec>) {
/*Some Code*/
} else {
/*Different Code*/
}
}
};
|
73,714,507
| 73,715,515
|
how to derive a class (from e.g. Eigen::VectorXf) with (only) an extra static method while retaining all the base constructors?
|
Let's say I need to attach some 'type id' to my Eigen::VectorXf vectors.
So far I have something like this (simplified for brevity):
struct MyVector123
{
Eigen::VectorXf vec;
static int id() {return 123};
};
struct MyVector456
{
Eigen::VectorXf vec;
static int id() {return 456};
};
(Please don't argue with me it's a poor design and I should not do this. You might be very right, but the legacy code I'm using requires me to do so...)
This is working fine but forces me to use .vec everywhere. I was wondering if I could do slightly better by deriving from Eigen::VectorXf directly, something like:
struct MyVector123 : public Eigen::VectorXf
{
static int id() {return 123};
};
struct MyVector456 : public Eigen::VectorXf
{
static int id() {return 456};
};
The problem is that this doesn't seem to allow me to recycle all the base constructors, e.g. MyVector123 x = MyVector123::Random(10) generates a compile error:
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Am I missing something simple to make this work?
|
You need to inherit the constructor (c++ 11)
struct MyVector123 : public Eigen::VectorXf
{
using Eigen::VectorXf::VectorXf;
static int id() {return 123};
};
|
73,714,725
| 73,715,012
|
Application crashes if (own) dll try to allocate a few MB of RAM
|
I'm not a good c++ programmer and I'm not very familiar creating DLLs for other application. My main programming language is Java so I'm having a little trouble with coding c++ and compiling with MinGW. However, as we need some small portion of "native" code for our main application (which is coded in Cobol) I was needed to try to do this with c++.
In general my DLL has a small footprint of memory usage as I'm doing nothing special with it. This DLL is mainly there to communicate with an external process using sockets.
As far as I can tell the DLL itself is fine and my problem must be more "specific" and is not a general c++ coding problem. Somewhere in my code I try to allocate some "large" amount of RAM with char buf[size]; and later read file content into this buffer.
size can be a few kilobyte up to a few megabyte (not more than 10MB). If the size is getting somewhere near to 1MB our main application crashes after above mentioned statement (I pinpoint this down to that statement using logging outputs). If I compile my DLL as an EXE file and test the function directly (using Windows console) all is going fine and no crash happens. Even if I use several more MB for this buffer there is no problem with it. This leads me to suspect that there must be some sort of upper limit on memory usage using my DLL which causes the main application to crash hardly if my dll try to grab more memory as it may be allowed to.
So my question is:
Could it be that there is some sort of upper limit a DLL can/may use? And if yes, is there some kind of compiling switch or option I need to use while generating my DLL to overcome this limitation?
Our main application is using several other DLLs which using way more memory as my DLL try to use so this is not a limitation of our main application.
Here is the whole function which try to read the file:
/**
* Read file content as Base64 Data
*/
char* readFileAsBase64(const char* filename) {
FILE *file;
if(!fileExists(filename)) {
return NULL;
}
long size = (long)fileSize(filename);
file = fopen(filename, "rb");
char ch;
// Crach happens here if 'size' is too large
char buf[size];
/* copy the file */
for(long i = 0; i<size; i++) {
ch = fgetc(file);
if(ferror(file)) {
return NULL;
}
if(!feof(file)) {
buf[i] = ch;
}
}
if(fclose(file)==EOF) {
return NULL;
}
return b64_encode(buf, size);
}
|
Yes, that's a stack allocation (and not legal C++ either).
Simple fix is to use a std::string
#include <string>
...
std::string buf
buf.resize(size);
...
return b64_encode(buf.data(), size);
No other code changes needed. Although you could make further changes to use std::string throughout your code, instead of using raw pointers.
|
73,714,951
| 73,715,265
|
Why do references to moved values not dangle after the lvalue that the object was moved into goes out of scope?
|
While playing around with references to lambdas I encountered a scenario where I expected the program to crash due to dangling references. In the following program, I assumed that the lambda argument to fn_x_3 in main is "moved to" the fn_x_3 function because it's an rvalue, where it binds to the lvalue fn.
#include <iostream>
#include <functional>
std::function<int(int)> fn_x_3(std::function<int(int, int)>& fn) {
// capture fn by reference!
return [&fn](int x) {
return fn(x, 3);
};
}
std::function<int(int)> fn_x_3(std::function<int(int, int)>&& fn) {
// passing fn (lvalue) by reference to fn_x_3 overload
return fn_x_3(fn);
}
int main()
{
// call to fn_x_3(function<int(int)>&& fn), lambda "moved into" the function
auto fn = fn_x_3([](int x, int y){ return x + y; });
int result = fn(2);
std::cout << result << std::endl;
return 0;
}
This program prints out 5. But when fn goes out of scope in fn_x_3(function<int(int,int)>&&), does this not invalidate the reference that is captured in fn_x_3(function<int(int,int)>&)?
|
It does, pretty much second function overload fn_x_3 is ok BUT if you use the return value in any way outside the scope of the function you are invoking UB by using object past its lifetime (the object is the underlying lambda structure of first fn_x_3 overload).
It is not enforced by the C++ compiler to block compilation of such programs.
If you want to find these kinds of error you could use so called address sanitizers.
Programs prints 5 - it is most likely due to the fact that the memory that you are accessing is still "bound" to the executable thus it doesn't see any access violations (std::function implementation detail)
|
73,715,505
| 73,715,765
|
Implicit conversion of initializer lists and perfect forwarding
|
I'm trying to make perfect forwarding work with initializer lists. For the sake of the example, I'd like to have a variadic function that calls into another function, and still enjoy automatic conversion of initializer lists of the latter:
#include <iostream>
#include <vector>
void hello(std::string const& text, std::vector<int> const& test)
{
std::cout << "hello " << text << " " << test.size() << std::endl;
}
template<class ... Args>
void f(Args&& ... args)
{
return hello(std::forward<Args>(args)...);
}
int main()
{
hello("world", {1,2,3}); // WORKS
f("world", std::vector<int>({1,2,3})); // WORKS
f("world", {1,2,3}); // COMPILER ERROR
}
The error is
example.cpp: In function ‘int main()’:
example.cpp:21:21: error: too many arguments to function ‘void f(Args&& ...) [with Args = {}]’
21 | f("world", {1,2,3});
| ^
example.cpp:12:6: note: declared here
12 | void f(Args&& ... args)
| ^
example.cpp: In instantiation of ‘void f(Args&& ...) [with Args = {}]’:
example.cpp:21:21: required from here
example.cpp:14:15: error: too few arguments to function ‘void hello(const string&, const std::vector<int>&)’
14 | return hello(std::forward<Args>(args)...);
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
example.cpp:6:6: note: declared here
6 | void hello(std::string const& text, std::vector<int> const& test)
| ^~~~~
Am I making any obvious mistake here?
|
The compiler is not able to recognize the type you are sending in the third case.
If you use
f("world", std::initializer_list<int>{1,2,3});
everything works.
This post has some detailed explanation and quotes the relevant part of the standard. It is for a slightly different case but the explanation still applies.
|
73,715,574
| 73,716,007
|
Data distribution fairness: is TCP and websocket a good choice?
|
I am learning about servers and data distribution. Much of what I have read from various sources (here is just one) talks about how market data is distributed over UDP to take advantage of multicasting. Indeed, in this video at this point about building a trading exchange, the presenter mentions how TCP is not the optimal choice to distribute data because it means having to "loop over" every client then send the data to each in turn, meaning that the "first in the list" of clients has a possibly unfair advantage.
I was very surprised then when I learned that I could connect to the Binance feed of market data using a websocket connection, which is TCP, using a command such as
websocat_linux64 wss://stream.binance.com:9443/ws/btcusdt@trade --protocol ws
Many other sources mention Websockets, so they certainly seem to be a common method of delivering market data, indeed this states
"Cryptocurrency trading applications often have real-time market data
streamed to trader front-ends via websockets"
I am confused. If Binance distributes over TCP, is "fairness" really a problem as the YouTube video seems to suggest?
So, overall, my main question is that if I want to distribute data (of any kind generally, but we can keep the market data theme if it helps) to multiple clients (possibly thousands) over the internet, should I use UDP or TCP, and is there any specific technique that could be employed to ensure "fairness" if that is relevant?
I've added the C++ tag as I would use C++, lots of high performance servers are written in C++, and I feel there's a good chance that someone will have done something similar and/or accessed the Binance feeds using C++.
|
The argument on fairness due to looping, in code, is ridiculous.
The whole field of trading where decisions need to be made quickly, where you need to use new information before someone else does is called: low-latency trading.
This tells you what's important: reducing the latency to a minimum. This is why UDP is used over TCP. TCP has flow control, re-sends data and buffers traffic to deliver it in order. This would make it terrible for low-latency trading.
WebSockets, in addition to being built on top of TCP are heavier and slower simply due to the extra amount of data (and needed processing to read/write it).
So even though the looping would be a tiny marginal latency cost, there's plenty of other reasons to pick UDP over TCP and even more over WebSockets.
So why does Binance does it? Their market is not institutional traders with hardware located at the exchanges. It's for traders that are willing to accept some latency. If you don't trade to the millisecond, then some extra latency is acceptable. It makes it much easier to integrate different piece of software together. It also makes fairness, in latency, not so important. If Alice is 0.253 seconds away and Bob is 0.416 seconds away, does it make any difference who I tell first (by a few microseconds)? Probably not.
|
73,715,880
| 73,716,439
|
How do I fix the second value of insertion sorting in tuple to work as well with the first value
|
Basically, I am trying to do Insertion Sorting on a tuple which is stored inside a vector, and I have a function to do it, when I only use the first value (get<0>(tupleVector[i])) it works, but when I try to add the second value (get<1>(tupleVector[i])) it doesn't, here's the whole function code.
void sort(vector<tuple<size_t, size_t>>& tupleVector, vector<int> idVector){
// insertionSort
for (int i = 1; i < tupleVector.size(); i++) {
int key = get<0>(tupleVector[i]);
int key2 = get<1>(tupleVector[i]);
int j = i;
while (j > 0 && get<0>(tupleVector[j - 1]) > key && get<1>(tupleVector[j - 1]) > key2) {
get<0>(tupleVector[j]) = get<0>(tupleVector[j - 1]);
get<1>(tupleVector[j]) = get<1>(tupleVector[j - 1]);
j--;
}
get<0>(tupleVector[j]) = key;
get<1>(tupleVector[j]) = key2;
}
cout << "Sorted" << endl;
}
EDIT:
I forgot to give examples of how it doesn't work, if I use values like ([500, 100], [700, 100], [100, 100], [500, 200]) it just doesn't sort anymore, but if I remove the (get<1>(tupleVector[i])) then it sorts based on the first value, but I need to sort for both, there's no compiler error or anything, it just doesn't sort
|
Assuming you intend a lexicographical comparison then your comparison operator fails to do so.
Assume you want to compare ordinary strings lexicographically:
Your operator would then accept xx as smaller to zz, as both characters in first string are smaller than the ones in second string – however this requirement fails to compare one of xz and zx as smaller than the other, as in neither string both characters are smaller as in the other one; thus neither of xz < zx nor zx < xz applies meaning both strings are considered equivalent with the consequence that when being sorted they are allowed to appear in arbitrary order.
Lexicographically one of these strings is already smaller if just the first of these characters is smaller, i.e. xy is smaller than both zx and zz, no matter if second character is smaller, equal or larger. On the other hand one string cannot be smaller if already first character is greater (obviously…) – i.e. to be smaller even if first character is not then first character needs to be equal. In this case the second character being smaller defines the entire string being smaller: xy is smaller than xz, but neither than xy nor than xx.
So as summary, you compare lexicographically two values by x[0] < y[0] || x[0] == y[0] && x[1] < y[1] – and you can apply this analogously to your tuples.
Generalised to arbitrary length then you can iterate over all characters of the strings x and y (testing x < y) or all members of the tuple respectively, returning true immediately if you encounter a value smaller in x than in y, false if you encounter a value greater and just continue iterating otherwise – until you encounter the end of one of the strings/tuples. If then y has further characters/members x still is smaller, otherwise not. Solely that iterating over tuples more complicated than with strings…
|
73,716,490
| 73,716,707
|
Translating Swift enums with associated values to C++
|
In Swift you can have an enum type with associated values.
enum Thing {
case num(Int)
case two(String, Double)
case other
}
var t: Thing = .num(123)
t = .two("a", 6.022)
t = .other
From what I'm reading, you can can do a similar thing in C++ by using std::variant. It has less syntactic sugar.
But the compiler complains if you give void to std::variant, so how would you represent the other case above? Maybe an ignored integer? Or is there better way to translate something like that enum type to C++?
std::variant<int, pair<string, double>, void> // error
std::variant<int, pair<string, double>, int> // okay
Compiler error from Clang:
... "variant can not have a void type as an alternative."
(If I wanted to refer to that variant as Thing I could use a typedef or wrap it in a struct.)
|
Because void cannot be instantiated, you'll need some stand-in type to represent void.
You could make your own, struct void_t{};, or you could use the std::monostate which is provided in C++17 and later.
|
73,716,618
| 73,720,092
|
flutter doctor ~ VS Code "Desktop Development in C++" error
|
The Flutter Doctor is showing this error:
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https:// visualstudio. microsoft .com /downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
I have already installed VS Code. How can I install the workload while not uninstalling and again installing VS Code?
|
VSCode and Visual Studio are two different software by the way :)
|
73,716,747
| 73,716,804
|
Universal reference deduction using the same_as concept
|
I'm trying to implement a push function for a blocking queue which accepts a universal reference as it's template parameter, but requires that the template argument be the same type as the queue's element type:
template <typename ValueType>
class shared_queue
{
public:
template <typename Arg>
requires std::same_as<Arg, ValueType>
void push(Arg&& arg);
private:
std::deque<ValueType> container_;
};
However, I'm not quite sure how is universal reference deduction supposed to work in this case, or if it works at all for that matter. The following code:
shared_queue<int> sq;
int x{ 5 };
sq.push(x); // won't compile
sq.push(5); // all good
does not compile. The compiler complains that:
I'm pretty sure I'm misunderstanding something but I don't know what.
|
You need to remove_reference from Arg for same_as to consider the int& to x and int the same type. You may also want to remove const in case you have const int x and pass that as a parameter. Removing both (+ volatile) can be done with std::remove_cvref_t:
template <typename Arg>
requires std::same_as<std::remove_cvref_t<Arg>, ValueType>
void push(Arg&& arg) {
container_.push_back(std::forward<Arg>(arg));
}
Another option would be to allow for any arguments that can be used to construct a ValueType:
template <class... Args>
requires std::constructible_from<ValueType, Args...>
void emplace(Args&&... args) {
container_.emplace(container_.end(), std::forward<Args>(args)...);
}
|
73,716,757
| 73,718,009
|
How to specify a fractional framerate with ffmpeg C/C++ when stitching together images?
|
I want to specify fractional frame rate's like 23.797 or 59.94 when creating my encoder. Here is how I do it currently:
AVStream* st;
...
st->time_base = (AVRational){1, STREAM_FRAME_RATE };
But looking at ffmpeg's source code at rational.h we can see that AVRational struct takes int's instead of float's. So my 23.797 turns into 23 thus encoding wrong. How can I specify fps with floating numbers?
|
As per the comment, you can make use of av_d2q from the libavutil library. By way of a basic example...
#include <iostream>
#include <limits>
extern "C" {
#include <libavutil/avutil.h>
}
int main ()
{
auto fps = 23.797;
auto r = av_d2q(1 / fps, std::numeric_limits<int>::max());
std::cout << "time base is " << r.num << "/" << r.den << " seconds\n";
}
The above gives me the following output...
time base is 1000/23797 seconds
|
73,717,088
| 73,717,248
|
Cin input of multiple lines not iterating correctly
|
I came from C so I'm trying to understand C++ input.
I want to read lines of input like so:
3
0 0 1 0
1 4 0 1
0 1 2 3
where 3 is the number of input lines I'm going to read next. My code is
#include<iostream>
#include<string>
int main() {
int n, k = 8;
std::cin >> n;
char lines[n][k];
for(int i = 0; i < n; i++)
std::cin.getline(lines[i], k);
}
I should be able to read the n lines (because of the zeroth iteration) but it only goes for n-1, so it finishes the reading at n-2. I don't understand why and how to deal with it and properly read input like this.
Also: how would I do if I wanted to read the same way for a std::string? Would I use std::string *lines[n];?
|
you are trying to create variadic length arrays, they are not a part of standard C++.
You should be using a combination of std::vector and std::string:
#include <iostream>
#include <string> //std::string, std::getline
#include <vector>
int main() {
int n;
std::cin >> n;
std::cin.ignore();
std::vector<std::string> lines(n);
for (auto& line : lines) {
std::getline(std::cin, line);
}
}
The std::ignore is needed because when using std::cin an additional \n is added after pressing enter. The next std::getline will be aborted when seeing the \n. So the ignore removes the next additional character from std::cin. read more on why does std::getline() skip input after a formatted extraction?
|
73,717,296
| 73,717,490
|
concept constraints don't apply
|
I've the following code
#include <cstdint>
#include <concepts>
template <class T>
concept has_id = requires(T) {
T::Id;
std::same_as<uint8_t[16], decltype(T::Id)>;
};
The has_id concepts ensure that a type has the member Id with type uint8_t[16].
However, when writing the following example it works even though the Id has type uint8_t[17] which is invalid.
#include <cstdint>
#include <iostream>
class Sample
{
public:
static constexpr uint8_t Id[17] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,10,11};
};
template<has_id T>
void print_id()
{
std::cout.setf(std::ios_base::hex);
std::cout << "{" << (int)T::Id[0];
for(auto i=1; i < sizeof(T::Id); ++i)
std::cout << ", " << (int)T::Id[i];
std::cout << "}";
}
int main()
{
print_id<Sample>();
return 0;
}
I've tried it on Visual C++ 2022 17.3 and Clang 14 and they give the same result, any idea why?
|
template <class T>
concept has_id = requires(T) {
T::Id;
std::same_as<uint8_t[16], decltype(T::Id)>;
};
Confirms that the expression T::Id compiles, and that the expression std::same_as<....> compiles. It doesn't check whether the latter is true or false.
You can just write
template <class T>
concept has_id = requires(T) {
T::Id;
requires std::same_as<uint8_t[16], decltype(T::Id)>;
};
to change the constraint from must compile to must be true.
Note GCC 12 helpfully emits the following warning with your original code:
<source>:7:2: warning: testing if a concept-id is a valid expression;
add 'requires' to check satisfaction [-Wmissing-requires]
|
73,717,892
| 73,718,075
|
Stop input loop when input is done | std::cin
|
I want to write a function that gets a set of integers and saves them to a vector.
To get the integers I'm using a while loop.
Enter the vector elements: 1 2 3 4 5
I want the loop to stop looking for input after the last element is inputted or until a non-numberis inputted, however I'm having trouble with it.
It is an assignment, so it needs to read input from std::cin.
This is my code:
#include <iostream>
#include <vector>
bool NumInVect(int num, std::vector<int> vect)
{
bool numInVect = false;
for (int i = 0; i < vect.size(); i++)
{
if (vect[i] == num)
{
numInVect = true;
}
}
return numInVect;
}
int main() {
std::vector<int> tempVect;
std::vector<int> finalVector;
std::cout << "Enter the vector elements: ";
int currVal;
while (std::cin >> currVal)
{
std::cout << "-\n";
if (!NumInVect(currVal, tempVect))
{
tempVect.push_back(currVal);
}
std::cout << currVal << std::endl;
}
//the code never reaches this loop, since its stuck in the while loop
std::cout << "knak\n";
for (int i = 0; i < tempVect.size(); i++)
{
std::cout << tempVect[i];
}
}
I've tried doing multiple things like using std::cin.eof()/.fail(), std::cin >> currVal in the while loop, a do-while loop, but I can't seem to figure out how to get this to work. Does anyone have any tips on what to look into or how to approach this?
|
If your intention is to get all the input from a given line, and add individual numbers to the vector, then you want to read a line of input into a string, then use an istringstream to process that line of input.
A simplified example:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::vector<int> tempVect;
std::string line;
std::getline( std::cin, line );
std::istringstream iss( line );
int curVal;
while ( iss >> curVal ) {
tempVect.push_back( curVal );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.