question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,976,442 | 70,978,196 | node not getting deleted if it's the head | This is my code, the important part at least. Whenever I run it and try to delete the head node, it won't work (the output will be a large negative number). It will work for all other nodes.
Is it something with my code, or you just can't replace the head?
node* displayList(node* head) {
node* curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
return NULL;
}
node* deleteVal(node* head, int val) {
node* cur, * prev;
if (head == NULL)
return head;
if (head->data == val) {
cur = head->next;
delete head;
head = cur;
return head;
}
cur = head;
prev = NULL;
while (cur->data != val && cur != NULL) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
return head;
}
prev->next = cur->next;
return head;
}
int main() {
node* head1 = initNode(), * head2=initNode(), * head3 = initNode();
int val;
head1 = input();
head2 = input();
head3 = input();
conca(head1, head2, head3);
cout << "the concatated list is: ";
displayList(head1);
cout << endl<<"enter the value you want to delete: ";
cin >> val;
deleteVal(head1, val);
cout << "the new list is: ";
displayList(head1);
return 0;
}
| deleteVal() is coded wrong.
When NOT removing the head node, your while loop will exhibit undefined behavior if val is not found in the list. In that situation, cur will become NULL after the last node is checked, and then the loop will try to access cur->data one more time, which is UB.
You need to swap the conditions of the while statement so that cur is checked for NULL before its data member is accessed:
while (cur != NULL && cur->data != val)
Also, if the while loop does find val in the remaining nodes, you are simply unlinking the found node from the list, but you are not actually delete'ing that node, thus you are leaking its memory.
Try this instead:
node* deleteVal(node* head, int val) {
node *cur, *prev;
if (head == NULL)
return head;
if (head->data == val) {
cur = head->next;
delete head;
return cur;
}
// we know the head node doesn't match, no need to
// test it again, so start the loop on the 2nd node...
cur = head->next;
prev = head;
while (cur != NULL && cur->data != val) {
prev = cur;
cur = cur->next;
}
if (cur != NULL) {
prev->next = cur->next;
delete cur;
}
return head;
}
Now, that being said, there are other issues with the code shown.
main() is ignoring the return value of deleteVal(). So, if the node pointed to by head1 were actually removed/deleted from the list, main() has no way of knowing that, and thus ends up passing a now-invalid node* pointer to displayList() afterwards. So, you need to assign the return value of deleteVal() back to head1 to reflect the new list state:
head1 = deleteVal(head1, val);
This is why it is not a good design choice to return a new list pointer by return value (unless you mark it as nodiscard in C++17 and later), as it is too easy to ignore. A better design choice is to pass in the caller's variable by reference/pointer instead, so the function can update the caller's variable directly when needed.
Also, main() is leaking the head1, head2, and head3 nodes when calling input(). You are creating new nodes with initNode(), and then reassigning the pointers to point at new nodes created by input(), thus you lose access to the original nodes from initNode().
In fact, even after calling deleteVal(), you are not freeing any remaining nodes before exiting the program. While it is true that the OS will reclaim all used memory when the program exits, it is best practice to explicitly free anything you allocate.
Also, your deleteVal() is needlessly complex, it can be greatly simplified.
Also, there is no good reason for displayList() to return anything at all.
With that said, try something more like this instead:
void displayList(node* head) {
node* curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
void deleteVal(node* &head, int val) {
node *cur = head, **prev = &head;
while (cur != NULL) {
if (cur->data == val) {
*prev = cur->next;
delete cur;
return;
}
prev = &(cur->next);
cur = cur->next;
}
}
void deleteList(node* &head) {
node *cur = head, *next;
head = NULL;
while (cur != NULL) {
next = cur->next;
delete cur;
cur = next;
}
}
int input() { // <-- return int, not node* !
...
return ...; // <-- just the user's entered value, not a node wrapping the value
}
int main() {
node* head1 = initNode(), *head2 = initNode(), *head3 = initNode();
head1->data = input();
head2->data = input();
head3->data = input();
conca(head1, head2, head3);
cout << "the concatenated list is: ";
displayList(head1);
cout << "enter the value you want to delete: ";
int val;
cin >> val;
deleteVal(head1, val);
cout << "the new list is: ";
displayList(head1);
deleteList(head1);
return 0;
}
|
70,976,880 | 70,977,109 | Multithreaded server don't switch between threads cpp | I'm trying to make a multithreaded server, but for some reason, the threads of my server aren't switching. Only the last thread that was create is running, the other threads aren't running.
This is the code of the main server:
void Server::serve(int port)
{
struct sockaddr_in sa = { 0 };
sa.sin_port = htons(port); // port that server will listen for
sa.sin_family = AF_INET; // must be AF_INET
sa.sin_addr.s_addr = INADDR_ANY; // when there are few ip's for the machine. We will use always "INADDR_ANY"
// Connects between the socket and the configuration (port and etc..)
if (bind(_serverSocket, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - bind");
std::cout << "binded" << std::endl;
// Start listening for incoming requests of clients
if (listen(_serverSocket, SOMAXCONN) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - listen");
std::cout << "Listening on port " << port << std::endl;
while (true)
{
SOCKET client_socket = accept(_serverSocket, NULL, NULL);
if (client_socket == INVALID_SOCKET)
throw std::exception(__FUNCTION__);
std::cout << "Accepting clients..." << std::endl;
std::cout << "Client accepted" << std::endl;
std::thread newClientThread(&Server::clientThread, this, std::ref(client_socket)); // Make thread of client
newClientThread.detach();
}
}
This is the thread of the client:
void Server::clientThread(SOCKET& clientSocket)
{
Helper ourHelper;
std::string msg = "";
int lengthOfMessage = 0;
this->_vectorOfSockets.push_back(clientSocket);
try
{
while (true)
{
std::cout << clientSocket;
/*
// Get message and save into queue
msg = ourHelper.getStringPartFromSocket(clientSocket, 1024);
msg = this->returnFullMsg(msg);
try
{
std::cout << clientSocket << " - d\n";
std::lock_guard<std::mutex> lck(mtx);
std::cout << clientSocket << " - d\n";
this->_messagesQueue.push(msg);
ourConditionVariable.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1)); // Wait the main thread to take care for the message
}
catch (std::exception e)
{
}*/
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
catch (const std::exception& e)
{
std::cout << "Client logged out\n";
// this->_users.erase(msg.substr(5, atoi(msg.substr(3, 5).c_str() + 5))); // Remove the user from the connected users list
closesocket(clientSocket);
}
}
And this the code of the main thread:
int main()
{
Server myServer;
std::string newMessage;
std::thread ourConnectorThread (connectorThread, std::ref(myServer));
ourConnectorThread.join();
/*std::cout << "Starting...\n";
while (true)
{
std::unique_lock<std::mutex> lckMessages(ourMutex);
ourConditionVariable.wait(lckMessages); // Wait for new message
newMessage = myServer.getQueue().front(); // Get the new message.
myServer.getQueue().pop(); // Remove the first item
takeCareForMessage(newMessage, myServer);
lckMessages.unlock();
}*/
return 0;
}
The code in the comments is irrelevant.
The result of this code is that the last thread is just printing the number of socket every second, and the other threads aren't printing anything..
What is the problem with my code?
| One main error in your code is that client_socket is passed by reference, and then it is modified by the server thread. A fix is to pass it by value.
Another error is that _vectorOfSockets.push_back is modified by multiple threads - a race condition. You need to use a mutex to fix that.
accept may fail when a client has disconnected. That's not an unrecoverable exceptional condition, no need to throw an exception, just retry accept to recover.
|
70,977,185 | 70,985,230 | How to change Qt's default selection behavior? | I am new to QGraphicsView. So for the practice purpose I was drawing some shapes like Rectangle, Ellipse, Polygon, Polyline, Text etc.
I observed here that, whenever we click on these drawn objects ( select them using mouse click )
dotted line rectangle appears around the object which indicates that, object is selected.
If I want to change that Qt's default behavior of selection, how to do that ?
I do not want dotted rectangle around circle, when it will
be clicked by mouse, but that dots should be around its circumference.
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QStyleOptionGraphicsItem>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
public:
virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QGraphicsScene>
#include<QGraphicsView>
#include<QGraphicsEllipseItem>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
QGraphicsScene *scene = new QGraphicsScene(this);
QGraphicsView *view = new QGraphicsView(this);
QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem();
ellipse = scene->addEllipse(2,2,80,80);
//ellipse->setFlag(QGraphicsItem::ItemIsSelectable);
scene->addItem(ellipse);
view->setScene(scene);
ui->verticalLayout->addWidget(view);
}
Widget::~Widget()
{
delete ui;
}
void Widget :: paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
auto copied_option = *option;
copied_option.state &= ~QStyle::State_Selected;
auto selected = option->state & QStyle::State_Selected;
paint(painter, &copied_option, widget);
if (selected) {
QPainterPath path;
path.addEllipse(2,2,80,80);
painter->save();
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine));
painter->drawPath(path);
painter->restore();
}
}
| As far as I'm aware there isn't any 'built in' facility to fo what you want. In the current code base you'll see...
void QGraphicsEllipseItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
Q_D(QGraphicsEllipseItem);
Q_UNUSED(widget);
painter->setPen(d->pen);
painter->setBrush(d->brush);
if ((d->spanAngle != 0) && (qAbs(d->spanAngle) % (360 * 16) == 0))
painter->drawEllipse(d->rect);
else
painter->drawPie(d->rect, d->startAngle, d->spanAngle);
if (option->state & QStyle::State_Selected)
qt_graphicsItem_highlightSelected(this, painter, option);
}
So the selection status indicator is drawn by qt_graphicsItem_highlightSelected which is called directly from the paint method. qt_graphicsItem_highlightSelected itself simply sets up a few basic parameters and ends by drawing the dashed rectangular border.
The obvious way to replace the default behaviour would be to subclass the QGraphicsItem class of interest and override the paint member (untested)...
#include <QApplication>
#include <QGraphicsEllipseItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
class ellipse: public QGraphicsEllipseItem {
public:
explicit ellipse (qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent = nullptr)
: QGraphicsEllipseItem(x, y, width, height, parent)
{}
virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
auto copied_option = *option;
copied_option.state &= ~QStyle::State_Selected;
auto selected = option->state & QStyle::State_Selected;
QGraphicsEllipseItem::paint(painter, &copied_option, widget);
if (selected) {
painter->save();
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine));
painter->drawPath(shape());
painter->restore();
}
}
};
int main (int argc, char **argv)
{
QApplication app(argc, argv);
QGraphicsView view;
QGraphicsScene scene;
view.setScene(&scene);
ellipse e(2, 2, 80, 80);
e.setFlag(QGraphicsItem::ItemIsSelectable);
scene.addItem(&e);
view.show();
return app.exec();
}
|
70,978,945 | 70,980,345 | How to use "*" to make letters using rows and columns | Here is the code of which I'm writing to create the letter "Z" for example just cant figure out how to connect the rows and columns. Also don't know why its re-writing the code as many times by the user input. ex: user inputs 5 rows, it produces the "letter" 5 times over. if anyone is able to help me resolve this issue, it would be greatly appreciated!
#include <iostream>
#include <string>
#include <cmath>
#include <random>
#include <time.h>
using namespace std; //when compiler sees a name it does not recognize, assume std;
//Program 2 by anon
int main() {
cout<<"This program draws characters. Select character, then height(s)\n";
const string PROMPT{"how many rows tall? (0 to quit): "};
bool running{true};
while (running) {
cout << "\nOption: a)Z b)H /)/ \\)\\ q)quit? (q to quit): ";
char option{}; cin>>option;
if (option=='a') { // box
while (true) {
cout << "([z]) " << PROMPT;
int rows=0;
cin >> rows;
if (rows<=0) break;
for (int col{1}; col<=rows; ++col) { // for each column
for (int row{1}; row<=rows; ++row)
cout << string(rows-row, ' ') << "*\n";
cout << "*";
}
cout<<endl;
}
}
if (option=='b') { // forward slash
while (true) {
cout << "(H) " << PROMPT;
int rows=0;
cin >> rows;
if (rows<=0) break;
for (int row{1}; row<=rows; ++row) {
cout << string(row-row, ' ') << "*\n";
for (int col{1}; col<=rows; ++col);
}
cout<<endl;
}
cout<<endl;
}
if (option=='/') { // forward slash
while (true) {
cout << "(/) " << PROMPT;
int rows=0;
cin >> rows;
if (rows<=0) break;
for (int row{1}; row<=rows; ++row) {
cout << string(rows-row, ' ') << "*\n";
}
cout<<endl;
}
}
else if (option=='\\') { // back slash
while (true) {
cout << "(\\) " << PROMPT;
int rows=0;
cin >> rows;
if (rows<=0) break;
for (int row{1}; row<=rows; ++row) { // backslash
cout << string(row-1, ' ') << "*\n";
}
cout<<endl;
}
}
else if (option=='q') {
break;
}
else {
cout<<" Invalid option, try again.\n";
}
}
cout<<"Goodbye\n";
return 0;
}
desired output:
a) Z b) H /)/ \\)\\ q) quit:a
How many rows tall? (0 to quit): 8
********
*
*
*
*
*
*
*
*
********
how many rows tall? (0 to quit): // loop reruns.
| In order to draw the Z you need to add the horizontal "*" line at the beginning and the end. In addition you have to remove the outer loop, to avoid the letter to be drawn multiple times. This loop needs to be seperate at the beginning and the end, to draw the horizontal line:
if (option == 'a')
{ // box
while (true)
{
cout << "([z]) " << PROMPT;
int rows = 0;
cin >> rows;
if (rows <= 0) break;
for (unsigned int i = 0; i < rows; ++i)
cout << "*";
cout << endl;
for (int row{ 1 }; row <= rows; ++row)
cout << string(rows - row, ' ') << "*\n";
for (unsigned int i = 0; i < rows; ++i)
cout << "*";
cout << endl;
}
}
|
70,979,101 | 70,984,013 | Why is my insertion sort algorithm altering numbers in the given array? (C++) | I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.
The code:
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
void insertionSort(T ary[10], int size)
{
// Printing unsorted array
cout << "Array before sorting: [";
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]" << endl;
// Beginning of sorting
int j, t;
for(int i = 1; i < size; i++)
{
for (int i = 0; i < size; i++)
{
j = i;
while(j > 0 && ary[j] < ary[j-1])
{
t = ary[j];
ary[j] = ary[j-1];
ary[j-1] = t;
j--;
}
}
}
// Printing sorted array
cout << "Array after sorting: [" ;
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]\n" << endl;
}
int main()
{
cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
int intAry[10] = {0};
for (int i = 0; i<= 9; i++)
{
intAry[i] = rand() % 100;
}
insertionSort(intAry, 10);
cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
double dAry[10] = {0};
for(int i = 0; i<=9; i++)
{
dAry[i] = (double)rand() / RAND_MAX * 100;
}
insertionSort(dAry, 10);
return 0;
}
The output:
You can see here that it changes the number in the array of doubles, like 14.1603 to 14.
Thank you for any help!
| The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type.
if you covert "double" the "int" data types, your problem will be solved.
Also you must change your array type to double.
|
70,979,238 | 70,979,531 | expected identifier before ')' token | When I tried to compile my game; and it says like
Networking/Sockets/Socket.hpp:18:81: error: expected identifier before ')' token
so if you want to see the source code I've in github here the link:
https://github.com/suky637/ServerPlusPlus
for peaple that do not want to go to github I will send you the Socket.hpp (this is the main error source) the code:
#ifndef Socket_hpp
#define Socket_hpp
#include <stdio.h>
#include <WinSock2.h>
#include <winsock.h>
#include <iostream>
namespace spp
{
class Socket {
private:
struct sockaddr_in address;
int sock;
int connection;
public:
// Constructor
Socket(int domain, int service, int protocol, int port, u_long interface_parameter);
// Virtual function to confirm to connect to the network
virtual int connect_to_network(int sock, struct sockaddr_in address) = 0;
// Function to test sockets and connection
void test_connection(int);
// Getter function
struct sockaddr_in get_address();
int get_sock();
int get_connection();
// Setter function
void set_connection(int connection_);
};
}
#endif
oh and this is the output:
// command : g++ Server.cpp -o ServerPlusPlus
In file included from Networking/Sockets/_ServerPlusPlus-sockets.hpp:6:0,
from Networking/ServerPlusPlus-Networking.hpp:6,
from ServerPlusPlus.hpp:6,
from Server.cpp:1:
Networking/Sockets/Socket.hpp:19:81: error: expected identifier before ')' token
Socket.cpp
#include "Socket.hpp"
// Default constructor
spp::Socket::Socket(int domain,
int service,
int protocol,
int port,u_long interface_parameter,
)
{
// Define address structure
address.sin_family = domain;
address.sin_port = port;
address.sin_addr.s_addr = htonl(interface_parameter);
// Establish socket
sock = socket(domain,service,protocol);
test_connection(sock);
// Establish Connection
connection = connect_to_network(sock, address);
test_connection(connect_to_network);
}
// Test Connection virtual function
void spp::Socket::test_connection(int item_to_test)
{
// Comfirm that the socket or connection has bin properly established
if (item_to_test < 0)
{
perror("Failed To Connect...");
exit(EXIT_FAILURE);
}
}
// Getter functions
struct sockaddr_in spp::Socket::get_address()
{
return address;
}
int spp::Socket::get_sock()
{
return sock;
}
int spp::Socket::get_connection()
{
return connection;
}
// Setter functions
void spp::Socket::set_connection(int connection_)
{
connection = connection_;
}
the main funtion where I compile is
#include "ServerPlusPlus.hpp"
using namespace std;
int main()
{
cout << "*--------- Starting ---------*" << endl;
cout << "* Binding Socket... ";
spp::BindingSocket bs = spp::BindingSocket(AF_INET,SOCK_STREAM,0,80,INADDR_ANY);
cout << "Complete\n* Listening Socket... ";
spp::ListeningSocket ls = spp::ListeningSocket(AF_INET, SOCK_STREAM, 0, 80, INADDR_ANY, 10);
cout << "Complete\n\n\n* Sucess!" << endl;
system("pause");
}
probably it is the file I copile and ServerPlusPlus.hpp is
#ifndef ServerPlusPlus
#define ServerPlusPlus
#include <stdio.h>
#include "Networking/ServerPlusPlus-Networking.hpp"
#endif
and ServerPlusPlus-Networking.hpp
#ifndef ServerPlusPlus_Networking_hpp
#define ServerPlusPlus_Networking_hpp
#include <stdio.h>
#include "Sockets/_ServerPlusPlus-sockets.hpp"
#endif
and ServerPlusPlus_Sockets_hpp
#ifndef ServerPlusPlus_Sockets_hpp
#define ServerPlusPlus_Sockets_hpp
#include <stdio.h>
#include "Socket.hpp"
#include "BindingSocket.hpp"
#include "ListeningSocket.hpp"
#include "ConnectingSocket.hpp"
#endif
| You seem to have missed that actual answer.
interface is used as a typedef in some windows headers
see What is the "interface" keyword in MSVC?
change the name to iface or something like that
|
70,979,477 | 70,979,835 | offsetof macro in c++ | #define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
I've been looking for this code for several minutes and I still don't understand what the const char volatile reference thing is, it's giving me a headache.
#define offsetof(s,m) ((size_t)&(((s*)0)->m))
This one is pretty clear, does make sense and it works well, why is the other one being used by MSVC compiler.
| If s::m is of a class type, it could overload operator&, so &(((s*)0)->m) would be the same as (((s*)0)->m).operator&(), which could do something unexpected.
To not use any custom operator&, it is cast to a const volatile char& first (which will have the same address). It needs to be both const and volatile because s::m might be const and/or volatile.
This is how std::addressof would have been implemented before C++11.
|
70,979,534 | 70,979,755 | #include errors detected based on information provided by the configurationProvider setting | I keep getting three errors when I try including a header file that looks like this:
#include <iostream>
#include <"maximum.h"> // *** Header file that is getting the three errors ***
These are the errors I am getting:
#include errors detected. based on information provided by the configurationProvider setting.
cannot open source file ""maximum.h""
'"maximum.h"' file not found
Here, is a link to a solution I tried out. That didn't solve the problem for me. Could anyone help me out? Thanks.
| You are trying to find file .../"maximum.h" which obviously in not existing.
Use either <maximum.h> which first will search your file inside compiler directories or "maximum.h" which first will search near your current file.
|
70,979,849 | 71,081,818 | Windows 10 detect keyboard layout change | I'm trying to implement a service that would monitor language/layout changes. I switch between English and Russian languages. So far I've found this question and tried to implement and install both sinks suggested there.
However, there are problems. ITfActiveLanguageProfileNotifySink::OnActivated is not triggered at all; ITfLanguageProfileNotifySink::OnLanguageChange is not triggered, too; ITfLanguageProfileNotifySink::OnLanguageChanged is triggered only when the main window of my program is in foreground, but it doesn't contain any information on the language. Is there any way to monitor input language change event globally?
| I found another way to detect such changes: to use SetWindowsHookEx with WH_SHELL. One of the available event is HSHELL_LANGUAGE which is exactly what I need and the test project seems to work just fine.
There's an article by Alexander Shestakov that describes a program very similar to what I'm trying to achieve and it also has a link to github project that I use as an example.
|
70,979,883 | 70,981,622 | Can I reset shared_ptr without deleting object so that weak_ptr loses a reference to it | I'd like to reset a shared_ptr without deleting its object and let weak_ptr of it loses a reference to it. However, shared_ptr doesn't have release() member function for reasons, so I can't directly do it. The easiest solution for this is just to call weak_ptr's reset() but the class which owns the shared_ptr and wants to release it doesn't know which class has weak_ptr of it. How can that be achieved in this case?
I understand why shared_ptr doesn't have release function but unique_ptr. In my case, only one instance owns a pointer, but shared_ptr can be owned by multiple instances and releasing doesn't make sense then. But if shared_ptr doesn't have that function, how can I cut connections to weak_ptr without deleting the object?
shared_ptr<int> A = make_shared<int>(100);
weak_ptr<int> B = A;
// I want something like this! but shared_ptr doesn't have release function..
int* releasedData = A.release();
A.reset(releasedData);
if (shared_ptr<int> C = B.lock)
{
// B already lost a reference, so it should never reach here
}
Background
A shared pointer of a class which stores a pointer of a large array is shared with other classes. The shared pointer is passed as a weak pointer to those, and the owner class of the shared pointer doesn't know about those classes. Multiple instances of the owner class are activated and deactivated at runtime. Because initializing cost of the instance is high, I use object pool pattern: I reuse those instances instead of creating/deleting every time I use it. The problem here is that when an instance of the owner class is deactivated, it should be tread as removed(although it still holds the data), and thus other classes which has a weak reference to the data should lose the reference. Resetting a shared pointer makes it possible, but I don't want to do it because the data is large.
I can make a manager class to keep track of which weak pointer refers to which shared pointer, but I wonder if this can be solved by something else.
| std::shared_ptr and std::weak_ptr are made to model the concept of RAII. When you use a std::shared_ptr, you already made the decision that it owns the resource, and that it should release the resource on destruction. The clunkiness you face is due to a rebellion against RAII: you want std::shared_ptr to own the resource but sometimes not really.
The solution is to reframe your object pool as an allocator. Suppose you have
struct obj_t { /* ... */ };
struct pool_t {
obj_t* acquire(); // get an object from the pool
void release(obj_t*); // return the object to the pool
// ...
};
Then your std::shared_ptr will look like
auto d = [&pool](auto p){ pool.release(p); };
std::shared_ptr<obj_t> obj{pool.acquire(), d};
Notably, the resource acquisition always gets paired with its destruction.
Under this model your problem doesn't exist
std::weak_ptr<obj_t> b = obj;
obj = nullptr; // or let obj get destroyed in any other way
if(auto c = b.lock())
// doesn't happen
|
70,979,884 | 70,980,047 | How can I interrupt boost message queue send & receive that are being blocked by signals? | I have a process which is using boost message queue. When it is being blocked in either send or receive due to queue size limit has been reached, if I send a signal, it seemed the function call remained blocking. I expected the call to cancel or raise an exception but it didn't behave that way. How can I interrupt the send or receive function call ?
#include <boost/interprocess/ipc/message_queue.hpp>
#include <signal.h>
#include <iostream>
#include <vector>
using namespace boost::interprocess;
static sig_atomic_t do_exit = 0;
void sig_handler(int sig)
{
printf("signal %d", sig);
do_exit = 1;
}
int main ()
{
signal(SIGINT, sig_handler);
try{
//Erase previous message queue
message_queue::remove("message_queue");
//Create a message_queue.
message_queue mq
(create_only //only create
,"message_queue" //name
,5 //max message number
,sizeof(int) //max message size
);
//Send 100 numbers
for(int i = 0; i < 100 && !do_exit; ++i){
mq.send(&i, sizeof(i), 0);
printf("%i\n", i);
}
printf("finished\n");
}
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}
catch(...) {
std:: cout << "Exception" << std::endl;
}
return 0;
}
| The way is to use the timed interfaces:
for (int i = 0; i < 100 && !do_exit; ++i) {
while (!do_exit) {
if (mq.timed_send(&i, sizeof(i), 0, now() + 10ms)) {
printf("%i\n", i);
break;
}
}
sleep_for(50ms);
}
E.g.:
#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <signal.h>
#include <vector>
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
namespace bip = boost::interprocess;
static sig_atomic_t do_exit = 0;
void sig_handler(int sig)
{
printf("signal %d\n", sig);
do_exit = 1;
}
int main()
{
auto now = std::chrono::steady_clock::now;
using std::this_thread::sleep_for;
signal(SIGINT, sig_handler);
try {
bip::message_queue::remove("message_queue");
bip::message_queue mq(bip::create_only, // only create
"message_queue", // name
5, // max message number
sizeof(int) // max message size
);
// Send 100 numbers
for (int i = 0; i < 100 && !do_exit; ++i) {
while (!do_exit) {
if (mq.timed_send(&i, sizeof(i), 0, now() + 10ms)) {
printf("%i\n", i);
break;
}
}
sleep_for(50ms);
}
printf("finished\n");
} catch (bip::interprocess_exception const& ex) {
std::cout << ex.what() << std::endl;
return 1;
} catch (...) {
std::cout << "Exception" << std::endl;
return 2;
}
}
Demo
|
70,980,038 | 70,980,492 | How to properly access packed struct members | What is the correct way to access packed struct's members?
struct __attribute__ ((packed)) MyData {
char ch;
int i;
}
void g(int *x); // do something with x
void foo(MyData m) {
g(&m.i);
}
void bar(MyData m) {
int x = m.i;
g(&x);
}
My IDE gives warning/suggestion for foo that I might be accessing misaligned int pointer, which is indeed the case here. My questions are
Between foo and bar, is one approach better than the other?
Is it incorrect to access misaligned pointer data but okay to use it to initialize a properly aligned type? (as in bar).
Should we copy packed struct individual members to properly aligned data structure and then use it? That would imply that for almost every packed data structure there is a non-packed data structure and packed structure remains confined to serialization layer.
|
Is it incorrect to access misaligned pointer data but okay to use it to initialize a properly aligned type? (as in bar).
As far as the C++ language is concerned, there is no such thing as a packed class nor such thing as improperly aligned object. Hence, an improperly aligned pointer would necessarily be invalid.
Whether your compiler that provides a language extension for packed classes also extends the language to allow access through misaligned pointers is up for your compiler vendor to document. The warning implies that latter extension might not be supported.
Between foo and bar, is one approach better than the other?
bar, as per the warning.
Should we copy packed struct individual members to properly aligned data structure and then use it? That would imply that for almost every packed data structure there is a non-packed data structure and packed structure remains confined to serialization layer.
That could be a convenient solution to confine the non-standard packed classes into the serialisation layer.
Note that this isn't the only problem with packed structs. Another problem is portability of serialised data between systems due to different byte orders and sizes of types.
A portable way to serialise data is to not use packed structs at all, but rather shift bytes individually using explicit offsets.
|
70,980,050 | 70,980,129 | Why this shift operation plus bitwise works only up to 31? | Why shift operation below works and end up equal?
Is there any name for this pattern?
I am trying to find out what was going on in the head of the person who wrote this code!
int i = 0x1;
i |= 0x1 << 1;
i |= 0x1 << 2;
i |= 0x1 << 3;
i |= 0x1 << 4;
i |= 0x1 << 5;
int j = 5;
if( ((0x1 << (j + 1)) - 1) == i)
{
// WHY?
}
I tried to check if this is true for all numbers but only works up to 31.
for (int i = 1; i <= 100; i++) {
int total_1 = 0x1;
for (int j = 1; j <= i; j++) {
total_1 |= 0x1 << j;
}
int total_2 = (0x1 << (i + 1)) - 1;
if (total_2 == total_1) {
} else {
cout << i << endl;
break;
}
}
UPDATE
Please explain the first part why they would end up equal?
|
Is there any name for this pattern?
0x1u << pos (or just 1u << pos) is a pattern for getting a number with only the bit in position pos is set. Using signed 0x1 is usually an anti-pattern.
i |= 1u << pos is a pattern for setting a bit in position pos of the integer i.
(1u << pos) - 1 is a pattern for creating a pattern of set bits only in positions lesser than pos.
Why shift operation below works and end up equal?
Perhaps it may help to look at intermediate results:
// least significant byte
int i = 0x1; // 0b0000'0001
i |= 0x1 << 1; // 0b0000'0011
i |= 0x1 << 2; // 0b0000'0111
i |= 0x1 << 3; // 0b0000'1111
i |= 0x1 << 4; // 0b0001'1111
i |= 0x1 << 5; // 0b0011'1111
int j = 5;
0x1 << (j + 1)
0x1 << 6 // 0b0100'0000
(0x1 << (j + 1)) - 1
0b0100'0000 - 1 // 0b0011'1111
only works up to 31
int is probably 32 bits wide on your system. If you left shift a 32 bit 0x1 by 31 or greater, then the behaviour of the program is undefined. If you were to use 0x1u, then you could shift by 31, but 32 and above would be UB.
|
70,980,151 | 70,980,233 | Outputting the objects out of a vector<object*> c++ | I have two classes:
class Transactions
{
public:
std::string type= "";
double value = 0;
void toString();
Transactions(std::string transT, double transVal) {
type = transT;
value = transVal;
}
};
class account
{
private:
double balance = 0;
std::vector <Transactions*> history{};
public:
double get_balance() { return balance; }
void set_balance(double value) { balance = value; }
void toString();
std::vector <Transactions*> get_history() { return history; }
void set_history(Transactions* His) { history.push_back(His); }
};
I am in the process implementing the toString() method by doing:
void account::toString() {
std::cout <<" | Current Account | Balance:" << std::to_string(get_balance()) << " | " << std::endl
<< "Transaction History: ";
for (Transactions* transaction : get_history())
{
std::cout << transaction->toString();
}
}
but I get an error on the "<<" in the for loop. I also tried using an ordinary for loop but came to the same conclusions of "C++ no operator matches these operands. operand types are: std::ostream << void". I am fairly new to c++ coming from a c#/python background where pointers aren't a thing so I can only assume that is where the issue is being raised? That or that the vector is empty, but when the program is running it will be filled so I'm not sure how to circumvent that issue
also this is where account and transaction objects are made:
account* curAccount = new account(std::stoi(parameters[2]), accID++);
accountStore.push_back(curAccount);
std::cout << "account open! The account number is " << accID;
Transactions* openingCTrans = new Transactions("Opening_Balance", std::stoi(parameters[2]));
curAccount->set_history(openingCTrans);
I know I didn't show the account or transaction constructors in the class but I don't think they're the issue
| this:
class Transactions
{
public:
std::string type= "";
double value = 0;
void toString();
Transactions(std::string transT, double transVal) {
type = transT;
value = transVal;
}
};
should be
class Transactions
{
public:
std::string type= "";
double value = 0;
std::string toString(); <<<<<============
Transactions(std::string transT, double transVal) {
type = transT;
value = transVal;
}
};
because you are doing
std::cout << transaction->toString();
ie, "please print the output of this function" so it has to return something printable
and use std::shared_ptr - you will thank me
|
70,980,500 | 70,981,303 | What does #ifndef _Python_CALL mean in a C++ code? | I am debugging a C++ code which contains something related to Python. In a function:
void normalize(string &text) {
...
#ifdef _Python_CALL
newContentStr = contentStr;
#endif
#ifndef _Python_CALL
...
...
#endif
return 0;
}
I am using GDB to keep track of the code logic, and I found that after it reaches the line:
newContentStr = contentStr;
It then directly jumps to the last line in the function:
return 0;
Why is the code between the following is skipped?
#ifndef _Python_CALL
...
...
#endif
Also note that the first is "#ifdef" and the 2nd is "#ifndef". Does that make the skip?
| Judging from the code fragment you've shown, _Python_CALL is a macro name, possibly defined somewhere via #define _Python_CALL (or maybe by some other means, such as using a command line argument to the C++ compiler during compilation).
Then, line #ifdef _Python_CALL means that everything that follows it until the line #endif will be compiled (and thus executed in the compiled program) if and only if the macro name _Python_CALL is defined (the #ifdef means "if defined"). Since you claim that the line newContentStr = contentStr; was executed, we can assume that the macro name _Python_CALL was indeed defined during compilation.
Now, the line #ifndef _Python_CALL means that everything that follows it until the line #endif will be compiled (and executed) if and only if the macro name _Python_CALL is NOT defined. (Note the n in #ifndef, it means "if not defined"). But, as we already know (from the conclusion we made in the previous paragraph), this is not the case, because _Python_CALL is indeed defined. Thus, this block will not be compiled/executed.
On Cppreference, you can read more about C++ preprocessor, especially about #define and #ifdef / #ifndef directives, to gain deeper understanding.
|
70,980,598 | 70,980,651 | How to intersect of more than 2 arrays? | I would like to intersect of more than 2 arrays. Here's incomplete version of my coding :
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
cout << "\n";
string rock[n];
for(int i=0;i<n;i++)
{
cin >> rock[i];
cout << "\n";
}
for(int i=0;i<n;i++)
sort(rock[i].begin(), rock[i].end());
}
So for example if I input
3
asasadfg
aassdw
dasaasf
I want it the output to be like this
ads
No duplication and intersect between more than 2 arrays. What's the best way to do it? Thanks
| Note: Variable length arrays are not standard in C++ and at best are a compiler-specific feature. In this case because length is not known at compile time, you'd be best off using a std::vector.
Now, we just need to know how to find the intersection of two strings, and do that across the entire vector. I'm sure there's a more elegant way, but hopefully you can trace what's happening below.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main() {
int n;
std::cin >> n;
std::cout << "\n";
std::vector<std::string> rocks;
for (int i = 0; i < n; ++i) {
std::string temp;
std::cin >> temp;
rocks.push_back(temp);
std::cout << "\n";
}
for (auto &s : rocks) {
std::sort(s.begin(), s.end());
}
std::string diff = rocks[0];
for (int i = 1; i < n; ++i) {
std::string temp_diff;
std::set_intersection(
diff.begin(), diff.end(),
rocks[i].begin(), rocks[i].end(),
std::back_inserter(temp_diff));
diff = temp_diff;
}
auto last = std::unique(diff.begin(), diff.end());
diff.erase(last, diff.end());
std::cout << diff << std::endl;
return 0;
}
|
70,980,688 | 70,980,711 | Undefined Reference to vtable After Adding Destructor | I looked at Undefined reference to vtable, but even after adding a destructor I am still met with a similar error:
main.cpp:(.text._ZN8isStringC2Ev[_ZN8isStringC5Ev]+0xf): undefined reference to `vtable for isString'
/usr/bin/ld: /tmp/ccVCX8sf.o: in function `isString::~isString()':
main.cpp:(.text._ZN8isStringD2Ev[_ZN8isStringD5Ev]+0xf): undefined reference to `vtable for isString'
/usr/bin/ld: /tmp/ccVCX8sf.o:(.data.rel.ro._ZTI8MyString[_ZTI8MyString]+0x10): undefined reference to `typeinfo for isString'
/usr/bin/ld: /tmp/ccVCX8sf.o:(.data.rel.ro._ZTI14CStringAdapter[_ZTI14CStringAdapter]+0x10): undefined reference to `typeinfo for isString'
collect2: error: ld returned 1 exit status
The following code is creating my own String class, but using an adapter for cstrings. They (MyString and CStringAdapter classes) inherit from a pure virtual class isString. I'm just trying to understand how to use adapters; I know creating my own string class is quite pointless.
I'm using C++ 17.
#include <iostream>
#include <cstring>
using namespace std;
class isString{
public:
virtual ~isString()=default;
virtual const char* getBuffer()const;
virtual size_t size()const;
};
class CStringAdapter: public isString{
protected:
string str;
public:
CStringAdapter(): str{""} {}
CStringAdapter(const char* newStr): str{newStr} {}
~CStringAdapter()=default;
const char* getBuffer() const override { return str.c_str(); }
size_t size() const override { return str.size(); }
};
class MyString: public isString{
protected:
string str;
public:
MyString():str{""} {}
MyString(const char* newCStr) { *this = newCStr; }
MyString(const MyString& newStr) { *this = newStr; }
~MyString()=default;
MyString& Assign(const isString& myStr, const isString& aStr){
memcpy(const_cast<char*>(myStr.getBuffer()), aStr.getBuffer(), aStr.size());
return *this;
}
MyString& operator=(const MyString& aString){ return Assign(*this, aString); }
MyString& operator=(const char* aCString){ return Assign(*this, CStringAdapter(aCString)); }
const char* getBuffer() const override { return str.c_str(); }
size_t size() const override { return str.size(); }
};
int main()
{
MyString str1{"Hello World"};
return 0;
}
| You didn't define the member functions isString::getBuffer and isString::size. You need to define them.
If you don't want the class to have definitions for these functions, you must mark them as pure virtual, making isString an abstract base class which cannot be instantiated directly:
virtual const char* getBuffer() const = 0;
virtual size_t size() const = 0;
|
70,980,743 | 70,990,005 | Passing arguments by template -- for efficiency? | There are two standard methods of passing arguments -- by value, and constant reference. Each has its trade-offs, with value being preferable in most cases that the data is very small. However, I just recently looked into templates more, and the way I understand it, they act more like a macro. Could you use templates to favor efficiency (disregarding bad code cleanliness for now)? For example, if I passed a std::vector through a template, would it allow access to the current scope to the function called?
| I think you are misunderstanding what templates are.
Template arguments are not another way of passing runtime arguments to a function. Templates are a way essentially of doing code generation if you want to use the exact same code multiple times but with different types and/or constants when you know all the types and constant values at compile time.
So to answer your question
For example, if I passed a std::vector through a template, would it
allow access to the current scope to the function called?
you can't pass an std::vector value to a template function beyond normal argument passing which may be parametrized on the type. As for allowing access to a vector in the current scope, you don't need templates for that anyway: pass a reference to the vector.
|
70,981,770 | 70,982,277 | How to declare an array without size known at compile-time? | I am trying to implement random_function(), which outputs the amount of random numbers within a range (user input), and count_function() to count for the value that the user wants to look up in the outputted random numbers. I made the random numbers to be saved in an array called randomlist[] so that it can be used to count for the value from the outputted random numbers. However, I cannot declare an array without its fixed size in the header file and define its size in the count_function.cpp. So I cannot use randomlist[] in the count_function() without redefining it (which is meaningless...).
Is there a way to declare array without defining its size, in the header file?
Here is the source code:
header file:
#pragma once
using namespace std;
class Rand
{
public:
// Rand();
int range,min,max;
char key;
void Random_function();
void Count_function();
// randomlist[]; something like this, which that is not possible in c++
};
This is randomfunction.cpp:
#include <iostream>
#include "random_function.hpp"
using namespace std;
void Rand::Random_function()
{
beginning:
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0 || cin.fail())
{
cout <<"Error! Please enter valid number and try again! "<<endl;
goto beginning;
}
else
{
reenter:
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
srand((unsigned)time(NULL));
if(max<min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
goto reenter;
}
else
{
int randomlist[range]; //I defined the size of the randomlist here but I want to use this outside of the random_fucntion() as well.
for(int i=0 ; i < range; i++)
{
randomlist[i] = min + (rand() % static_cast<int>(max - min + 1));
cout <<i+1<<". "<< randomlist[i] <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
cout <<"Do you want to continue? y/n"<<endl;
cin >> key;
if(key=='y')
{
Count_function();
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
else
{
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
}
}
void Rand::Count_function()
{
int n,count=0;
reenter2:
cout<<"Enter the value to count for: ";
cin>>n;
if(cin.fail())
{
cout<<"Please enter valid value to count for"<<endl;
goto reenter2;
}
else
{
for(int i=0 ; i <range; i++)
{
if(randomlist[i]==n)
{
count++;
}
}
}
cout <<"The number of '"<<n<<"'s in the given list is: "<< count <<endl;
}
main:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int main()
{
Rand call;
call.Random_function();
}
| When you want to use an array, but the size cannot be known at compile-time, the generally accepted approach in C++ is to use a std::vector.
|
70,981,797 | 70,981,895 | align the first digit for floats C++ | Needing to align floats by the first digit, not by the decimal. I'm not 100% on the intricacies of setw(), so not sure if the output I'm looking for is even possible. Tried searching for an answer for a couple hours now, and nothing seems to be exactly what I'm looking for. The field width isn't accurate here, they're just placements, but they still don't give desired output regardless.
Current code:
cout << setw(14) << collections1 << setw(18) << collections2 << setw(15) <<
collections3 << endl ;
Current output:
Collections1: Collections2: Collections3:
11.00 111.00 111.00
22.00 222.00 222.00
33.00 333.00 333.00
444.00 4444.00 444.00
555.00 5555.00 555.00
666.00 6666.00 666.00
Desired output:
Collections1: Collections2: Collections3:
11.00 111.00 111.00
22.00 222.00 222.00
33.00 333.00 333.00
444.00 4444.00 444.00
555.00 5555.00 555.00
666.00 6666.00 666.00
Have tried aligning right, left, but nothing seems to work.
Edit 1: Believe I may have found a good enough solution.
cout << left << "\t" setw(14) << collections1 << setw(18) << collections2 << setw(15) << collections3 << endl ;
Not certain if this is poor or not, but it gets the job done for the moment.
| You can try using left function for streaming your output as below:
std::cout.width(6); std::cout << std::left << n << '\n';
|
70,982,566 | 70,983,535 | c++ SFINAE - checking class has typedef, why is void_t required? | template <class T> struct has_iterator_typedefs
{
private:
struct __two {char dummy[2];};
template <class U> static __two test( ... );
template <class U> static char test( typename __void_t<typename U::iterator_category>::type* = NULL, //NOTE: require __void_t , == NULL ?
typename __void_t<typename U::difference_type>::type* = NULL,
typename __void_t<typename U::value_type>::type* = NULL,
typename __void_t<typename U::reference>::type* = NULL,
typename __void_t<typename U::pointer>::type* = NULL);
public:
static const bool value = sizeof(test<T>(0,0,0,0,0)) == 1;
};
This is part of libc++ code.
I understand how does void_t work, but I don't know why it is required in the context.
Why SFINAE does not work without void_t, like typename U::iterator_category*?
+) I think it does work w/o default argument = NULL, is it required?
| you cannot have pointer to reference
using X = int&;
using T = X*; // fail
so at least U::reference* is pretty likely to fail.
I don't think NULLs are really necessary since the caller do provide all the value.
note: I'm assuming __void_t is the same as std::void_t
|
70,982,750 | 70,983,510 | How do I use std::is_same_v in a using statement? | Consider the following code:
template<typename T>
using IsInt = std::is_same<T, int>::value;
template<class SrcType, class DstType>
constexpr DstType As(SrcType val) {
if constexpr (IsInt<SrcType>) return val;
}
This code compiles fine with C++17 but if I use std::is_same_v<...> instead of std::is_same<...>::value, then the GCC complains:
error: 'std::is_same_v<_Tp, _Up>' in namespace 'std' does not name a template type
I'm guessing the error is due to the fact that std::is_same_v is declared constexpr. How can I fix it (while maintaining the type alias)?
| Actually, the sample code doesn't compile.
#include <type_traits>
template<typename T>
using IsInt = std::is_same<T, int>::value;
The using declaration here is for type aliases. In C++17, it would have to be
template<typename T>
using IsInt = typename std::is_same<T, int>::value;
However, this is incorrect, because std::is_same<T, int>::value isn't a type, it's a value, and we want IsInt to be a value as well.
(In C++20, because only typenames are syntactically correct for the right hand side of this kind of using expression, the use of the typename keyword is no longer required here, but it's still creating a type alias, which is not what's intended.)
So what we actually want is the same sort of helper that C++17 uses for its _v convenience members:
template<typename T>
inline constexpr bool IsInt = std::is_same<T, int>::value;
The following also works:
template<typename T>
inline constexpr bool IsInt = std::is_same_v<T, int>;
inline assuming that this lives in a header and we want to use this same definition in multiple translation units, constexpr because it's known at compile time and this lets us use it in if constexpr or other purposes.
|
70,983,374 | 70,983,949 | Armadillo C++ fails to diagonalize bigger matrices | I'm working with the Armadillo linear algebra library for C++ to diagonalize large matrices up to 65k x 65k on a cluster operating with SLURM. For matrices larger than 30k x 30k i get the following error message:
Intel MKL ERROR: Parameter 9 was incorrect on entry to DSYTRD.
Intel MKL ERROR: Parameter 8 was incorrect on entry to DSTEDC.
Intel MKL ERROR: Parameter 12 was incorrect on entry to DORMTR.
I assume this could be caused by using int32 instead of int64, even though I enabled the arma macros ARMA_USE_64bit, ARMA_USE_BLASS_LONG_LONG etc so the internal code should operate on 64-bit integers. Here is my compilation line
g++ main.cpp IsingModel.cpp IsingModel_disorder.cpp IsingModel_sym.cpp tools.cpp\ user_interface.cpp -o Ising.o -pthread -I../LIBRARIES_CPP/armadillo-10.8.0/include/ \
-L${MKLROOT}/lib/intel64 -fopenmp -lmkl_intel_lp64 -lmkl_core -lmkl_intel_ilp64\
-lmkl_sequential -lpthread -lm -lmkl_gnu_thread -lstdc++fs -llapack -fcx-fortran-rules\
-fomit-frame-pointer -lblas -std=c++20 -std=c++17 -O3
For those, which know SLURM here are the modules I am using:
module load Armadillo/9.900.1-foss-2020a
module load imkl/2021.4.0
module load OpenBLAS/0.3.18-GCC-11.2.0
Thank you for any help in advance!
| Sorry, I do not have enough reputation to comment below so I have to make it an answer.
During my use of Armadillo, I find the current version of Armadillo and Intel MKL does not work properly and can be buggy (Ubuntu 20). Indeed there have been a lot of reports of that but it's hard for us to do anything for it is the Armadillo library that links to these libraries. Maybe this can be an issue for the developers.
I myself find OpenBlas a good alternative to Intel MKL as the support for Armadillo. It is really efficient. Moreover, if you have an Nvidia GPU, NVBlas works well with OpenBlas. (A cmake solution to use NVBlas together with OpenBlas is detailed in my answer.)
If you use cmake to install the Armadillo library, change the CmakeLists.txt file a bit to disable the detection of MKL.
CMake Solution
If MKL is installed and it is persistently giving problems during linking,
Support for MKL can be disabled by editing the CMakeLists.txt file,
deleting CMakeCache.txt and re-running the cmake based installation.
(Armadillo README)
In CMakeLists.txt, comment out the line (Line 327) containing:
INCLUDE(ARMA_FindMKL)
g++ Solution
With g++, delete the linking library for Intel MKL, use -lopenblas for OpenBlas.
g++ main.cpp IsingModel.cpp IsingModel_disorder.cpp IsingModel_sym.cpp tools.cpp \
user_interface.cpp -o Ising.o -pthread -I../LIBRARIES_CPP/armadillo-10.8.0/include/ \
-fopenmp -lpthread -lm -lstdc++fs -llapack -fcx-fortran-rules \
-fomit-frame-pointer -lblas -lopenblas -std=c++20 -O3
|
70,983,517 | 70,983,693 | How to make the compiler 'paste' specific code to an area | i was working on an educationary project to study C++ where specific labels include code to that specific topic being studied. However, at the end of each code block i want the compiler to ask if the user wants to exit or countine from beginning:
void main(void)
{
beginning:
printf("goto : \n 1) pointers \n 2) classes \n 3) \n 4) \n 5) \n ");
scanf_s("%d", &input);
switch (input)
{
case 1:
goto pointers;
case 2:
goto classes;
case 3:
case 4:
case 5:
default:
printf("wrong try again \n");
goto beginning;
}
pointers:
.....
classes:
......
}
the code to check what the user wants:
do {
printf("1 for exit and 2 for return menu \n");
scanf_s("%d", &reserved);
if (reserved == 2) { goto beginning; }
else if (reserved == 1) { exit; }
else { printf("wrong number, put a valid one you little..!"); }
} while (reserved != 1 && reserved != 2);
i tried to turn it to a function but the problem is labels are defined putside of main function so i want to just make the compiler put my function once it is called and not evaulate it from the beginning.
| The proper way to structure the code would be (pseudocode follows):
Do
PrintPrompt()
input = ReadInput()
switch (input)
case 1: DoFirstThing()
case 2: DoSecondThing()
...
default: PrintError()
While (UserWantsToContinue())
There's really no justification to using goto here (or almost anywhere, see answers to this question). For the canonical thesis go here.
|
70,983,595 | 70,988,240 | Deducing extent when passing std::array to function expecting std::span | I have a function expecting a std::span parameter. This function is called by passing an std::array.
This works fine if the std::span argument is declared with template parameter Extent set to std::dynamic_extent. But if the function is templated on Extent, the compiler is unable to deduce this value from std::array argument.
Any idea why the compiler is unable to deduce this template argument ?
See the snippet code below (Godbolt link).
Update after comments
When we explicitly create a std::span (without specifying template parameters) object when calling g(), everything works fine, the compiler is able to deduce the span type and Extent from the std::array. Following cppreference, the corresponding constructor (5) is not mark as explicit.
So why is the compiler unable to do the same deduction ?
void f(const std::span<std::byte> buffer)
{
std::cout << "f() => Extent = 0x" << std::hex << buffer.extent
<< " Size = " << std::dec << buffer.size() << std::endl;
}
template<std::size_t Extent>
void g(const std::span<std::byte, Extent> buffer)
{
std::cout << "g() => Extent = 0x" << std::hex << buffer.extent
<< " Size = " << std::dec << buffer.size() << std::endl;
}
std::array<std::byte, 4> buffer = {};
f(buffer);
g(std::span{buffer}); // <= Works fine
g(buffer); // <= Compiler error!
With this result from compiler:
<source>:23:6: error: no matching function for call to 'g(std::array<std::byte, 4>&)'
23 | g(buffer);
| ~^~~~~~~~
<source>:13:6: note: candidate: 'template<long unsigned int Extent> void g(std::span<std::byte, _Count>)'
13 | void g(const std::span<std::byte, Extent> buffer)
| ^
<source>:13:6: note: template argument deduction/substitution failed:
<source>:23:6: note: 'std::array<std::byte, 4>' is not derived from 'std::span<std::byte, _Count>'
23 | g(buffer);
| ~^~~~~~~~
|
So why is the compiler unable to do the same deduction ?
Because class template argument deduction is a different process from function template argument deduction.
In the case of g, the compiler has no idea what the constructors of span are because... it's not a class yet. It's a template. And since template specialization is a thing, it is entirely possible that the deduced Extent value radically changes what span conversion constructors are available.
Function template argument deduction is about matching the type of each function argument against the type and template parameters of the corresponding parameter type. Since you're using a specific template type whose arguments have to be deduced from those of the incoming parameter, this requires that the parameter be a specialization of that template.
Class template argument deduction bypasses all of this because it is solely based on the constructor declarations in the primary template (and any template deduction guides). It can use the constructors in that template to deduce the template parameters.
But function template argument deduction doesn't work that way.
|
70,984,103 | 71,008,828 | Learning Curve in Q-learning | My question is I wrote the Q-learning algorithm in c++ with epsilon greedy policy now I have to plot the learning curve for the Q-values. What exactly I should have to plot because I have an 11x5 Q matrix, so should I take one Q value and plot its learning or should I have to take the whole matrix for a learning curve, could you guide me with it.
Thank you
| Learning curves in RL are typically plots of returns over time, not Q-losses or anything like this. So you should run your environment, compute the total reward (aka return) and plot it at a corresponding time.
|
70,984,611 | 70,985,040 | C++ program stuck in an infinite loop | Please note that I am a complete beginner at C++. I'm trying to write a simple program for an ATM and I have to account for all errors. User may use only integers for input so I need to check if input value is indeed an integer, and my program (this one is shortened) works for the most part.
The problem arises when I try to input a string value instead of an integer while choosing an operation. It works with invalid value integers, but with strings it creates an infinite loop until it eventually stops (unless I add system("cls"), then it doesn't even stop), when it should output the same result as it does for invalid integers:
Invalid choice of operation.
Please select an operation:
1 - Balance inquiry
7 - Return card
Enter your choice and press return:
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool isNumber(string s) //function to determine if input value is int
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
else if (rtrn == "2" and isNumber(rtrn)) { return true; }
else {cout << "Invalid choice." << endl; ReturnCard(); };
return 0;
}
int menu() //function for operation choice and execution
{
int choice;
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == 1 and isNumber(to_string(choice))) { cout << "Your balance is $" << balance; "\n\n"; }
else if (choice == 7 and isNumber(to_string(choice))) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; menu(); }
} while (ReturnCard()==false);
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I've tried every possible solution I know, but nothing seems to work.
***There is a different bug, which is that when I get to the "Do you wish to continue?" part and input any invalid value and follow it up with 2 (which is supposed to end the program) after it asks again, it outputs the result for 1 (continue running - menu etc.). I have already emailed my teacher about this and this is not my main question, but I would appreciate any help.
Thank you!
| There are a few things mixed up in your code. Always try to compile your code with maximum warnings turned on, e.g., for GCC add at least the -Wall flag.
Then your compiler would warn you of some of the mistakes you made.
First, it seems like you are confusing string choice and int choice. Two different variables in different scopes. The string one is unused and completely redundant. You can delete it and nothing will change.
In menu, you say cin >> choice;, where choice is of type int. The stream operator >> works like this: It will try to read as many characters as it can, such that the characters match the requested type. So this will only read ints.
Then you convert your valid int into a string and call isNumber() - which will alway return true.
So if you wish to read any line of text and handle it, you can use getline():
string inp;
std::getline(std::cin, inp);
if (!isNumber(inp)) {
std::cout << "ERROR\n";
return 1;
}
int choice = std::stoi(inp); // May throw an exception if invalid range
See stoi
Your isNumber() implementation could look like this:
#include <algorithm>
bool is_number(const string &inp) {
return std::all_of(inp.cbegin(), inp.cend(),
[](unsigned char c){ return std::isdigit(c); });
}
If you are into that functional style, like I am ;)
EDIT:
Btw., another bug which the compiler warns about: cout << "Your balance is $" << balance; "\n\n"; - the newlines are separated by ;, so it's a new statement and this does nothing. You probably wanted the << operator instead.
Recursive call bug:
In { cout << "Invalid choice of operation."; menu(); } and same for ReturnCard(), the function calls itself (recursion).
This is not at all what you want! This will start the function over, but once that call has ended, you continue where that call happened.
What you want in menu() is to start the loop over. You can do that with the continue keyword.
You want the same for ReturnCard(). But you need a loop there.
And now, that I read that code, you don't even need to convert the input to an integer. All you do is compare it. So you can simply do:
string inp;
std::getline(std::cin, inp);
if (inp == "1" || inp == "2") {
// good
} else {
// Invalid
}
Unless that is part of your task.
|
70,984,963 | 70,985,223 | Selecting container type at compile time | I want to select one of the standard containers with one template parameter at compile time. Something like
template<typename T>
void foo()
{
using Container = std::conditional_t< std::is_same_v<T, int>,
std::vector, // T is int
std::set>; // any other T
Container<T> bar;
}
How to do this properly?
| The simplest way seems to be
using Container = std::conditional_t< std::is_same_v<T, int>,
std::vector<T>, // T is int
std::set<T>>;
Container bar;
std::conditional_t allows you to select a type. There is no standard conditional template that would allow to select a template. You can write one if you want but this won't be convenient to use.
template <bool t, template <typename...> typename X, template <typename...> typename Y>
struct conditional_template;
template <template <typename...> typename X, template <typename...> typename Y>
struct conditional_template<true, X, Y>
{
template <typename... ts> using type = X<ts...>;
};
template <template <typename...> typename X, template <typename...> typename Y>
struct conditional_template<false, X, Y>
{
template <typename... ts> using type = Y<ts...>;
};
template <typename... ts>
using Container = conditional_template<true, std::list, std::vector>::type<ts...>;
Container<int> x;
It doesn't seem possible to define an analogue of std::conditional_t convenience alias.
|
70,985,020 | 70,988,136 | Should I just believe that std::thread is implemented not by creating user threads only? | I learned that all of user threads mapped with a kernel thread be blocked if one of the threads calls some system call likes I/O System Call.
If std::thread is implemented by creating only a user thread in some environment, then a thread for I/O in some programs can block a thread for Rendering.
So I think distinguishing user / kernel is important but c++ standard does not.
Then how I assure that some situations like above will not occur in particular environment(like Windows10 )?
|
I learned that all of user threads mapped with a kernel thread be blocked if one of the threads calls some system call likes I/O System Call.
Yes, however it's rare for anything to use kernel's system calls directly. Typically they use a user-space library. For a normally blocking "system" call (e.g. the read() function in a standard C library) the library can emulate it using asynchronous functions (e.g. the aio_read() function in a standard C library) and a user-space thread switches.
So I think distinguishing user / kernel is important but c++ standard does not.
It is important, but for a different reason.
The first problem with user-space threading is that the kernel isn't aware of thread priorities. If you imagine a computer running 2 completely separate applications (with the user using "alt+tab" to switch between them), where each application has a high priority thread (for user interface), and few medium priority threads (for general work) plus a few low priority threads (for doing things like prefetching and pre-calculating stuff in the background); you can end up with a situation where kernel gives CPU time to one application (that uses the CPU time for low priority threads) because it doesn't know the other application needs CPU time for its higher priority threads.
In other words, for a multi-process environment, user-space threading has a high risk of wasting CPU time doing irrelevant work (in one process) while important work (in another process) waits.
The second problem with user-space threading is that (for modern systems) good scheduling decisions take into account differences between different CPUs ("big.Little", hyper-threading, which caches are shared by which CPUs, ..) and power management (e.g. for low priority threads it's reasonable to reduce CPU clock speed to increase battery life and/or reduce CPU temperatures so they can run faster for longer when higher priority work needs to be done later); and user-space has none of the information needed (and none of the ability to change CPU speeds, etc) and can not make good scheduling decisions.
Note that these problems could be "fixed" by having a huge amount of communication between user-space and kernel (the user-space threading informing kernel of thread priorities of waiting threads and currently running thread, kernel informing user-space of CPU differences and power management, etc); but the whole point of user-space thread switching is to avoid the cost of kernel system calls, so this communication between user-space and kernel would make user-space thread switching pointless.
Then how I assure that some situations like above will not occur in particular environment(like Windows10 )?
You can't. It's not your decision.
When you choose to use high level abstractions (std::thread in C++ rather than using the kernel directly from assembly language) you are deliberately delegating low level decisions to something else (the compiler and its run-time environment). The advantages (you no longer have to care about these decisions) are the disadvantages (you are no longer able to make these decisions).
|
70,985,072 | 70,985,157 | Run time choice of method using std::bind. Problem with access to variable | I need to choice the particular method of the class at the run time. To do it I use std::bind. Below is an example demonstrating what I do:
#include<iostream>
#include<functional>
class bc {
public:
bc(int, double);
std::function<double(double)> f; //pointer to function which will be binded with f1 or f2
void setVal(double v) {val = v;} //method allowing to change val
double val; //some variable used by f1 and f2
double f1(double v) {return 2*v*val;}
double f2(double v) {return 3*v*val;}
};
bc::bc(int fid, double v) //depends on fid the f1 or f2 is chosen for binding
{
using namespace std::placeholders;
this->val = v;
if(fid == 1)
f = std::bind(&bc::f1, *this, _1);
else
f = std::bind(&bc::f2, *this, _1);
}
So depends on the value of fid given to the constructor the necessary implementation (f1 or f2) is chosen. Then in the main:
int main()
{
bc my(1, 2.0);
std::cout << my.f(1) << std::endl; //1
my.setVal(5.0);
std::cout << my.f(1) << std::endl; //2
return 0;
}
The first output from string //1 is as expected: 4 .
But the second output (//2) is also 4, while it should be 10, because the value of val should be changed to 5 by my.setVal(5.0).
I expect that something like a copy of the class was made at the stage of binding, and the change of the val by my.setVal(5.0) have no effect on this "copy".
How can I solve this problem? Or may be there is a better way to make run time choice between several implementations of some function.
| *this causes a copy of the current object to be bound, use this or std::ref(*this) instead.
|
70,985,164 | 70,985,217 | How can I choose the algorithm of a code only once at the beginning in C++? | There are two different algorithms being used throughout the code. Which one is chosen is determined at runtime by a parameter (e.g. true or false). I do not want to use if-statements each time the algorithm comes up.
So instead of writing the following every time
if (parameter==true)
algorithmOne();
else
algorithmTwo();
I want to set the algorithm at the beginning, like
if (parameter==true)
algorithm()=algorithmOne();
else
algorithm()=algorithmTwo();
and only use 'algorithm()' from this point forward.
How can I choose the algorithm at the beginning depending on a parameter after the code is already compiled?
Edit:
How do you do that within the constructor of a class (since a pointer-to-member function is no regular pointer)? As both algorithms rely on member variables and functions of this class, it is inconvenient to derive a new class.
Solution:
This could be solved with a virtual function and derived classes.
class Base
{
public:
Base();
virtual void algorithm() = 0;
~Base();
protected:
double d;
int i;
...
}
class DerivedOne : public Base
{
public:
DerivedOne() : Noise() {};
void algorithm() override;
~DerivedOne();
};
Base *b;
if (parameter==true)
{
b = new DerivedOne();
}
else
{
b = new DerivedTwo();
}
Then the function can be called with:
b->algorithm();
And deleted with:
delete b;
This may not be the best way but it seems to work for me. See answers and comments.
| You're almost there:
auto algorithm = parameter ? algorithmOne : algorithmTwo.
No (), you're not trying to call any function here.
|
70,985,312 | 70,985,613 | unique_ptr to a derived class as an argument to a function that takes a unique_ptr to a base class and take owenership | I have already read various comments similar to this question here on stack overflow without finding exactly the solution to my problem.
I have a Base class and Derived class an also a class that contain and also keep the ownership of this objects.
class Base { };
class Derived: public Base { };
class MyClass
{
std::vector<std::unique_ptr<Base>> myVector;
public:
MyClass() {}
void addElement (std::unique_ptr<Base> &base)
{
myVector.push_back(std::move(base));
}
};
My code fails to compile when I try to add a derived object in my class.
MyClass myClass;
auto b = std::make_unique<Base>();
myClass.addElement(b);
auto d = std::make_unique<Derived>();
myClass.addElement (d); // <-- ERROR: error: cannot convert ‘std::unique_ptr >’ to ‘std::unique_ptr&’
| The function must accept the unique_ptr by value:
void addElement (std::unique_ptr<Base> base)
{
myVector.push_back(std::move(base));
}
and then call the member function like this:
MyClass myClass;
auto b = std::make_unique<Base>();
myClass.addElement(std::move(b));
auto d = std::make_unique<Derived>();
myClass.addElement(std::move(d));
or even better avoid the variables because you cannot use them anyway after the function call:
MyClass myClass;
myClass.addElement(std::make_unique<Base>());
myClass.addElement(std::make_unique<Derived>());
|
70,986,423 | 70,986,707 | Segfault 11 binary tree paths | I have to make a function in C++ that finds the external path and the internal path of a binary tree and prints them. I'm having trouble with a segfault 11 once the function for finding the paths is called, but I can't figure out where the segfault is. I don't have a very clear understanding of what a segfault is, all I know is that the program is trying to access a chunk of memory that's not available. Thank you for your time.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Nodo
{
friend class Albero;
Nodo (int);
int valore;
Nodo *prev;
Nodo *next;
};
Nodo :: Nodo (int num)
{
valore = num;
prev = 0;
next = 0;
};
class Albero
{
public:
Albero ();
void inserisci (int); // insertion of a value;
void trovaCammino (int&, int&, int); // find path
void stampa (); //print
private:
Nodo *radice; // first item
void stampaRicorsivo (Nodo*);
void inserisciRicorsivo (Nodo *&, int);
void trovaCamminoRic (Nodo*&, int&, int&, int);
};
Albero :: Albero ()
{
radice = 0;
};
void Albero :: inserisci (int nuovo)
{
inserisciRicorsivo (radice, nuovo);
};
void Albero :: inserisciRicorsivo (Nodo*& radice, int nuovo)
{
if (radice == 0)
{
radice = new Nodo (nuovo);
} else if (nuovo < radice->valore)
{
inserisciRicorsivo(radice->prev, nuovo);
} else if (nuovo > radice->valore)
{
inserisciRicorsivo(radice->next, nuovo);
}
};
void Albero :: trovaCammino (int& contInt, int& contEst, int curr)
{
trovaCamminoRic(radice, contInt, contEst, curr);
};
void Albero :: trovaCamminoRic (Nodo*& radice, int& contInt, int& contEst, int curr)
{
if (radice->prev != 0) // if previous element is present
{
curr++; // increase current level
contInt++; // increase internal path counter
trovaCamminoRic(radice->prev, contInt, contEst, curr); // call it again on the previous element
} else if (radice->next != 0) // if next element is present...
{
curr++;
contInt++;
trovaCamminoRic(radice->prev, contInt, contEst, curr);
} else // if both are untrue, which means that the node is a leaf
{
contEst = (contEst+curr); // increase the external counter
contInt--; // decrease the internal counter by one;
}
};
void Albero :: stampa ()
{
stampaRicorsivo (radice);
};
void Albero :: stampaRicorsivo (Nodo* radice)
{
if (radice != 0)
{
stampaRicorsivo (radice->prev);
cout << radice->valore << endl;
stampaRicorsivo(radice->next);
}
;}
int main ()
{
int curr;
curr = 0;
Albero rami;
int dim;
cout << "Inserire la grandezza dell'albero che si vuole generare"; cin >> dim;
for (int i = 0; i < dim; i++)
{
int num;
cout << "Inserire il valore n° " << (i+1) << ": "; cin >> num;
rami.inserisci(num);
}
int contInt = 0;
int contEst = 0;
rami.stampa();
rami.trovaCammino(contInt, contEst, curr);
cout << "Il cammino interno dell'albero è: " << contInt << endl << "Il cammino esterno dell'albero è: " << contEst << endl;
}
| In trovaCamminoRic, radice can be NULL, but you don't check that, and dereferencing NULL like in radice->prev is undefined behaviour, which usually crashes your program with a segfault.
Simply add this check and it should work:
void Albero::trovaCamminoRic(Nodo*& radice, int& contInt, int& contEst, int curr)
{
if (radice == NULL)
return;
...
You should invest an hour or so in learning the basics of your debugger. With a debugger you find this kind of problems in minutes.
Disclaimer: I'm not sure what the program is supposed to do, and there may be other problems.
|
70,986,572 | 70,986,653 | Problem with Output with Static keyword in C/C++ | Output wrt my reasoning should be 0456 but the compiler shows 0415 and I debugged it a little and realised it is targeting both "i" differently.
I'll be grateful if someone can explain the reasoning behind it.
Thank You :)
#include <iostream>
using namespace std;
int main()
{
static int i;
for(int j = 0; j<2; j++)
{
cout << i++;
static int i = 4;
cout << i++;
}
return 0;
}
| You should expect the output to be as follow:
Loop pass #1: print 0 (top-level block scope i) followed by 4 (for loop block scope i).
Loop pass #2: print 1 (top-level block scope i) followed by 5 (for loop block scope i).
Thus 0415.
static int i; // declares i at block-scope; denote as (i1)
for(int j = 0; j<2; j++)
{ // enter nested block scope
cout << i++; // at this point, `i` local to current
// block scope is yet to be declared.
// thus, this refers to (i1)
static int i = 4; // this declares a local `i` (denote as (i2))
// which shadows (i1) henceforth
cout << i++; // this refers to (i2)
}
Even if the lifetime of the local static variable i starts at first loop pass (the first time control passes its declaration) such that its declaration is skipped on the second pass, this does not affect the scope of it.
Block scope
The potential scope of a name declared in a block (compound statement) begins at the point of declaration and ends at the end of the block [...]
|
70,987,185 | 70,987,823 | How long will QueryPerformanceCounter() return the correct value for 32 bit machine (without overflows)? | Will QueryPerformanceCounter return the correct value for 32-bit computer that is up for more than month or even a couple of months or years?
Thanks
| Microsoft guarantees that QueryPerformanceCounter will not roll over sooner than 100 years from boot: quoting https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps#general-faq-about-qpc-and-tsc
How often does QPC roll over?
Not less than 100 years from the most recent system boot, and potentially longer based on the underlying hardware timer used. For most applications, rollover isn't a concern.
You cannot deduce this just from the fact that QueryPerformanceCounter produces a 64-bit value. The hardware clock used to implement QPC could have a much smaller range, and Windows could just be zero-extending that clock to 64 bits. This is particularly plausible on the older 32-bit systems you were asking about. Only explicit documentation of the rollover interval should be relied on.
|
70,987,238 | 70,987,971 | Is there a C++ template way to loop on different enums? | In this topic I would like to know if a C++ way is possible to loop on different given enums ? The following source code is my proposition but doesn't compile.
enum class Fruit : int
{
UNKNOWN = 0,
APPLE = 1
};
enum class Vegetable : int
{
UNKNOWN = 0,
CARROT = 1
};
static const std::map<std::string, Fruit> FRUITS_MAP
{
{"unknown", Fruit::UNKNOWN},
{"apple", Fruit::APPLE}
};
static const std::map<std::string, Vegetable> VEGETABLES_MAP
{
{"unknown", Vegetable::UNKNOWN},
{"carrot", Vegetable::CARROT}
};
template<typename T>
T myFunction(const std::string &iName)
{
T result{T(0)};
if (std::is_same<T, Fruit>::value)
{
const auto &found = FRUITS_MAP.find(iName);
if (FRUITS_MAP.end() != found)
{
result = found->second;
}
}
else if (std::is_same<T, Vegetable>::value)
{
const auto &found = VEGETABLES_MAP.find(iName);
if (VEGETABLES_MAP.end() != found)
{
result = found->second;
}
}
return result;
}
I can't write methods with only changing return type because I get error: ambiguating
| You can fix your code simply by adding constexpr in the lines:
if constexpr (std::is_same<T, Fruit>::value)
...
else if constexpr (std::is_same<T, Vegetable>::value)
And use it like:
std::cout << static_cast<int>(myFunction<Fruit>("apple")) << std::endl;
std::cout << static_cast<int>(myFunction<Vegetable>("carrot")) << std::endl;
If you sit on a decade outdated compiler ( why? ) you can simply use specialized templates:
template<typename T> T myFunction(const std::string &iName);
template<>
Fruit myFunction<Fruit>(const std::string &iName)
{
Fruit result{Fruit(0)};
const auto &found = FRUITS_MAP.find(iName);
if (FRUITS_MAP.end() != found)
{
result = found->second;
}
return result;
}
template<>
Vegetable myFunction<Vegetable>(const std::string &iName)
{
Vegetable result{Vegetable(0)};
const auto &found = VEGETABLES_MAP.find(iName);
if (VEGETABLES_MAP.end() != found)
{
result = found->second;
}
return result;
}
But here we can ask why we need templates as simply overloads with different names have the same effect. It depends on the real use case. If you have type lists you walk over with some MTP stuff, this may help, if it is handcrafted code which will call the given functions, the template stuff makes no sense.
|
70,987,449 | 70,987,526 | How can I skip the goto statement if the user enters marks less than 100 | Note: I am a beginner.
I have used goto statement to execute if the user enters marks more than 200 but if the user has entered marks less than 100 then the rest of the code should run.
How can I do that ?
Here is the piece of code
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
float sum, perc;
int total = 500;
INPUT:
cout << "Enter marks for English" << endl;
cin >> a;
cout << "Enter marks for Urdu" << endl;
cin >> b;
cout << "Enter marks for Maths" << endl;
cin >> c;
cout << "Enter marks for Computer" << endl;
cin >> d;
cout << "Enter marks for Islamiat" << endl;
cin >> e;
if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
cout << "You must enter all subject marks below 100" << endl;
}
goto INPUT;
sum = a + b + c + d + e;
perc = (sum / total) * 100;
if (a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100) {
cout << "Percentage is = " << perc << "%" << endl;
}
else {
cout << "You must enter marks below 100" << endl;
return 0;
}
if (perc >= 50) {
cout << "Congratulations you are Passed" << endl;
}
else {
cout << "You are fail" << endl;
}
return 0;
}
| Just use do-while loop as for example
bool success = false;
do
{
cout << "Enter marks for English" << endl;
cin >> a;
cout << "Enter marks for Urdu" << endl;
cin >> b;
cout << "Enter marks for Maths" << endl;
cin >> c;
cout << "Enter marks for Computer" << endl;
cin >> d;
cout << "Enter marks for Islamiat" << endl;
cin >> e;
success = not ( a > 100 || b > 100 || c > 100 || d > 100 || e > 100 );
if ( not success )
{
cout << "You must enter all subject marks below 100" << endl;
}
} while ( not success );
|
70,987,585 | 70,987,722 | How to initialize shared_ptr not knowing its type? | I have a template function, that should get std::shared_ptr<sometype>.
Inside of function I want to make a temporary variable with std::shared_ptr<sometype>, but I can't put sometype as template param because I don't know it.
#include <memory>
template<typename sometypePtr>
void foo()
{
sometypePtr tmp_ptr = std::make_shared<sometype>(); //compilation error, because we don't know sometype
}
int main()
{
foo<std::shared_ptr<int>>();
return 0;
}
Is there some common way of making variable with std::shared_ptr<sometype> type?
| Assuming that sometypePtr is a non-array std::shared_ptr, then you can use sometypePtr::element_type.
template<typename sometypePtr>
void foo()
{
sometypePtr ptr = std::make_shared<typename sometypePtr::element_type>();
}
If sometypePtr is an array std::shared_ptr, you will have to supply the extent as well as the type.
|
70,987,964 | 70,988,078 | C++14: enumeration previously declared with fixed underlying type: different behavior between compilers | Sample code:
enum E : char;
enum E;
Invocations:
$ g++ -std=c++14 -pedantic -Wall -Wextra -c
<nothing>
$ clang++ -std=c++14 -pedantic -Wall -Wextra -c
<source>:2:6: error: enumeration previously declared with fixed underlying type
$ icc -std=c++14 -pedantic -Wall -Wextra -c
<nothing>
$ cl /std:c++14 /Za
<source>(2): error C3432: 'E': a forward declaration of an unscoped enumeration must have an underlying type
<source>(2): error C3433: 'E': all declarations of an enumeration must have the same underlying type, was 'char' now 'int'
Is this code well-formed?
What the standard says?
| From [dcl.enum]/3:
An unscoped enumeration shall not be later redeclared as scoped and each redeclaration shall include an enum-base specifying the same underlying type as in the original declaration.
Emphasis added. Clang is correct.
|
70,988,138 | 70,988,249 | Sort elements alphabetically but keep one always at the beginning | I have elements of the following type stored in a collection.
class Element
{
public:
bool IsDefault { false };
std::wstring Name { };
Element() = default;
Element(const bool isDefault, std::wstring name) : IsDefault { isDefault }, Name { std::move(name) }
{}
bool operator==(const Element& other) const noexcept = default;
};
Note there can only be one element with IsDefault == true. What I want to achieve is sort the collection alphabetically (case-insensitive), but put the one element with IsDefault == true always at the beginning, regardless of its name.
My current code works, but I am looking for a way that is more efficient (as it is now, finding the one element with IsDefault == true takes O(N) and then sorting the collection takes O(N log N) afterwards) ore more idiomatic / requires less code. What can I do to improve it? Is there a way to achieve my goal with a single call to std::ranges::sort or some other function?
I can make use of C++20 features if required.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector elements { Element(false, L"World"), Element(true, L"Foo"), Element(false, L"Zoo"), Element(false, L"Bar") };
// Find the default element and remove it from the vector.
Element defaultElement;
for (const auto& e : elements)
{
if (e.IsDefault)
{
defaultElement = e;
std::erase(elements, e);
break;
}
}
// Sort the remaining elements alphabetically
std::ranges::sort(elements, [](const Element& a, const Element& b) noexcept
{
const auto& first { a.Name };
const auto& second { b.Name };
return ::_wcsnicmp(first.c_str(), second.c_str(), std::min(first.size(), second.size())) < 0;
});
// Insert the default element at index 0
elements.insert(std::begin(elements), defaultElement);
_ASSERT(elements.at(0).Name == L"Foo");
_ASSERT(elements.at(1).Name == L"Bar");
_ASSERT(elements.at(2).Name == L"World");
_ASSERT(elements.at(3).Name == L"Zoo");
}
| Include the default in the comparison:
if(a.default != b.default)
return b.default < a.default; // true, if a is true -> a is less
// or more elegant (thanks, Adrian, for the hint): simply
return a.default;
// rest of comparison
|
70,988,185 | 70,988,294 | C++ class question: why this "get" method exists | In my textbook on the chapter introducing classes it gives this example class:
class clockType
{
public:
void setTime(int, int, int);
void getTime(int&, int&, int&) const;
void printTIme() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType&) const;
private:
int hr;
int min;
int sec;
};
The definition of getTime is
void clockType::getTime(int& hours, int& minutes, int& seconds) const
{
hours = hr;
minutes = min;
seconds = sec;
}
What is the purpose of this getTime function? It's not returning anything to the caller, so I it doesn't seem useful to the user.
Also, you pass in parameters but then the arguments are assigned to the private member variables? That also doesn't make sense to me.
| You are passing to your function getTime 3 references and these in the getTime function are filled with the private time values. Then once this function is called you will be able to access the time values simply by using the variables you passed by reference. Note that unless you create a Time object that contains these three integers, there is no direct way to return three integers in C++.
|
70,988,313 | 70,988,342 | In headers, should variables be declared as "extern" even if they are class data members? | I read in other posts that header variables should be declared using "extern" to prevent multiple definitions / memory allocation if the header is imported into several .cpp files.
Is it also the case when these variables are class data members? I think not because including the class header don't create instances, so I don't see why a memory allocation would occur, but I'm not sure.
| The answer is no. To do so generates a compiler error.
|
70,988,402 | 70,989,879 | SFINAE User-Defined-Conversion Operator | I'm trying to do a templated user-defined-conversion that uses design by introspection.
In C++20 I can do the following:
template<typename T>
operator T() const
{
if constexpr( requires { PFMeta<T>::from_cursor(*this); } )
{
return PFMeta<T>::from_cursor(*this);
}
else
{
T x;
std::memcpy(&x, &data, sizeof(x));
return x;
}
}
i.e. if PFMeta<T>::from_cursor(const struct PFCursor&) is defined then use it else do a memcpy. (longer example here in godbolt: https://godbolt.org/z/abed1vsK3)
I love this approach but unfortunately this library will need to work on C++17 too.
So I've been trying SFINAE as an alternative to the concepts but it's very tricky.
I finally managed to get something similar but with a templated method as rather than the user-defined-conversion operator itself:
template<typename T, typename = void>
struct has_from_cursor : std::false_type { };
template<typename T>
struct has_from_cursor<T, decltype( PFMeta<T>::from_cursor(std::declval<struct PFCursor>()), void() ) > : std::true_type { };
// ...
template<class T>
std::enable_if_t<has_from_cursor<T>::value, T> as() const
{
return PFMeta<T>::from_cursor(*this);
}
template<class T>
std::enable_if_t<!has_from_cursor<T>::value, T> as() const
{
T x;
std::memcpy(&x, &data, sizeof(x));
return x;
}
I tried the following which compiles but does not work (I can't cast with it):
template<typename T>
operator std::enable_if_t<has_from_cursor<T>::value, T>() const
{
return PFMeta<T>::from_cursor(*this);
}
template<typename T>
operator std::enable_if_t<!has_from_cursor<T>::value, T>() const
{
T x;
std::memcpy(&x, &data, sizeof(x));
return x;
}
Longer example here: https://godbolt.org/z/5r9Mbo18h
So two questions:
Can I do effectively what I can do with concepts with just SFINAE in C++17 for the user defined conversion operator?
Is there a simpler way to do the as approach than the type traits & enable_if? Ideally I'd like to do something like define the default templated method and then have a specialisation to be preferred if the condition is there (i.e. there is a meta class with a static member function defined).
Thanks!
|
Can I do effectively what I can do with concepts with just SFINAE in C++17 for the user defined conversion operator?
Consider that C++17 support if constepr. Given that you've developed a has_from_cursor custom type traits that inherit from std::true_type or from std::false_type, you can use it for if constexp.
I mean (caution: code not tested)
template<typename T>
operator T() const
{ // .............VVVVVVVVVVVVVVVVVVVVVVVVV
if constexpr( has_from_cursos<T>::value )
{
return PFMeta<T>::from_cursor(*this);
}
else
{
T x;
std::memcpy(&x, &data, sizeof(x));
return x;
}
}
Is there a simpler way to do the as approach than the type traits & enable_if? Ideally I'd like to do something like define the default templated method and then have a specialisation to be preferred if the condition is there (i.e. there is a meta class with a static member function defined).
I suppose you can try tag-dispatching...
I mean something as calling 'as()', from operator T() with an additional int argument
template<typename T>
operator T() const
{ return as<T>(0); } // <-- call as() with a int
where there is a as() specific for from_cursos class enabled, that receive an unused int and is simply SFINAE enabled/disabled through decltype()
template <typename T> // ........accept an int; best match
decltype(PFMeta<T>::from_cursor(*this)) as (int) const
{ return PFMeta<T>::from_cursor(*this); }
and a generic as(), receiving a long
template <typename T>
T as (long) const // <-- accept a long; worst match
{
T x;
std::memcpy(&x, &data, sizeof(x));
return x;
}
The trick is the unused argument: a int.
When the specialized as() is enabled, if preferred because accept a int so is a better match.
When the specialized as() is disabled, remain the generic as() as better-than-nothig match.
|
70,989,133 | 70,989,209 | Overloading operator () instead of [] for indexing | An old code base I'm refactoring has a rather unorthodox way to access n dimensional vectors by overloading the () operator instead of the [] operator.
To illustrate, suppose Vec is a class that overloads both operators for indexing purpose of an internal list of doubles.
Vec v, w;
int index = 651;
double x = v(index); // they index like this ..
double y = w[index]; // .. instead of like normally..
I can only think of one good reason why you would do this: The operator[] requires an argument of type size_t which may or may not be uint64 depending on the platform. On the other hand, the index type used in the code is mostly int, which would mean a lot of implicit/explicit type casting when indexing. The code is extremely indexing heavy, so I'm quite hesitant to change this.
Does this really makes any sense for todays modern compilers and 64bit platforms? I quickly whipped up a test on https://godbolt.org/ You can try it out here here
I was primarily concerned with the latest x64 gcc and Visual Studio compilers, but the difference shows when compiling in x86-64 gcc (11.2). Gcc adds a cdqe instruction for the () operator, which we know may be less efficient.
I am a bit puzzled. Why would one make this choice?
Update
As explained in the answers, my assumption about operator [] being locked to size_t type size was incorrect. If you index with int instead of uint64 indices, the compiled code is nearly the same, save using different registers and constants.
The idea to provide multiple indices for multiple dimensions with () is quite a nice one, I must say. Wasn't actually used anywhere in the codebase, so I think it's just better to replace it with []. I'm also happy to see it handled by the proper indexing operator instead in future versions of C++.
| One "problem" with [] is when you have multiple dimensions. With an array you can do arr[val1][val2], and arr[val1] will give you an array you can index with [val2]. With a class type this isn't as simple. There is no [][] operator so the [val1] needs to return an object that [val2] can be applied to. This means you need to create another type and provide all the functionality you want. With (), you can do data(val1, val2) and no intermediate object is needed.
|
70,989,159 | 70,989,374 | Check product in range postive or negative | You are given two integers A and B. Your task is to determine if the product of the integers A,A+1,A+2,...,B is positive, negative or zero.
Input
The input contains two integers A and B (−109≤A≤B≤109).
Output
If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.
#include<iostream>
using namespace std;
int main ()
{
long long num1,num2;
bool check=false;
long long count=0;
cin>>num1>>num2;
while(num1<=num2)
{
if(num1==0)
{
check=true;
break;
}
if(num1<0)
{
count++;
num1++;
}
else
{
num1++;
}
}
if(count%2==0&&check==false)
{
cout<<"Positive";
}
else if(count%2!=0&&check==false)
{
cout<<"Negative";
}
else
cout<<"Zero";
return 0;
}
how can i get better algoritm which not take much time and without overflow if someone have better idea to check if the product is postive or negative or zero ?
| You probably remember from when you were little that the product of two positive numbers is positive.
You probably also remember that the product of two negative numbers is positive, and that the product of one negative and one positive number is negative.
In other words, multiplying by a positive number has no effect on the sign, and multiplying by a negative number turns + into - and - into +.
From this, you can deduce first of all that you can ignore the positive part of the range, as it has no effect on the result.
You can also deduce that the product of three negative numbers is the product of one positive number and one negative number, so it is negative.
You can further deduce that the product of four negative numbers is the product of two positive number, so it is positive.
Now you can discover a very simple pattern, and figure out how to solve this problem without multiplying any numbers at all - you only need to care about
Is there a zero involved?
How many negative numbers are there?
Working out the details left as an exercise.
(If your solution is more than a couple of lines long, you're on the wrong track.)
|
70,989,165 | 70,989,539 | How to support a range based loop in polymorphic classes (containing vector and set)? | I would like to iterate over some items in my class
for (const auto i: myclass) { /* do stuff with i */}
For this I want to expose the iterator of whatever STL container happens to be storing my data inside myclass.
My class is polymorphic and has the following hierarchy:
#include <set>
#include <vector>
class Base_t {
public:
//works for the set, but not for the vector
//using iterator_t = decltype(std::declval<std::set<int>>().cbegin());
//does not work, see error below.
using iterator_t = std::iterator<std::input_iterator_tag, int>;
virtual iterator_t begin() = 0;
virtual iterator_t end() = 0;
};
class MyVector_t: public Base_t {
std::vector<int> v;
public:
iterator_t begin() override { return v.begin(); }
iterator_t end() override {return v.end(); }
};
class MyTree_t: public Base_t {
std::set<int> s;
public:
iterator_t begin() override { return s.begin(); }
iterator_t end() override {return s.end(); }
};
//#################################################
//the class using these things looks like:
//#################################################
class Worker_t {
Base_t& container; //polymorphic container
public:
Worker_t(const bool UseTree): container(*CreateContainer(UseTree)) {}
Base_t* CreateContainer(const bool UseTree) const {
if (UseTree) { return new MyTree_t(); }
else { return new MyVector_t(); }
}
//need an iterator into the container to use it.
void DoStuff() { for (const auto i: container) { printf("%i",i); } }
};
int main(const int argc, const char* argv[]) {
const auto UseTree = true;
Worker_t worker1(UseTree);
worker1.DoStuff();
Worker_t worker2(!UseTree);
worker2.DoStuff();
}
This gives the error:
no viable conversion from returned value of type 'std::set::const_iterator' (aka '__tree_const_iterator<int, std::__tree_node<int, void *> *, long>') to function return type 'Base_t::it' (aka 'iterator<std::input_iterator_tag, int>')
I could make the hierarchy a CRTP setup, but I need the methods to be virtual.
template <typename T>
class Base_t<T> {
....
};
class Derived: Base_t<Derived> {
...
};
Does not work for me, because the code using the classes only knows about Base_t, not about anything else, that is, the class using these things looks like:
class Worker_t {
Base_t& container; //polymorphic container
public:
Worker_t(const bool UseTree): container(*CreateContainer(UseTree)) {}
Base_t* CreateContainer(const bool UseTree) const {
if (UseTree) { return new MyTree_t(); }
else { return new MyVector_t(); }
}
//need an iterator into the container to use it.
void DoStuff() { for (const auto i&: container) { /* do stuff*/ } }
};
What would be the minimal changes needed to make the code work, preferably using virtual methods?
For the record I'm using c++20
Apple clang version 13.1.6 (clang-1316.0.19.2)
Target: x86_64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
| You're attempting to force runtime polymorphism into a box designed for compile-time polymorphism. That will naturally create problems.
The iterator mechanism is based on compile-time mechanisms being able to ask questions of the iterator. Iterator tags are nothing like base classes. Iterator tag types do not do anything at runtime; they are solely used to allow compile-time metaprogramming (template or constexpr-based) to detect if an iterator's type provides the interface of a particular iterator category.
In runtime polymorphism, the base class defines everything. Everything, directly and explicitly. Derived classes can change the implementation, but they cannot change the compile-time interface.
An iterator's value_type (the type the iterator "points" to) is a compile-time construct. vector<int> has a different iterator type from vector<float>. They both model the same kind of iterator (random-access), but the types themselves have no runtime relationship. Iterator types are largely unaware of each other, even if they have the same iterator category and value_type.
std::array<int, 5> and std::vector<int> both have RandomAccessIterators over the same value_type, but the two iterator types have nothing in common. They can be used in the same compile-time polymorphic interfaces, but they cannot be used interchangeably at runtime.
Iterator categories are not base classes.
Since the base class defines a virtual interface which returns a concrete type, all properties of such iterators are defined by the base class. Derived classes can provide the actual range of values, but all compile-time aspects of the iterators must be fixed at compile time. This includes the underlying type of the iterator.
If you are fine with restricting all of your derived classes to using a particular container with a particular iterator, that's fine. But if you want them to define their own containers with different iterator types, that's a problem.
The only way around this is to create a type-erased iterator type for your base class, which can be filled in by any iterator and itself uses runtime polymorphism to access the real iterator type. This isn't trivial to implement and involves significant overhead (as every operation on the iterator is now a dynamic dispatch of some form).
Also, such an iterator can only ever model a specific kind of iterator. So if you want derived classes to be able to store data in a RandomAccessIterator or a ForwardIterator, your type-erased iterator must only expose itself as a ForwardIterator: the lowest common denominator.
|
70,989,418 | 70,989,494 | Undefined struct 'addrinfo' winsock2 | I encountered an error and I didn't find any solution (even over the internet)
I created aQt app to receive data using a TCP protocol and plot them using QcustomPlot.
I have the following files:
mainwindow.h :
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_mainwindow.h"
#include <QVector>
#include <iostream>
class MainWindow: public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
// ...
private:
struct addrinfo _hints;
struct addrinfo* _result = NULL;
// ...
};
mainwindow.cpp :
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
#include "mainwindow.h"
#include <QVector>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//...
}
and the main.cpp file:
#include "mainwindow.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
I have the following error:
'MainWindow::hints' uses undefined struct 'addrinfo' (compiling source file main.cpp).
I don't understand why I have this error, because I tested the same program in a classic consol app following the microsoft tutorial and it was working.
I believe it comes from the includes, but I still dont have a clue about which one causes that.
| You need to #include something in your mainwindow.h that defines struct addrinfo, because your MainWindow class has a member variable of that type. At the moment you include all the socket stuff only in your *.cpp file.
|
70,990,248 | 70,990,326 | Extract list of types from std::tuple for template class | Suppose I have the following class
class Example {
public:
using value_type = std::tuple<
uint8_t,
uint8_t,
uint16_t
>;
private:
value_type _value;
};
Now, I want to be able to create another class based upon this type that wraps each of the classes types in another type. Based upon Wrapping each type in a variadic template in a templated class, I know I can accomplish half my goal via:
template <typename T>
class Wrapper;
template <typename ... ARGS>
class ExampleWrapper {
private:
std::tuple<Wrapper<ARGS>...> _args;
};
However, what I can't figure out is how to get ARGS if all I know is T, where T is Example. I would like to be able to use ExampleWrapper as follows:
ExampleWrapper<Example> myWrapper;
| You can use template partial specialization to get ARGS:
template <typename T>
class Wrapper;
template <typename Tuple>
class ExampleWrapper;
template <typename ... ARGS>
class ExampleWrapper<std::tuple<ARGS...>> {
private:
std::tuple<Wrapper<ARGS>...> _args;
};
Then:
ExampleWrapper<Example::value_type> myWrapper;
|
70,990,743 | 70,997,791 | How to tell QPluginLoader to check for dll dependencies in containing folder instead of exe folder | I have a dll which is some kind of plugin and I intend to deploy it as a package, the dll and all it's dependencies (also dlls) in one package. The issue that I have is that the dll is checking for it's dependencies in the exe folder instead of its own folder, its dependencies are next to it.
Is there a way to tell it where the dependencies are?
Edit:
In my case the plugin is loaded by QPluginLoader and the answers hinted that this is relevant as the loader decides where to look for dependencies.
| As @Alex Reinking pointed out the loader is responsible for finding the dlls, in my case the loading was done by QPluginLoader and a solution was to set the current directory to the plugin directory as the loader looks in the current directory for dlls:
QDir pluginsDir(QLatin1String("../src/"));
QDir::setCurrent(pluginsDir.path());
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
|
70,990,821 | 70,990,939 | How create method for get the child (QWebEngineView) of th curent view tab (QTabWidget)? | I'm trying to make some project with QTabWidget (a litle browser and a text editor with multiple tab like notepad++) but I'm stuck in 2 project when I try to edit a value of widget (QWebEngine or QTextEdit) inside of QTabWidget. This is the code for the litle browser project:
fp.h :
#ifndef FP_H
#define FP_H
#include <QMainWindow>
#include <QWebEngineView>
#include <QWidget>
#include <QLabel>
QT_BEGIN_NAMESPACE
namespace Ui { class fp; }
QT_END_NAMESPACE
class fp : public QMainWindow
{
Q_OBJECT
public:
fp(QWidget *parent = nullptr);
~fp();
public slots:
void newtab();
void deltab();
void newpage();
QWebEngineView *ap();
int cui();
private:
Ui::fp *ui;
QWebEngineView *webnav;
};
#endif // FP_H
fp.cpp
#include "fp.h"
#include "ui_fp.h"
fp::fp(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::fp)
{
ui->setupUi(this);
ui->in_url->setText("https://google.com");
}
fp::~fp()
{
delete ui;
}
void fp::newtab()
{
QWebEngineView *webnav = new QWebEngineView;
webnav->load(QUrl("https://google.com"));
webnav->setObjectName("webnav");
ui->in_url->setText("https://google.com");
ui->onglet->addTab(webnav,"Home");
}
int fp::cui()
{
return ui->onglet->currentIndex();
}
QWebEngineView *fp::ap()
{
return ui->onglet->currentWidget()->findChild<QWebEngineView *>("webnav");
}
void fp::deltab()
{
ui->onglet->removeTab(cui());
}
void fp::newpage()
{
QString use_url = ui->in_url->text();
ap()->load(use_url);
}
and there what look like the .ui
Image of .ui in Qdesigner
I try to make work the method "ap" it should return the QWebEngineView child of current viewed tab but when I call the slots "newpage" (it currently using "ap" method) it just crash the application. This slot is trigered when I enter a new URL in the QLineEdit in .ui
(before that I create a new tab whit a QWebEngineView inside whit the slot "newtab" )
void fp::newtab()
{
QWebEngineView *webnav = new QWebEngineView;
webnav->load(QUrl("https://google.com"));
webnav->setObjectName("webnav");
ui->in_url->setText("https://google.com");
ui->onglet->addTab(webnav,"Home");
}
So what wrong whit that line it the good method for get child widget of a QTabWidget? If it the good method what should be modified to make it work?
QWebEngineView *fp::ap()
{
return ui->onglet->currentWidget()->findChild<QWebEngineView *>("webnav");
}
| Try something like:
QWebEngineView *view = qobject_cast<QWebEngineView *>(
this->ui->onglet->widget(0)
);
Note to put above somewhere in fp's methods (where you need the reference).
I could use ui->onglet->currentWidget(), but the difference is, that will not work once you have multiple tabs.
|
70,990,839 | 70,995,175 | How to link SDL_ttf and SDL_image libraries using cmake in windows? | I have trouble including and linking SDL_ttf and SDL_image to my project. I have a cmake file that works only for SDL and SDL_gfx on Clion. I guess the problem is from the cmake file.
I got several errors when I build the project:
undefined reference to `FUNCTION'
The libraries which I used for my project: https://github.com/satayyeb/sdl2-libraries
sdl2 folder (where library files are located) tree:
sdl2-|
|-sdl2-image-include
| |-SDL_image.h
|
|-sdl2-image-lib
| |-libSDL2_image.a
| |-libSDL2_image.dll.a
| |-libSDL2_image.la
|
|-sdl2-ttf-include
| |-SDL_ttf.h
|
|-sdl2-ttf-lib
|-libSDL2_ttf.a
|-libSDL2_ttf.dll.a
|-libSDL2_ttf.la
CMakeLists.txt :
set(SOURCE src/main.c)
set(PROJECT_NAME state.SAT)
cmake_minimum_required(VERSION 3.19)
project(${PROJECT_NAME} C)
set(CMAKE_C_STANDARD 11)
set(SDL2_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-include")
set(SDL2_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-lib")
set(SDL2_GFX_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-gfx-include")
set(SDL2_GFX_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-gfx-lib")
set(SDL2_IMAGE_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-image-include")
set(SDL2_IMAGE_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-image-lib")
set(SDL2_TTF_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-ttf-include")
set(SDL2_TTF_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-ttf-lib")
set(SDL2_FLAGS "-mwindows -Wl,--no-undefined -static-libgcc")
add_library(SDL2 STATIC IMPORTED)
add_library(SDL2main STATIC IMPORTED)
add_library(SDL2_GFX STATIC IMPORTED)
add_library(SDL2_IMAGE STATIC IMPORTED)
add_library(SDL2_TTF STATIC IMPORTED)
set_property(TARGET SDL2 PROPERTY IMPORTED_LOCATION "${SDL2_LIB_DIR}/libSDL2.a")
set_property(TARGET SDL2main PROPERTY IMPORTED_LOCATION "${SDL2_LIB_DIR}/libSDL2main.a")
set_property(TARGET SDL2_GFX PROPERTY IMPORTED_LOCATION "${SDL2_GFX_LIB_DIR}/libsdl-gfx.a")
set_property(TARGET SDL2_IMAGE PROPERTY IMPORTED_LOCATION "${SDL2_IMAGE_LIB_DIR}/libSDL2_image.a")
set_property(TARGET SDL2_TTF PROPERTY IMPORTED_LOCATION "${SDL2_TTF_LIB_DIR}/libSDL2_ttf.a")
set(SDL2_LIBS SDL2 SDL2main SDL2_GFX SDL2_TTF SDL2_IMAGE m dinput8 dxguid dxerr8 user32 gdi32 winmm imm32 ole32 oleaut32 shell32 version uuid)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ${SDL2_FLAGS}")
file(GLOB_RECURSE SOURCE "src/*.c" "src/*.h")
add_executable("${PROJECT_NAME}" "${SOURCE}")
include_directories(${SDL2_INCLUDE_DIR} ${SDL2_GFX_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR} ${SDL2_TTF_INCLUDE_DIR})
target_link_libraries(${PROJECT_NAME} ${SDL2_LIBS})
| I found the problem:
In sdl2-image-lib and sdl2-ttf-lib directory there are libSDL2_image.dll.a and libSDL2_ttf.dll.a binary files that must be linked instead of libSDL2_image.a and libSDL2_ttf.a files.
dll files must be copied to the directory where the EXE file is located. the dll files are in bin folders of the library.
The libraries which I used for my project:
https://github.com/satayyeb/sdl2-libraries
and the modified CMakeLists.txt:
set(SOURCE src/main.c)
set(PROJECT_NAME island_soldier)
cmake_minimum_required(VERSION 3.19)
project(${PROJECT_NAME} C)
set(CMAKE_C_STANDARD 11)
set(SDL2_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-include")
set(SDL2_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-lib")
set(SDL2_GFX_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-gfx-include")
set(SDL2_GFX_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-gfx-lib")
set(SDL2_IMAGE_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-image-include")
set(SDL2_IMAGE_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-image-lib")
set(SDL2_TTF_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-ttf-include")
set(SDL2_TTF_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/sdl2/sdl2-ttf-lib")
set(SDL2_FLAGS "-mwindows -Wl,--no-undefined -static-libgcc")
add_library(SDL2 STATIC IMPORTED)
add_library(SDL2main STATIC IMPORTED)
add_library(SDL2_GFX STATIC IMPORTED)
add_library(SDL2_IMAGE_DLL STATIC IMPORTED)
add_library(SDL2_TTF_DLL STATIC IMPORTED)
set_property(TARGET SDL2 PROPERTY IMPORTED_LOCATION "${SDL2_LIB_DIR}/libSDL2.a")
set_property(TARGET SDL2main PROPERTY IMPORTED_LOCATION "${SDL2_LIB_DIR}/libSDL2main.a")
set_property(TARGET SDL2_GFX PROPERTY IMPORTED_LOCATION "${SDL2_GFX_LIB_DIR}/libsdl-gfx.a")
set_property(TARGET SDL2_IMAGE_DLL PROPERTY IMPORTED_LOCATION "${SDL2_IMAGE_LIB_DIR}/libSDL2_image.dll.a")
set_property(TARGET SDL2_TTF_DLL PROPERTY IMPORTED_LOCATION "${SDL2_TTF_LIB_DIR}/libSDL2_ttf.dll.a")
set(SDL2_LIBS mingw32 SDL2 SDL2main SDL2_GFX SDL2_TTF_DLL SDL2_IMAGE_DLL m dinput8 dxguid dxerr8 user32 gdi32 winmm imm32 ole32 oleaut32 shell32 version uuid)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ${SDL2_FLAGS}")
file(GLOB_RECURSE SOURCE "src/*.c" "src/*.h")
IF(WIN32)
SET(GUI_TYPE WIN32)
ENDIF(WIN32)
IF (APPLE)
SET(GUI_TYPE MACOSX_BUNDLE)
ENDIF (APPLE)
add_executable("${PROJECT_NAME}" ${GUI_TYPE} "${SOURCE}")
include_directories(${SDL2_INCLUDE_DIR} ${SDL2_GFX_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR} ${SDL2_TTF_INCLUDE_DIR})
target_link_libraries(${PROJECT_NAME} ${SDL2_LIBS})
|
70,991,106 | 70,993,917 | In a variadic function template can the return type be deduced from the template parameter pack elements | I am trying to write a variadic function template.
The first argument to the function is an integer index value.
The rest of the (variable number of) arguments represent the variable number of arguments.
This function must return the argument at the location index.
For example, if function is invoked as
`find_item(1, -1, "hello", 'Z', 10.03)`
it must return "hello"
If invoked as
find_item(2, -1, "hello", 'Z', 10.03)
it must return 'Z'
If invoked as
find_item(3, -1, "hello", 'Z', 10.03, 'Q', 100)
it must return 10.03 etc....
I was trying something like the following code :
template <class T>
auto find_item(int inx, T val) { return val ;}
// GENERAL CASE
template <class T, class... Others>
auto find_item(int inx, T a1, Others ... others) {
if(inx==0) return a1 ;
else return print(inx-1, others...) ;
}
int main() {
cout<<find_item(1, -1, "hello", string("abvd"), 10.03)<<endl ; ;
}
This code does not compile because the return type not being uniform, can not be deduced.
I want to know if there is any way that this can be achieved. Or is it an invalid use case all together.
If this can be achieved, then how.
|
I want to know if there is any way that this can be achieved.
No.
In C/C++ (that are statically typed languages) the type returned from a function must depends from the types of the arguments, not from the values.
So the types returned from the following calls
find_item(1, -1, "hello", 'Z', 10.03);
find_item(2, -1, "hello", 'Z', 10.03);
find_item(3, -1, "hello", 'Z', 10.03);
must be the same.
Point.
You can get around this rule returning a std::variant (that can contain values of different types), or a std::any (that can contain generic values), but a type that is determined independently from the received value.
Different if you pass the index of type/value you want (the first argument, in your case) as a template parameter.
I mean: different if you call find_item() as follows
find_item<1>(-1, "hello", 'Z', 10.03);
find_item<2>(-1, "hello", 'Z', 10.03);
find_item<3>(-1, "hello", 'Z', 10.03);
Now find_item<1>() can return a char const *, find_item<2>() can return a char and find_item<3>() can return a double.
This is because find_item<1>(), find_item<2>() and find_item<3>() are different functions, so can have different return types.
But... this way... we've almost obtained the std::get<>() that extract values from a std::tuple.
Unfortunately you can use this solution only when the index (the template parameter) is known compile time.
In other words, you can't make something as follows
for ( auto i = 1 ; i < 4 ; ++i )
{ // .............NO! ---V
auto value = find_item<i>(-1, "hello", 'Z', 10.03);
}
|
70,991,246 | 70,991,575 | How to format output like this | My code is like this so far :
void matrix::print(int colWidth) const
{
cout << getRows() << " x " << getCols() << endl;
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
for (unsigned x = 0; x < getRows(); x++) {
cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
cout << setw(colWidth) << at(x, y) << " |";
}
cout << endl;
}
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
}
But the output depends on the colWidth which will be the space between each number printed. So how can I adjust my dashes to be printed like the following no matter the colWidth it should align.
One output should look like this:
Second output is like this:
| If the column width is a parameter, you're almost done with your code. Just turn the cout<<"--------" into:
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-');
That code prints a string of dashes, which width is: number of matrix columns, times column width plus 2, plus 1:
Plus 2 because you are appending a " |" to each column.
Plus 1 because you are adding a '|' at the beginning of each row.
You may want to check for empty matrices at the beginning of your print method.
[Demo]
#include <initializer_list>
#include <iomanip> // setw
#include <iostream> // cout
#include <vector>
class matrix
{
public:
matrix(std::initializer_list<std::vector<int>> l) : v{l} {}
size_t getRows() const { return v.size(); }
size_t getCols() const { if (v.size()) { return v[0].size(); } return 0; }
int at(size_t x, size_t y) const { return v.at(x).at(y); }
void print(int colWidth) const
{
std::cout << "Matrix: " << getRows() << " x " << getCols() << "\n";
// +2 due to " |", +1 due to initial '|'
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
for (unsigned x = 0; x < getRows(); x++) {
std::cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
std::cout << std::setw(colWidth) << at(x, y) << " |";
}
std::cout << "\n";
}
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
}
private:
std::vector<std::vector<int>> v{};
};
int main()
{
matrix m{{1, 2}, {-8'000, 100'000}, {400, 500}};
m.print(10);
}
// Outputs
//
// Matrix: 3 x 2
// -------------------------
// | 1 | 2 |
// | -8000 | 100000 |
// | 400 | 500 |
// -------------------------
|
70,992,159 | 70,992,244 | can someone explain to me why my string is not not showing in output it happens to me a lot and this is a simple example, | can someone tell me why s is not showing up.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string a="1 23";
string s="";
if(a[1]==' '){s[0]=a[1];
cout<<s; }
return 0;
}
| You are not allocating any character memory for s to refer to, so s.size() is 0 and thus [0] is out of bounds, and writing anything to it is undefined behavior 1.
1: in C++11 and later, you can safely write '\0' to s[s.size()], but you are not doing that here.
Try this instead:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string a = "1 23";
string s = "";
if (a[1] == ' ') {
s += a[1];
// alternatively:
s = a[1];
// alternatively:
s.resize(1);
s[0] = a[1];
cout << s;
}
return 0;
}
Just note that a[1] is the whitespace character ' ', so while you can assign that character to s, and it will print to the console, you just won't (easily) see it visually in your console. Any of the other characters from a would be more visible.
|
70,992,743 | 70,993,738 | i am getting this error while making a build for opencv project on mac os (intel chip) | i am running any code(over xcodes)even "hello world" and i am getting the same error all the time
how can i fix this ?????
dyld: Library not loaded: /usr/local/opt/opencv/lib/libopencv_stitching.4.5.dylib
Referenced from: /Users/khaledzbidat/Library/Developer/Xcode/DerivedData/OpencvCourse_-hhaivjyxxrgltdhgizcoxxkwobzu/Build/Products/Debug/OpencvCourse_
Reason: no suitable image found. Did find:
/usr/local/opt/opencv/lib/libopencv_stitching.4.5.dylib: code signature in (/usr/local/opt/opencv/lib/libopencv_stitching.4.5.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.
/usr/local/lib/libopencv_stitching.4.5.dylib: code signature in (/usr/local/lib/libopencv_stitching.4.5.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.
/usr/local/Cellar/opencv/4.5.4_4/lib/libopencv_stitching.4.5.4.dylib: code signature in (/usr/local/Cellar/opencv/4.5.4_4/lib/libopencv_stitching.4.5.4.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed.
(lldb)
| It looks like you need to disable library validation for your app to load this library. Apple are getting stricter and stricter about what will and will not run on macOS.
You can do this in the 'Signing and Capabilities' tab of your project settings for your app build target (my app is called VinylStudio, in this example):
Then, hopefully, your library will load and the app will run.
|
70,992,965 | 71,057,524 | How do I deliver OpenAL32.dll with my application without requiring OpenAL installation on the client machine? | I have a 32-bit C++ Windows application using the OpenAL library. I am using the official OpenAL setup to install the required DLL file, but when I publish my application, I would like to find a way to deliver it without requiring the user to install OpenAL seperately like I did.
With other DLL files, I simply add them to my project, but with OpenAL I seemed to get issues. Is this possible? And if so, how?
| Apparently, I mixed up the System32 and SysWow64 folders in Windows.
It should be the other way around!
System32 on 64-bit Windows contains 64-bit .dll files
SysWow64 on 64-bit Windows contains 32-bit .dll files
For reference:
https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-folders-in-windows/
What I did:
So I installed OpenAL from the official installation source. This installer copies the OpenAL32.dll files into the System32 and SysWow64 folders.
As my application is 32-bit I needed to copy OpenAL32.dll from SysWow64 folder into my executable directory. Once I uninstalled OpenAL (which removed these .dll files from my Windows System32 and SysWow64 folders, it worked with the .dll file accompanied with my executable file.
|
70,993,273 | 70,993,360 | Is MSVC correct in refusing to compile this code? | Consider this code (godbolt):
#include <type_traits>
#include <memory>
#include <cstdlib>
using namespace std;
template<auto L, class T = decltype(L)>
using constant = integral_constant<T, L>;
int main()
{
unique_ptr<void, constant<&free>> p1;
unique_ptr<void, constant<free>> p2; // <-- MSVC refuses to compile this line
return 0;
}
Why does MSVC refuse to compile the highlighted line? Is this code valid?
MSVC produces:
<source>(13): error C2975: 'L': invalid template argument for 'constant', expected compile-time constant expression
<source>(7): note: see declaration of 'L'
| Pre-C++20 it looks like a MSVC bug.
After C++20, the behavior is unspecified (thanks @heapunderrun)
since free is not in the list of functions you're allowed to take the addresses of. But I'd argue that it's still a bug (even if conformant), since MSVC lets you take the address of the same function if you use &.
Template argument deduction in this case is done as if by constexpr auto x = free; ([temp.arg.nontype]/1), and the above declaration is accepted by MSVC, deducing a function pointer.
Some implicit conversions are banned when passing a template argument, the allowed conversions are listed in [expr.const]/10 and include a "function-to-pointer conversion".
|
70,993,333 | 71,011,814 | Why my Qt test (which uses a QProcess) fails? | I created a Qt test which invokes another program thanks to a QProcess. After calling the QProcess::start method, my test waits for it to finish with the QProcess::waitForFinished method. When I run this test with Qt Creator, there's no problem. But when I run it with CTest, the QProcess::waitForFinished function always returns false. Can someone explain me why ? Thank you.
| Finally, I found a solution : the QProcess:start method couldn't find the program because the working directory of my Qt test wasn't good. So, I changed it with the QDir::setCurrent and now, it works.
|
70,993,819 | 70,993,882 | Is "this" a default parameter in a class method? | I've read somewhere that the "this" keyword is a default parameter (I suppose it's invisible or something) in any method of a class.
Is this true?
| "default parameter" is the wrong term. this can be thought of as an implicit paramter passed to member functions. If there were no member functions then you could emulate them with free functions like this:
struct Foo {
int x = 0;
};
void set_x(Foo* THIS, int x) {
THIS->x = x;
}
However, member functions do exists and the above can be written as:
struct Foo {
int x = 0;
void set_x(int x) {
this->x = x;
}
};
this is not passed to Foo::set_x explicitly. Nevertheless, inside the method you can use it to refer to the current object. It can be said to be an implicit parameter to the member function.
However, thats not the whole story. In member functions you actually do not need this to refer to members of the class. Instead of this->x just x would work as well and in contrast to other languages it is common style to ommit the this-> unless necessary. For more details I refer you to https://en.cppreference.com/w/cpp/language/this.
Note that it is not an implicit parameter to all methods of a class. You cannot refer to the current object via this in a static member function, because there is no "current object" in a static member function.
Also compare to python where self is explicitly passed:
class Foo:
def __init__(self):
self.x = 0
def set_x(self,x):
self.x = x
|
70,993,901 | 70,993,930 | C++ How can I combine and add functionality to the same inherited method by a class with multiple inheritance? | So say I have the class empire. empire inherits populationContainer and landContainer as such:
class empire : public populationContainer, public landContainer
Both of those parent classes have the method update(), each of which do their own thing; for example, the pop container calculates pop growth and the land container calculates land expansion.
I currently cannot call empire.update() because it is ambiguous. How do I have both methods get called at once? Additionally, what if I also want empire to have more instructions under update()?
I can call each method in turn like such:
void empire::update() {
populationContainer::update();
landContainer::update();
// Do other stuff
}
But doesn't this violate the open-closed principal? What if I want to add more 'container' classes with their own update() functions? I'd have to add each one to empire's update() function.
| My solution would be:
// If you add more base classes here, add them also to the 'update' method
class empire : public populationContainer, public landContainer
|
70,994,145 | 71,030,164 | Python Compile Mixed C and C++ Extension | I'm attempting to compile libspng with PyBind11 so I can easily convert image data into a numpy array.
The compilation process requires compiling a few C files and then linking them to C++. However, I'm not sure how to do this with Python setuptools. I've so far been compiling all C++ or all C modules in my practice, but on clang, this results in problems when I mix the pybind11 file with the C files.
Is there a simple way that I'm missing to compile and link the C files to C++ within setup.py?
I tried building an extension for libspng, but I wasn't sure how to reference the compiled shared object file which was in the build folder.
Thanks!
| In case it's helpful (and because I am procrastinating) I built a small demo based on the spng example
// pywrappers.cpp
#include <pybind11/pybind11.h>
#include <utility>
#include <cstdio>
extern "C" {
#include <spng/spng.h>
}
namespace py = pybind11;
std::pair<size_t, size_t> get_size(const std::string& filename)
{
FILE* fp = fopen(filename.c_str(), "rb");
if (fp == nullptr)
{
fclose(fp);
throw std::runtime_error("File not found");
}
spng_ctx* ctx = spng_ctx_new(0);
spng_set_crc_action(ctx, SPNG_CRC_USE, SPNG_CRC_USE);
size_t limit = 1024 * 1024 * 64;
spng_set_chunk_limits(ctx, limit, limit);
spng_set_png_file(ctx, fp);
struct spng_ihdr ihdr;
spng_get_ihdr(ctx, &ihdr);
spng_ctx_free(ctx);
fclose(fp);
return std::make_pair<size_t, size_t>(ihdr.width, ihdr.height);
}
PYBIND11_MODULE(foo, m)
{
m.def("get_size", &get_size);
}
# setup.py
from setuptools import setup, Extension
import pybind11
SPNG_SOURCE = './libspng-0.7.1' # Wherever you put the spng headers and .a
libfoo = Extension(
'foo',
sources=['pywrappers.cpp'],
extra_compile_args = ['-std=c++14'],
include_dirs=[SPNG_SOURCE, pybind11.get_include()],
extra_link_args=['-lspng_static','-lz'],
library_dirs=[SPNG_SOURCE]
)
if __name__ == "__main__":
setup(
name = 'foo',
ext_modules=[libfoo],
)
Build the extension as usual with e.g. python setup.py build_ext --inplace. Then for example
import foo
foo.get_size('stuff.png')
|
70,994,567 | 70,994,601 | Lambda functions with "=" capture and memory usage | In my mind when I create a lambda [=]{...} all variables from parent function clones to the lambda.
So the following code will use too much memory because variables a...z will be copied to lambda function:
void foo() {
long double a = 0.123456789;
long double b = 0.123456789;
long double c = 0.123456789;
//....
long double z = 0.123456789;
auto val = [=]() {return a+z;};
}
Is not it?
| [=] will cause only the variables that are actually used in the lambda to be captured by it.
In your case val will have a copy of a and z. Assuming there is no padding (which there shouldn't be), then sizeof(val) == 2*sizeof(long double).
|
70,994,857 | 70,994,884 | Should explicit keyword be used for move constructors? | This code does not compile. But if I remove the explicit keyword from the move constructor then it works. Why?
struct Bar {
Bar() {}
explicit Bar(const Bar& x) {}
explicit Bar(Bar&& x) {}
};
Bar bar() {
Bar x;
return x;
}
The compilation error is:
error: no matching function for call to 'Bar::Bar(Bar&)'
| The return statement copy-initializes the return value from the operand.
Copy-initialization doesn't consider explicit constructors. But explicit doesn't change that the constructors you defined are copy and move constructors. Therefore no other implicit constructors will be declared.
In effect, there is no viable constructor left to construct the return value.
If you remove the explicit on either of the constructors, there will be a viable constructor to construct the return value and it will compile. The move constructor will be preferred if it is not explicit, because of the special semantics of return statements.
Copy and move constructors should usually not be explicit.
|
70,994,879 | 70,996,278 | No suitable user-defined conversion with inherited classes | I'm struggling with casing a subclass as a superclass to store in a vector of superclass pointers. The objective is to have a vector of ContainerObjects which can be both bins and boxes.
This is a barebones example - in my code, I am passing in a definition of stuff to store in the box and then add the box to my inventory. That part is working fine, but it's adding the box to the inventory which is defeating me.
#include <memory>
#include <vector>
struct ItemData
{
};
class ContainerObject
{
};
using U_ContainerObjectPtr = std::unique_ptr<ContainerObject>;
class Box : ContainerObject
{
public:
Box(ItemData data)
{
// store the data in the box
}
};
// Another container type
class Bin : ContainerObject
{
};
using U_BoxPtr = std::unique_ptr<Box>;
using U_BinPtr = std::unique_ptr<Bin>;
class StorageArea
{
std::vector<U_ContainerObjectPtr> myStorageArea;
public:
void addContainer(U_ContainerObjectPtr container)
{
myStorageArea.push_back(container);
}
};
class DoingWork
{
private:
StorageArea area;
public:
void boxItem(ItemData data)
{
U_BoxPtr newBox = std::make_unique<Box>(data);
area.addContainer(newBox);
}
};
The error I am getting is "No suitable user-defined conversion from U_BoxPtr to U_ContainerObjectPtr" on the call to addContainer() in boxItem() which is understandable. I'm not sure what I need to do to resolve this, or even if this is actually possible.
Reasonably new to C++ as well.
| Firstly, you should make your inheritance publicly.
class Box : ContainerObject -> class Box : public ContainerObject
class Bin : ContainerObject -> class Bin : public ContainerObject
Secondly, std::unique_ptr implies only one owner, so it has no copy constructor/asignment only move constructor/asignment.
So you should do the following replacements:
area.addContainer(newBox); -> area.addContainer(std::move(newBox));
myStorageArea.push_back(container); -> myStorageArea.push_back(std::move(container));
The whole code looks like this:
#include <memory>
#include <vector>
struct ItemData
{
};
class ContainerObject
{
};
using U_ContainerObjectPtr = std::unique_ptr<ContainerObject>;
class Box : public ContainerObject
{
public:
Box(ItemData data)
{
// store the data in the box
}
};
// Another container type
class Bin : public ContainerObject
{
};
using U_BoxPtr = std::unique_ptr<Box>;
using U_BinPtr = std::unique_ptr<Bin>;
class StorageArea
{
std::vector<U_ContainerObjectPtr> myStorageArea;
public:
void addContainer(U_ContainerObjectPtr container)
{
myStorageArea.push_back(std::move(container));
}
};
class DoingWork
{
private:
StorageArea area;
public:
void boxItem(ItemData data)
{
U_BoxPtr newBox = std::make_unique<Box>(data);
area.addContainer(std::move(newBox));
}
};
|
70,995,081 | 70,995,312 | Switch-Case Range C++20 in Visual Studio Syntax Error '...' | Maybe a similar topic has already been discussed. But, I have a different problem. Here, I'm using C++ 20 in Visual Studio
I have code
#include<iostream>
using namespace std;
int main() {
int a;
cin >> a;
switch (a) {
case 1 ... 9:
cout << "satuan" << endl;
break;
case 10 ... 99:
cout << "puluhan" << endl;
break;
case 100 ... 999:
cout << "ratusan" << endl;
break;
case 1000 ... 9999:
cout << "ribuan" << endl;
break;
case 10000 ... 99999:
cout << "puluhribuan" << endl;
break;
}
}
And the problem is
Build started...
1>------ Build started: Project: If Then or Case, Configuration: Debug x64 ------
1>If Then or Case.cpp
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(8,9): error C2143: syntax error: missing ':' before '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(8,9): error C2059: syntax error: '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(11,10): error C2143: syntax error: missing ':' before '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(11,10): error C2059: syntax error: '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(14,11): error C2143: syntax error: missing ':' before '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(14,11): error C2059: syntax error: '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(17,12): error C2143: syntax error: missing ':' before '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(17,12): error C2059: syntax error: '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(20,13): error C2143: syntax error: missing ':' before '...'
1>D:\Multimedia\Teknik Informatika - Komputer - Elektronika\C++\Visual Studio\If Then or Case\If Then or Case.cpp(20,13): error C2059: syntax error: '...'
1>Done building project "If Then or Case.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have tried my code in C++11 (Using DevC++) and it's work. But, when I tried in C++20 (Using Visual Studio) this error. How can I fix this problem?
| Hey you can use if else statement instead
#include<iostream>
using namespace std;
int main() {
int a;
cin >> a;
if(a <= 9)
cout << "satuan" << endl;
else if(a <= 99)
cout << "puluhan" << endl;
else if(a <= 999)
cout << "ratusan" << endl;
else if(a <= 9999)
cout << "ribuan" << endl;
else if(a <= 99999)
cout << "puluhribuan" << endl;
}
|
70,995,142 | 70,996,114 | two triangles, line, and border in OpenGL | I'm quite confused on how I can make two triangles that are not beside each other (they have a gap between them) along with a line and a border. I have a code done already, but for some reason the triangles and line won't show up, only the border is the one showing up when I comment the triangle and line codes. The triangles, line, and border have color too, hopefully the code for that one is correct.
What do you think is wrong with my code?
#include<GL/glut.h>
#include<iostream>
using namespace std;
void triangle();
void line();
void border();
void display();
int main(int argc, char** argv){
glutInit(&argc, argv);
glutCreateWindow("simple");
glClearColor(1.0, 1.0, 0.0, 1.0);
glutDisplayFunc(display);
glutMainLoop();
}
void display(){
glClear(GL_COLOR_BUFFER_BIT);
triangle();
line();
border();
glFlush();
}
void triangle() {
glClear(GL_COLOR_BUFFER_BIT);
glTranslatef(0.0f,0.0f,-4.0f);
glBegin(GL_TRIANGLES);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(-1.0f,-0.25f);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(-0.5f,-0.25f);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(-0.75f,0.25f);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(0.5f,-0.25f);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(1.0f,-0.25f);
glColor3f(0.0f,0.0f,1.0f); glVertex2f(0.75f,0.25f);
glEnd();
glFlush();
}
void line() {
glClear(GL_COLOR_BUFFER_BIT);
glLineWidth(5.0f);
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 1.0); glVertex2f(-0.3, -0.3);
glColor3f(0.0, 0.0, 1.0); glVertex2f(0.3, -0.3);
glEnd();
glFlush();
}
void border() {
glClear(GL_COLOR_BUFFER_BIT);
glLineWidth(7.0f);
glBegin(GL_LINE_LOOP);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2f(-1, -1);
glVertex2f(-1, 1);
glVertex2f(1, 1);
glVertex2f(1, -1);
glEnd();
glFlush();
}
| The problem is that the color buffer is cleared before each mesh is drawn. This "clears" the previous draw mesh. Call glClear(GL_COLOR_BUFFER_BIT) once before drawing the scene in display, but don't clear the color buffer in triangle, line and border. Just remove glClear(GL_COLOR_BUFFER_BIT) from these functions.
|
70,995,704 | 70,995,904 | Using for_each on container with const_iterators? | If you iterate on an std container with this elegant formula:
for (auto& item: queue) {}
It will be using queue's begin and end functions.
Is there a way to use cbegin and cend without modifying the queue's source?
I tried with
for (const auto& item: queue) {}
But if begin or end is missing, it doesn't compile.
|
Is there a way to use cbegin and cend without modifying the queue's
source?
In C++20, you can use queue.cbegin() and queue.cend() to construct a ranges::subrange:
#include <ranges>
for (auto& item: std::ranges::subrange(queue.cbegin(), queue.cend())) {}
|
70,995,866 | 70,996,036 | Why does std::distance doesn't work on iterator of unordered_map? | I have this code:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
unordered_map<int, int> umap;
unordered_map<int, int>::iterator itr1, itr2;
itr1 = umap.begin();
itr2 = std::next(itr1, 3);
cout << distance(itr2, itr1);
return 0;
}
It compiles fine. But produces a Segmentation fault upon executing.
Why can't I find the distance between iterators?
| Your code has undefined behavior.
umap is empty, then std::next(itr1, 3) returns an invalid iterator.
Change the order of the arguments passed to std::distance.
InputIt must meet the requirements of LegacyInputIterator. The operation is more efficient if InputIt additionally meets the requirements of LegacyRandomAccessIterator
If InputIt is not LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. If InputIt is LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first and first is not reachable from last.
E.g.
unordered_map<int, int> umap { {1,1}, {2,2}, {3,3} };
unordered_map<int, int>::iterator itr1, itr2;
itr1 = umap.begin();
itr2 = std::next(itr1, 3);
cout << distance(itr1, itr2);
LIVE
|
70,995,922 | 70,995,935 | How does C/CPP know how to point to "next" struct node when the struct node is not yet defined? | When creating singly linked lists, it is common to create a Node struct as follows:
struct node {
int data;
struct node *next;
}
However, I was wondering how does the pointer to the next node next knows what struct node is if node's definition has not been done yet.
I have read from quora that the compiler fails to compile the following:
struct node {
int data;
struct node next;
};
giving the following error:
a.c:6:13: error: field has incomplete type 'struct node'
struct node next;
^
a.c:4:8: note: definition of 'struct node' is not complete until the closing '}'
struct node {
^
1 error generated.
If the definition of node struct is not done before '}' is used, then how come can we set the pointer to an undefined user-defined data type node?
| Because next is a pointer to node, the type does not need to be complete in order for compilation to succeed.
Consider also a simple example in C++. The type of A does not need to be complete in order to have a pointer to it in struct B. Be prepared to see this pattern used to resolve circular dependencies.
struct A;
struct B {
A *c;
};
struct A {
B *d;
};
Please note that C and C++ are two distinct programming languages, and while specific chunks of C code may be valid C++, it is not guaranteed that it will be, or even that if it is, that it will behave with exactly the same semantics.
|
70,996,358 | 70,996,495 | Error: GCC parenthesized initializer in array new | In template class constructor,initialize a array by T *p = new T[10](userInputData)
But the G++ parenthesized initializer in array new, how to deal with it?
| The problem is that
although we can use empty parentheses to value initialize the elements of an array, we cannot supply an element initializer inside the parentheses.
This means,
int *pia2 = new int[10](); //VALID, block of 10 ints value initialized to 0
int *pia3 = new int[10](55); //NOT VALID
For the same reason you're getting the mentioned error. In particular, you've supplied the initializer userInputData.
To solve this error you have to remove the initializer userInputData. Also you can use std::fill_n as shown below.
T *p = new T[10];
std::fill_n(p, 10, userInputData);
|
70,996,748 | 70,999,739 | Warning haswell support is incomplete | Pretty much the title, when I call (through the hpp header) instance.enumeratePhysical devices()
I am getting the warning:
MESA-INTEL: warning: Haswell Vulkan support is incomplete
Thing is, that's not a validation layer error (my error message would append a lot of info not present here), it's not one of my print statements, and I have not even picked the device yet, once I have picked one it's my nvidia 1070.
Why is this message showing?
|
Why is this message showing?
Because the "anvil" ICD (the Intel Vulkan driver from the mesa project) is present on your system and detected an Intel iGPU from the Haswell generation. This is basically what the physical device enumeration is about: checking all the installed ICDs and finding all the devices on your machine they can work with. In this particular case, there is just a log message in the ICD source code itself. There's nothing to worry about.
|
70,996,920 | 70,997,031 | Why destructor is called if the return operation is elided? | I have the following code that mimics an elision testcase
class Obj
{
public:
int x = 0;
Obj(int y) : x(y) {std::cout << "C\n"; }
~Obj() { std::cout << "D\n"; }
};
auto factory()
{
std::vector<Obj> vec {1,2,3};
std::cout<< &vec[0] << std::endl;
return vec;
}
int main()
{
auto vec = factory();
std::cout<< &vec[0] << std::endl;
for(auto& v : vec)
std::cout << v.x << std::endl;
}
The output is unexpected, tho
C C C D D D
0x5640f1d43e80
0x5640f1d43e80
1 2 3
D D D
Why Obj destructor is called if there's elision active ?
I see that the memory space of the first item is the same ( and constructor is not called )
So I would imagine that no memory has been copied. But if that's so, why (again) item destructors are called in the first place ?
| With the initializer list construction:
std::vector<Obj> vec {1,2,3};
First the initializer_list is constructed, with all 3 Obj objects. Only then is the constructor of std::vector invoked, coping the three objects. What you see as 3 destructor calls is actually the destruction of the initializer_list, not the vector object (which is in fact elided in this case).
|
70,997,011 | 70,997,141 | Overloading ostream << operator for a class with private key member | I am trying to overload the ostream << operator for class List
class Node
{
public:
int data;
Node *next;
};
class List
{
private:
Node *head;
public:
List() : head(NULL) {}
void insert(int d, int index){ ... }
...}
To my humble knowledge (overload ostream functions) must be written outside the class. So, I have done this:
ostream &operator<<(ostream &out, List L)
{
Node *currNode = L.head;
while (currNode != NULL)
{
out << currNode->data << " ";
currNode = currNode->next;
}
return out;
}
But of course, this doesn't work because the member Node head is private.
What are the methods that can be done in this case other than turning Node *head to public?
| You can solve this by adding a friend declaration for the overloaded operator<< inside class' definition as shown below:
class List
{
//add friend declaration
friend std::ostream& operator<<(std::ostream &out, List L);
//other member here
};
|
70,997,021 | 70,997,233 | How would you word this function differently? | My calculations are incorrect in the sense that my program thinks, for example, that 2022 is a leap year and 2024 is not. How do I fix this, please?? I've tried changing the bool statement but nothing seems to work.
#include <iostream>
int leapYear(int year)
{
return (((year % 400) == 0) || ((year % 4 == 0)&& !(year % 100 == 0)));
}
// extracted
}
| Try like this in the leap Year function
return (((year % 400) == 0) || ((year % 4 == 0)&& !(year % 100 == 0)));
|
70,997,431 | 72,242,742 | How to check c++ pointer pointing to invalid memory address? | Is there anyone show me how to check my pointer is pointing to an invalid memory address.
#include<iostream>
class Node{
public:
int data;
Node * next , * prev;
};
// Driver Code
int main () {
Node * node = new Node{ 3 , nullptr , nullptr };
Node * ptr = node;
delete node;
// here node gets deleted from memory and ptr pointing to invalid memory address
if(ptr == nullptr)
std::cout << "ptr is null \n";
else std::cout << "ptr is not null !\n";
return 0;
}
// OUTPUT : ptr is not null !
Here I have very simple code In which ' node ' is allocating memory in heap and pointer ' ptr '
points to the node after this I delete ' node ' and ' ptr ' is still pointing to 'node'. so the question is how I can check ' ptr ' is pointing to an invalid memory address.
| I end up with this solution It may help someone who runs into the same problem
#include<iostream>
class Node{
public:
int data;
Node * next , * prev;
};
template<class T>
void DeletePtr (T*** ptr) {
T** auxiliary = &(**ptr);
delete *auxiliary;
**ptr = nullptr;
*ptr = nullptr;
}
// Driver Code
int main () {
Node * node = new Node{ 3 , nullptr , nullptr };
Node ** ptr = &node;
DeletePtr(&ptr);
if(ptr == nullptr && node == nullptr)
std::cout << "ptr is null \n";
else std::cout << "ptr is not null !\n";
return 0;
}
|
70,997,693 | 71,037,709 | Why does Valgrind return executable file's exit code? | I want to run Valgrind in cp Linux command and watch the XML result of Valgrind.
when I run the below command to get XML output, the exit code is 1. because Valgrind runs the cp command.
valgrind --xml=yes --leak-check=full --verbose --track-origins=no --xml-file=/home/user/Desktop/test/cp_valgrind.xml --log-file=/home/user/Desktop/test/cp_valgrind.txt --error-exitcode=100 /home/user/Desktop/test/cp
I got the below error:
/home/user/Desktop/test/cp: missing file operand
Try '/home/user/Desktop/test/cp --help' for more information.
Why does Valgrind return the executable file's exit code?
How can I run Valgrind on an executable file without Valgrind runs it?
| Valgrind will return the guest return value by default.
If you specify --error-exitcode then it will return that value if there is an error from the view of the Valgrind tool and the guest returns 0. It will still return the guest return value of the Valgrind tool detects no errors. It does not translate a guest error code into the value specified by --error-exitcode, or override a non-zero guest error code.
In the table below invalid_free is a small testcase that generates a single memcheck error but returns 0.
No mem error, no guest error
No mem error, guest error
Mem error, no guest error
Standalone
pwd ; echo $? -> 0
cp ; echo $? -> 1
invalid_free ; echo $? -> 0
Under memcheck
valgrind -q pwd ; echo $? -> 0
valgrind -q cp ; echo $? -> 1
valgrind -q invalid_free ; echo $? -> 0
Under memcheck with --error-code
valgrind -q --error-exitcode=42 pwd ; echo $? -> 0
valgrind -q --error-exitcode=42 cp ; echo $? -> 1
valgrind -q --error-exitcode=42 invalid_free ; echo $? -> 42
and a 4th column that I can't fit without scrolling
Mem error, guest error
Standalone
invalid_free2 ; echo $? -> 1
Under memcheck
valgrind -q invalid_free2 ; echo $? -> 1
Under memcheck with --error-code
valgrind -q --error-exitcode=42 invalid_free2 ; echo $? -> 1
|
70,997,820 | 70,998,607 | Bison shift/reduce conflict in "else" | Consider the following grammar:
%start stmt;
%right "else";
stmt: "foo"
| "if" "(" exp ")" stmt
| "if" "(" exp ")" stmt "else" stmt
exp: "foo2"
On running bison (with producing counter examples) I get:
parser.yy: warning: 1 shift/reduce conflict [-Wconflicts-sr]
parser.yy: warning: shift/reduce conflict on token "else" [-Wcounterexamples]
Example: "if" "(" exp ")" "if" "(" exp ")" stmt • "else" stmt
Shift derivation
stmt
↳ 2: "if" "(" exp ")" stmt
↳ 3: "if" "(" exp ")" stmt • "else" stmt
Reduce derivation
stmt
↳ 3: "if" "(" exp ")" stmt "else" stmt
↳ 2: "if" "(" exp ")" stmt •
This is somehow the shift/reduce represented in bison's manual here. But I don't have "then" after this grammar. The manual says that this problems can be solved defining left and right associativity and precedence. At above I've defined right associativity for "else" but it has no effect on this shift reduce problem.
I don't want to suppress the warning by shift/reduce counts since it is too dangerous because my grammar is too big.
What can I do ?
| In your counterexample, you can see that bison does not know if it should shift or reduce the "if" "(" exp ")" that is the stmt after your first ")".
In other words, if it should group your first if with the else:
if(exp) (if(exp) stmt) else stmt
or the second if with the else:
if(exp) (if(exp) stmt else stmt)
To solve this you could for example also give a precedence for the last terminal symbol of your if, e.g. %right "else" ")".
Alternatively, you could also modify your grammar to have a statement-terminator symbol, e.g.:
stmt: "foo"
| "if" "(" exp ")" stmt ";"
| "if" "(" exp ")" stmt "else" stmt ";"
|
70,998,237 | 71,000,047 | Redefinition error when defining friend function inside class template | I am learning friend declarations in C++ using the books listed here. So after reading, to test my understanding of the concept, i wrote the following program whose output i am unable to understand:
template<typename T>
struct Name
{
friend void anotherFeed(int x)//anotherFeed is implicitly inline and its definition is generate only when we use this nonmember function so why are we getting error at instiantiation?
{
}
};
int main()
{
Name<int> s;
Name<double> p;//error here. My question is that this is instiantiation of the class template Name<double> and not a call to anotherFeed so why do we get error here?
}
The above program give the following error:
error: redefinition of ‘void anotherFeed(int)’
This is my current understanding:
The friend non-member function anotherFeed(int) is implicitly inline.
Even if anotherFeed(int) is inline, we cannot define the same function(doesn't matter inline or not) in the same translation unit.
The definition of anotherFeed(int) is generated only when we use/call this function just like for a nontemplate member function of a class template.
My question is that: Assuming that my understanding(the above 3 points) are correct, since i have not called/used anotherFeed so its definition should not be generated and we should not get the redefinition error at the time of creating an instance of the class template. Only when we call anotherFeed using those instances, we should get the redefinition error. So why do we get error at the time of creating class template's instance. Is there anything wrong in any of the above 3 points.
Summary
I read that the definitions for these functions(non template member functions and friend non template functions) are instantiated only when used. That is,
Name<int> s;
Name<double> p; //this should work in principle because this does not instantiate the definition of anotherFeed(int)
But this doesn't happen. Why/How?
| This issue is addressed here.
However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition.
So even though there is no actual instantiation of the definition of anotherFeed(int) in your program, the compiler is still required to diagnose multiple definitions within the same translation unit as if the definition had been instantiated every time the declaration were instantiated.
And so when you wrote:
Name<double> p; //instantiate a declaration of anotherFeed(int) for the second time.
The above statement, instantiate a redeclaration of anotherFeed(int) and since this declaration corresponds to a definition, according to the quoted statement at the beginning of my answer you get the redefinition error.
|
70,999,195 | 70,999,245 | I have used enum in my code and it is crashing | I am using enum in the below code and using operator overloading but it is crashing. Could anyone explain why?
#include<iostream>
using namespace std;
enum E{M, T= 3, W, Th, F, Sa, Su};
E operator+(const E &a, const E &b){
unsigned int ea = a, eb = b;
unsigned int ec = (a+b)%7;
return E(ec);
}
int main(){
E a = M, b = F;
cout<<a<<endl;
cout<<b<<endl;
E day = a+b;
//cout<<int(day)<<endl;
return 0;
}
| E operator+(const E &a, const E &b){
This defines the + operator for two objects who are instances of class E.
unsigned int ec = (a+b)%7;
Both a and b are instances of class E, therefore the + operation will be done by calling your operator+ overload.
Except that this is your operator+ overload in the first place. So, this will end up calling the operator+ again, in perpetuity, resulting in infinite recursion and a crash.
That's the reason why the shown code is crashing.
|
70,999,852 | 71,000,070 | Error When Passing String array to function in C++ | Hi guys I've some errors when passing some strings of array in C++, do you know what's wrong with this code guys?, Thankyou
#include <iostream>
#include <string>
void showData(string data[]);
int main()
{
string namaMahasiswa[] = {"Nico", "Yonathan", "Andre", "Ratu"};
enum option{ SHOW = 5 };
switch (5)
{
case SHOW:
showData(namaMahasiswa);
break;
}
}
void showData(string data[])
{
for (int z = 0; z < sizeof(data) / sizeof(*data); z++)
{
cout << data[z] << endl;
}
}
This is the error :
'int main()':
index.cpp:61:18: error: could not convert '(std::string*)(& namaMahasiswa)' from 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} to 'std::string' {aka 'std::__cxx11::basic_string<char>'}
61 | showData(namaMahasiswa);
| ^~~~~~~~~~~~~
| |
| std::string* {aka std::__cxx11::basic_string<char>*}
In function 'void showData(std::string*)':
index.cpp:83:36: warning: 'sizeof' on array function parameter 'data' will return size of 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} [-Wsizeof-array-argument]
83 | for (int z = 0; z < sizeof(data) / sizeof(*data); z++)
index.cpp:80:22: note: declared here
80 | void showData(string data[])
So it means we can't pass string array to a function like that or maybe I've to use some char?
| As an alternative to the answer provided by @ACB, you can use a std::array.
#include <array>
#include <string>
#include <iostream>
template <std::size_t S>
void foo(std::array<std::string, S> &bar) {
for (auto &i : bar) {
std::cout << i << std::endl;
}
}
int main() {
std::array<std::string, 3> baz = {"hello", "world", "wooble"};
foo(baz);
return 0;
}
We could even use the template to allow for std::arrays of other types. As long as there is an applicable << overload with std::ostream and T.
#include <array>
#include <string>
#include <iostream>
template <typename T, std::size_t S>
void foo(std::array<T, S> &bar) {
for (auto &i : bar) {
std::cout << i << std::endl;
}
}
int main() {
std::array<std::string, 3> baz = {"hello", "world", "wooble"};
foo(baz);
return 0;
}
|
71,000,168 | 71,001,240 | Use a compiled dart executable as DynamicLibrary in Flutter | Since a longer time now it is possible to open a DynamicLibrary (dylib, dll, so) in Flutter. Those libraries are written in C or C++.
I've now tried to build a basic dart command line application, compiled it using dart compile exe and tried to load it in my Flutter application using DynamicLibrary.open(), as you would do with the native libraries in C/C++.
typedef HelloWorldFunc = Void Function();
typedef HelloWorld = void Function();
...
final dynLib = DynamicLibrary.open('/path/to/cli.exe');
final HelloWorld func = dynLib.lookup<NativeFunction<HelloWorldFunc>>('hello_world').asFunction();
func();
(I've followed this tutorial and just added an empty void function called hello_world
https://dart.dev/tutorials/server/get-started#3-create-a-small-app)
But the symbol could not be found:
Failed to lookup symbol 'hello_world': dlsym(0x7fec2310e5a0, hello_world): symbol not found
Question
Is it generally possible to open dart-compiled libraries in Flutter, like DLLs written in C++? Since dart compile exe generates native machine code as well
If yes, how?
Thanks!
| Dart cannot create shared libraries like other languages can do because it needs to be run in an embedder/DartVM.
This issue has a good explanation:
https://github.com/dart-lang/sdk/issues/37480
|
71,000,795 | 71,000,893 | Why can't I wrap a template parameter with parentheses? | to avoid XY, I will start by explaining my overall goal.
I'm trying to make a choice between two different generic containers at compile-time. The solutions I came up with is very straightforward using macros. For the sake of demonstaration here is how it would look with std::vector and std::set (in practice they're other containers but it's irrelevant to the issue)
// switch between the container types
//#define CONT_SET
#ifdef CONT_SET
#define CONTAINER(type) std::set<type>
#else
#define CONTAINER(type) std::vector<type>
#endif
int main() {
CONTAINER(float) cont;
}
this works perfectly fine.
The problem arises when I try to store more complicated types in the container, for example
CONTAINER(std::pair<int, int>) cont;
this will not work, because the compiler detects this as two different macro parameters std::pair<int and int>.
I tried overcoming this issue by adding parantheses that group the entire type together
CONTAINER((std::pair<int, int>)) cont;
but then I get a 'template argument 1 is invalid' (godbolt)
is there a way to tell the compiler that the entire expression is just one macro parameter? or that the parenthesized template parameter is a valid type?
| Premised that I think that C/C++ macros are distilled evil (and that seems to me that you can substitute Container() using using) you can pass throug a type alias
using pair_i_i = std::pair<int, int>;
CONTAINER(pair_i_i) cont;
|
71,001,083 | 71,003,005 | Use existing Static library in C++ WinRT UWP app | I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that?
I have read the documentation. But it has me confused.
Documentation talk about "Using a native C++ static library in a UWP App" what is a native c++ library?.
Also, I do not have the source code for this library.
| The primary limitation for UWP is that the library:
(a) Must use the subset of Win32 imports that are supported for use in WINAPI_PARTITION_APP
(b) It needs to have been built with VS 2015 Update 3 or later in order to be 'binary compatible' with modern Visual C++ tooling used for UWP.
(c) Some APIs that are used by the static library may not be supported in the "AppContainer" security context (i.e. they may fail in ways the code doesn't handle gracefully).
You should also use /NODEFAULTLIB:kernel32.lib to avoid having your static library force the import of non-supported APIs. The "WindowsApp.lib" umbrella library provides everything that's supported.
More than likely, you'll need the static library built with some modification to actually link successfully and eventually pass WACK.
|
71,001,327 | 71,001,382 | argument of type "const char *" is incompatible with parameter of type "char *" & expression must be a modifiable lvalue | #include <iostream>
class House {
private:
char name[20];
char date[10];
float width;
float height;
float age;
public:
void set(char n[20], char d[10], float w, float h, float a) {
name = n;
date = d;
width = w;
height = h;
age = a;
}
void get() {
std::cout << name << ", " << age << " (" << width << "x" << height <<
")" << ", age = " << age << std::endl;
}
};
int main() {
House shop;
shop.set("Shop", "2000.10.10", 200.5, 100.4, 10.0);
return 0;
}
The picture shows my errors in debugging:
I know that I can use std::string, but in this program I want to use char string[n]
How to fix my mistakes?
| The short answer is to use std::string instead. It's easier and safer.
But if you must use arrays, keep in mind that you cannot assign an array to another like that. What you must instead do is copy elements from one array to another. Since you're dealing with char arrays, the obvious solution is to use strcpy:
#include <cstring>
void set(const char n[20], const char d[10], float w, float h, float a) {
strcpy(name, n);
strcpy(date, d);
width = w;
height = h;
age = a;
}
Notice how I made the char array arguments const: that's because array arguments to functions are really actually pointers in disguise, and you can't legally assign a literal to a non const pointer (at least not without enabling some kind of compiler specific option to allow dangerous deprecated conversions).
This, however, is potentially dangerous: it assumes that the input array is null terminated, and also that there are not more characters in the source that can fit in the destination. That includes the null terminator, which C++ will helpfully put at the end of any char array literal: so, a string like "2000.10.10" actually needs 11 characters, because of the hidden \0 at the end, and missing that \0 will cause a lot of trouble down the line because every C string function assumes it is there (and if it isn't, you're in undefined behaviour territory).
For all those reasons, using char arrays is a minefield, so please use std::string.
|
71,001,409 | 71,001,507 | Can I create a set of list::iterators? Will they still point to the same node after I erase/insert other nodes from the same list? | I want to create a set of list::iterators, so that when I update other nodes in the list, my iterator still points to the same node.
int n;
string s;
cin >> n >> s;
list<char> str;
for (char c : s) {
str.push_back(c);
}
vector<set<list<char>::iterator>> locations(10);
for (auto it = str.begin(); it != str.end(); ++it) {
auto next = it;
++next;
if (next != str.end()) {
int l = *it - '0', r = *next - '0';
if ((l + 1) % 10 == r) {
locations[l].insert(it);
}
}
}
I get a compile error saying
error: no match for ‘operator<’ (operand types are ‘const std::_List_iterator’ and ‘const std::_List_iterator’)
386 | { return __x < __y; }
What am I doing wrong? Is this possible in C++? Or should I create my own node structure and store pointers to it?
PS - I am trying to solve a problem from Google Kickstart (https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435914/00000000008d94f5) and the string s contains only digits from 0-9.
| You'd need a custom comparator. E.g. something like this:
struct CompareIterators {
template <typename It>
bool operator()(It iter1, It iter2) const {
using Ptr = decltype(&*iter1);
return std::less<Ptr>{}(&*iter1, &*iter2);
}
};
using MySet = set<list<char>::iterator, CompareIterators>;
vector<MySet> locations(10);
The order of elements in MySet will be essentially random, unpredictable. It won't necessarily correspond to the order of nodes in the list. All it ensures is that, if you insert an iterator to the same element twice, it will only appear in the set once.
|
71,001,458 | 71,019,939 | Constructing register map using templated class | I'm working on modelling some hardware in SystemC (although that's not relevant to the question). The goal is to be able to declare a bunch of registers in a block (class) which are used directly in the class implementation. The external software/firmware will access the registers through a register map to decode based on address. So the HW block as part of its constructor will initialize the register map (not shown below). The issue arises from the fact that some registers need to trigger an action. To do this is seems appropriate to have method in the HW class that is called if the register is written.
The simplified class hierarchy is as follows
class regBase {
public:
regBase(uint64_t _address, std::string _name) :
m_address(_address),
m_name(_name) { }
regBase() {};
void setAddress(uint64_t _address) { m_address = _address;}
virtual void write(uint32_t newval) = 0; //virtual methods to be overridden in template
virtual uint32_t read(void) = 0;
virtual int size(void) = 0;
private:
uint64_t m_address;
std::string m_name;
};
template <class REG>
class hwRegister : public regBase
{
public:
uint32_t read(void) override
{
return m_val.value();
}
void write(uint32_t newval) override
{
m_val.setValue(newval);
}
int size(void) override
{
return (m_val.size());
}
private:
REG m_val;
};
typedef std::function<void(uint64_t, uint32_t)> writeCallback_t;
struct reg_entry {
reg_entry(int _size, regBase *_reg) :
m_reg(_reg), m_size(_size) {}
reg_entry() {}
regBase *m_reg;
int m_size;
writeCallback_t m_callback;
};
typedef boost::ptr_map<int, std::shared_ptr<reg_entry> > reg_map_t;
class RegMap {
public:
void write(uint64_t address, uint32_t val) {
auto it = m_register_map.find(address);
if (it==m_register_map.end())
{
BOOST_ASSERT_MSG(false, "Invalid address");
}
auto entry = *it->second;
entry->m_reg->write(val);
if (entry->m_callback)
entry->m_callback(address, val);
};
void setCallback(uint64_t address, writeCallback_t newcallback)
{
auto it = m_register_map.find(address);
if (it==m_register_map.end())
{
BOOST_ASSERT_MSG(false, "Invalid address");
}
(*it->second)->m_callback = newcallback;
};
void addReg(uint64_t address, regBase *reg) {
auto entry = std::make_shared<reg_entry>(reg->size(), reg);
entry->m_callback = nullptr;
entry->m_reg = reg;
m_register_map[address] = entry;
}
private:
reg_map_t m_register_map;
};
I want to in the implementation of HW block, add myReg to myMap and be able to add a callback if necessary for a given register. The issue is around the callback. Does the declaration of the callback look right? Do I need to use std::bind and placeholders?
Ok, updated with compiling code.
| [this](uint64_t address, uint32_t val) { myCallback(address, val); } worked
struct my_reg_st {
uint64_t data;
uint64_t size(void) { return 8; };
void setValue(uint32_t val) { data = val; };
uint64_t value(void) {return data; };
};
class test {
public:
test() {
myMap.addReg(0, &myReg);
// use lambda function for callback. Note that use of intermediate f is only for readability
writeCallback_t f = [this](uint64_t address, uint32_t val) { myRegCallback(address, val); };
myMap.setCallback(0, f);
}
void myRegCallback(uint64_t address, uint32_t value);
void write(uint64_t address, uint32_t val) { myMap.write(address, val); };
private:
hwRegister<my_reg_st> myReg;
RegMap myMap;
};
|
71,001,735 | 71,002,826 | How do I build a parameterized third-party library in cmake? | I have a project in which I have a third party library checked out as a git submodule. The third party library is just source code with no build system. In addition, The third party library must configured on a per-executable basis by way of compiler definitions and selectively compiling only the parts of the library that I need. I use this library in a lot of different repositories, so I want to make a reusable component to generate an instantiation of the library for any particular executable.
The way I've currently attempted this is by creating a generate_thirdparty.cmake. This file looks something like this:
function(generate_thirdparty parameters)
# several calls to add_library for the different components of this third party library
# the generated libraries depend on the parameters argument
# the parameters configure compile definitions and which source files are compiled
endfunction()
Then in my project CMakeLists.txt I have something like:
cmake_minimum_required(VERSION 3.8)
project(test C)
include(generate_thirdparty.cmake)
set(parameters <some parameters here>)
generate_thirdparty(${parameters})
add_executable(my_exe main.c)
target_link_libraries(my_exe <library names from generate_thirdparty>)
It seems like what I have works, but I'm confused on how you're supposed to do this. I've read through other posts and seen people suggest using find_package or ExternalProject_add. Given a third party repository that contains source code and no build system, which you have no control over, how do you create a reusable way to build that library, especially in the case that the library must be parameterized any given executable?
EDIT: I would like to have the flexibility to have multiple instantiations of the library in the same project.
| Let's sum up:
The third-party library does not provide its own build.
You need many instantiations of the library within a single build.
You use these instantiations across multiple different repositories.
I think you're pretty much taking the right approach. Let's call the third-party library libFoo for brevity. Here's what I think you should do...
Create a wrapper repository for libFoo that contains a FindFoo.cmake file and the actual foo repository submodule next to it. This is to avoid the contents of FindFoo.cmake from being independently versioned across your various projects.
Include the wrapper as your submodule in dependent projects, say in the directory third_party/foo_wrapper
In those dependent projects, write:
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/third_party/foo_wrapper")
find_package(Foo REQUIRED)
generate_foo(config1 ...)
generate_foo(config2 ...)
add_executable(app1 src/app1/main.cpp)
target_link_libraries(app1 PRIVATE foo::config1)
add_executable(app2 src/app2/main.cpp)
target_link_libraries(app2 PRIVATE foo::config2)
The contents of FindFoo.cmake will simply be:
cmake_minimum_required(VERSION 3.18)
function(generate_foo target)
# Use CMAKE_CURRENT_FUNCTION_LIST_DIR to reference foo's source files
# for example:
set(sources "src/src1.cpp" "src/src2.cpp" ...)
list(TRANSFORM sources PREPEND "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/foo/")
add_library(${target} ${sources})
add_library(foo::${target} ALIAS ${target})
# Do other things with ARGN
endfunction()
# Define a version for this dependency + script combo.
set(Foo_VERSION 0.1.0)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo VERSION_VAR Foo_VERSION
HANDLE_COMPONENTS)
The CMAKE_CURRENT_FUNCTION_LIST_DIR is the absolute path to the file containing the function being called. Remember that this is the root of your wrapper repository, so the actual sources for libFoo will be in the adjacent foo directory. list(TRANSFORM) lets us write relative paths in the sources list that get converted to absolute paths for the sake of add_library (passing a relative path to add_library would be relative to the caller's source directory).
I also create an ALIAS target so that callers of generate_foo can link to the alias. This is important because CMake considers names that contain :: to be targets when a library is expected. This very helpfully turns typos from unintended linker flags into configure-time "target not found" errors.
Then we define the function like normal and call the find_package_handle_standard_args to handle find_package arguments like REQUIRED, COMPONENTS (even just to check that none were incorrectly specified), and VERSION. See the docs for it, here: https://cmake.org/cmake/help/latest/module/FindPackageHandleStandardArgs.html
|
71,002,059 | 71,002,588 | Do languages like JS with a copying GC ever store anything on the cpu registers? | I am learning about GC's and I know there's a thing called HandleScope which 'protects' your local variables from the GC and updates them if a gc heap copy happens. For example, if I have a routine which adds togother 2 values and I call it, it may invoke the garbage collector which will copy the Object that my value is pointing to (or the GC will not even know that the Object the value is pointing to is referenced). A really minimal example:
#include <vector>
Value addValues(Value a, Value b);
std::vector<Value*> gc_vals_with_protection;
Value func(Value a, Value b)
{
vars.push_back(&a); // set protection for a
gc_vals_with_protection.push_back(&b); // set protection for b
Value res = addValues(a, b); // do calcuations
gc_vals_with_protection.pop_back(); // remove protection for b
gc_vals_with_protection.pop_back(); // remove protection for a
return res;
}
But this has got me thinking, it will mean that a and b will NEVER be on the physical CPU registers because you have taken their addresses (and CPU registers don't have addresses) which will make calcuations on them inefficient. Also, at the beggining of every function, you would have to push back twice to the vector (https://godbolt.org/z/dc6vY1Yc5 for assembly).
I think I may be missing something, as this must be not optimal. Is there any other trick I am missing?
| (V8 developer here.)
Do languages like JS with a copying GC ever store anything on the cpu registers?
Yes, of course. Pretty much anything at all that a CPU does involves its registers.
That said, JavaScript objects are generally allocated on the heap anyway, for at least the following reasons:
(1) They are bigger than a register. So registers typically hold pointers to objects on the heap. It's these pointers, not the objects themselves, that Handles are needed for (both to update them, and to inform the GC that there are references to the object in question, so the object must not be freed).
(2) They tend to be much longer-lived than the typical amount of time you can hold something in a register, which is only a couple of machine instructions: since the set of registers is so small, they are reused for something else all the time (regardless of JavaScript or GC etc), so whatever they held before will either be spilled (usually though not necessarily to the stack), or re-read from wherever it originally came from next time it's needed.
(3) They have "pointer identity": JavaScript code like obj1 === obj2 (for objects, not primitives) only works correctly when there is exactly one location where an object is stored. Trying to store objects in registers would imply copying them around, which would break this.
There is certainly some cost to creating Handles; it's faster than adding something to a std::vector though.
Also, when passing Handles from one function to another, the called function doesn't have to re-register anything: Handles can be passed around without having to create new entries in the HandleScope's backing store.
A very important observation is that JavaScript functions don't need Handles for their locals. When executing JavaScript, V8 carefully keeps track of the contents of the stack (i.e. spilled contents of registers), and can walk and update the stack directly. HandleScopes are only needed for C++ code dealing with JS objects, because this technique isn't possible for C++ stack frames (which are controlled by the C++ compiler). Such C++ code is typically not the most critical performance bottleneck of an app; so while its performance certainly matters, some amount of overhead is acceptable.
(Side note: one can "blindly" (i.e. without knowledge about their contents) scan C++ stack frames and do so-called "conservative" (instead of "precise") garbage collection; this comes with its own pros and cons, in particular it makes a moving GC impossible, so is not directly relevant to your question.)
Taking this one step further: sufficiently "hot" functions will get compiled to optimized machine code; this code is the result of careful analysis and hence can be quite aggressive about keeping values (primarily numbers) in registers as long as possible, for example for chains of calculations before the final result is eventually stored in some property of some object.
For completeness, I'll also mention that sometimes, entire objects can be held in registers: this is when the optimizing compiler successfully performs "escape analysis" and can prove that the object never "escapes" to the outside world. A simple example would be:
function silly(a, b) {
let vector = {x: a, y: b};
return vector.x + vector.y;
}
When this function gets optimized, the compiler can prove that vector never escapes, so it can skip the allocation and keep a and b in registers (or at least as "standalone values", they might still get spilled to the stack if the function is bigger and needs those registers for something else).
|
71,002,088 | 71,020,351 | Export c++ code from simulink scheme with s-function | I have a simulink working simulink schema in which there are some s-function, I want to export this code in c++ and compile it. I already tried to export and compile a simple schema and it works, but when i try to compile the exported code of my project I get a lot of errors like
error: #error Unrecognized use
error: #error Must define one of RT,nNRT, MATLAB_MEX_FILE, SL_INTERNAL, or FIPXT_SHARED_MODULE
error: #error Unhandled case
error: ‘mxArray’ does not name a type mxArray **dlgParams; /* The S-function parameters
error: ‘mxArray’ has not been declared mxArray **)
error: ‘mxArray’ does not name a type mxArray *propVal;
error: ‘RTWSfcnInfo’ does not name a type; did you mean ‘RTWLogInfo’? RTWSfcnInfo sfcnInfo
The main settings that i used are:
Code generation system target file --> grt.tlc
language --> C++
Pack code and artifact --> <name_zip>
Tool chain GNU gcc/g++ | gmake (64-bit Linux)
default parameter behavior --> tuanble
code interface packaging --> nonreusable function
external mode --> chcked
standar math library --> c++ 03(ISO)
single output/update function --> checked
i used a fixed step size solver
Im using Ubuntu 18.
The source is generated succesfully the problem is when i try to compile the code.
Once the code is generate I get a zip folder with all the sources and also some external header file that I include when I make the CMakeLists.txt. I also tryied to compile directly the code with the .mk file but also I get a bounch of errors. The problem is realated with the s-function because I built a simple simulink schema with a source an s-function that implements a dynamical model and an output and when i generate the code and compile it I get the same errors. I also tryied to make a simple schema without s-function and this works. So is there any settings for the s-function to be exportable
| At the end I found an answer that I post here in case someone else has my same problem.
The solution that worked form my is:
First of all once you have the generated zip file with all the sources and headers open it and load on the Matlab workspace the file buldinfo.mat then in the Matlab shell run
packNGo(buildInfo)
in this way you generate a new .zip with all the sources and headers, this .zip differs from the previous because is flat, no nested folder.
Inside this folder there is a file called define.txt with a list of variables, all these variables should be passed as flags to the compiler. For example in my case I use a CMakelists.txt so to set these flags I used
set(CMAKE_CXX_FLAGS "-Wall -Wextra -DMODEL=test_sum_gain -DNUMST=2 -DNCSTATES=2 -DRT -DUSE_RTMODEL -DON_TARGET_WAIT_FOR_START=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=1 -DEXT_MODE=1 -DMAT_FILE=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0")
this depends on the way in which you compile the source, but in any case you should set these variables that is I am not wrong are just a directive for the precompiler.
These two things worked for me.
|
71,002,089 | 71,002,883 | std::cin don't break program when reading incorrect int | I have a program I made that will check your age and gender. I am using visual studio 2022 to see what happens when debugging.
If I put random letters for the age it skips the cin > gender part which is so weird and the locals shows that age is set to 0 but gender is -52'' . What can I do so it still atleast takes your gender, even if you put weird stuff in for age?
#include <iostream>
using namespace std;
int main()
{
// prompt user for age AND gender
//age is int, gender is character
int age;
char gender;
cout << "What is your age? \n" << endl;
cin >> age;
cout << "What is your gender? \n" << endl;
cin >> gender;
if (gender == 'f' || gender == 'F')
{
bool result = (age > 60);
switch (result)
{
case 0:
cout << "You do not qualify for discount need to be over 60";
break;
case 1:
cout << "You qualify for discount";
break;
}
}
else if (gender == 'm' || gender == 'M')
{
cout << "You do not qualify you need to be female and over 60 \n" << endl;
}
else {
cout << "Wrong gender either use male or female Exiting... \n" << endl;
return -1;
exit;
}
return 0;
}
This is a picture of the visual studio locals area
| When you type bad data for the age and the conversion fails, cin enters an error state. When it's in an error state, it refuses to read anything. The simplest fix would be to just clear the stream after the first
cout << "What is your age? \n" << endl;
cin >> age;
cin.clear(); // But now, the bad integer will become the gender
cout << "What is your gender? \n" << endl;
cin >> gender;
Far better would be to check cin after the first read, and do some error handling, perhaps printing a message and setting the age to some known value.
cin >> age;
if(!cin.good()) {
// Handle bad input here
}
Note: after the integer read fails, the non-integer data is still in the input stream. If you just clear, that will be the next thing read.
|
71,002,139 | 71,003,755 | What is the fastest way to calculate the logical_and (&&) between elements of two __m256i variables, looking for any pair of non-zero elements | As far as I know, integers in C++ can be treated like booleans, and we can have a code like this:
int a = 6, b = 10;
if (a && b) do something ---> true as both a and b are non-zero
Now, assume that we have:
__m256i a, b;
I need to apply logical_and (&&) for all 4 long variables in __m256i, and return true if one pair is non-zero. I mean something like:
(a[0] && b[0]) || (a[1] && b[1]) || ...
Do we have a fast code in AVX or AVX2 for this purpose?
I could not find any direct instruction for this purpose, and definitely, using the bitwise and (&) also is not the same. Any help will be greatly appreciated.
| You can cleverly combine a vpcmpeqq with a vptest:
__m256i mask = _mm256_cmpeq_epi64(a, _mm256_set1_epi64x(0));
bool result = ! _mm256_testc_si256(mask, b);
The result is true if and only if (~mask & b) != 0 or
((a[i]==0 ? 0 : -1) & b[i]) != 0 // for some i
// equivalent to
((a[i]==0 ? 0 : b[i])) != 0 // for some i
// equivalent to
a[i]!=0 && b[i]!=0 // for some i
which is equivalent to what you want.
Godbolt-link (play around with a and b): https://godbolt.org/z/aTjx7vMKd
If result is a loop condition, the compiler should of course directly do a jb/jnb instruction instead of setnb.
|
71,002,193 | 71,002,294 | Partial specialization for class method | I'm trying to specialize a method of a (non-templated!) class. Apparently, it's not possible, however I am struggling to figure out why, or how to overcome the problem.
class MyClass {
public:
template <typename... T>
auto MyMethod(T... t) -> void { std::cout << "Original" << std::endl; }
template <typename... T>
auto MyMethod<int, T...>(int value, T... t) -> void { std::cout << "Specialization" << value << std::endl; }
};
int main(void) {
MyClass myClass;
myClass.MyMethod<char, char>('c', 'c');
myClass.MyMethod<int, char>(123, 'c');
return 0;
}
The error is as follows:
test.cpp:10:49: error: non-class, non-variable partial specialization ‘MyMethod<int, T ...>’ is not allowed
10 | auto MyMethod<int, T...>(int value, T... t) -> void { std::cout << "Specialization" << value << std::endl; }
It seems that there would be no reason for this to be impossible (with a template class it makes sense that the entire class has to be specialized too). What am I missing? Is it literally not possible?
| Only classes can be partially specialized; methods can only be fully specialized. As your methods still have template arguments (T) that are not specified, this means a partial method specialization.
If you would use these template arguments for a class (and call a non-templated member function of that class) then this should be possible.
|
71,002,525 | 71,002,583 | Using the "!" operator during file input/output operations in C++ | I'm reviewing a project that does file input/output operations in C++. There are uses for the overloaded ! operator defined in std::ios that I have not encountered before. I know that the ! operator is used to check if a file has been opened. However, I did not understand why the author used the fstream object by using the ! operator after using the istream::seekg, istream::read, ostream::seekp, ostream::write methods in the project I was examining.
Below is a part of the add() function in the source code I've reviewed:
#include <fstream>
#include <iostream>
bool add(std::fstream &file, std::istream &input)
{
file.seekg((id - 1) * sizeof(Person));
/* What is the purpose of using the "operator!" below? */
if(!file){ return false; }
file.read(reinterpret_cast<char *>(&temp), sizeof(Person));
/* What is the purpose of using the "operator!" below? */
if(!file){ return false; }
file.seekp((id - 1) * sizeof(Person));
/* What is the purpose of using the "operator!" below? */
if(!file){ return false; }
file.write(reinterpret_cast<const char*>(&person), sizeof(Person));
/* What is the purpose of using the "operator!" below? */
if(!file){ return false; }
}
Do the above uses of the operator! operator make any sense?
| The ! operator is overloaded for classes derived from std::basic_ios (such as std::fstream) to indicate whether or not an error has occurred following an operation, or that has not been cleared after an earlier operation.
From cppreference:
Returns true if an error has occurred on the associated stream.
Specifically, returns true if badbit or failbit is set in rdstate().
In the code sample you have shown, the ! operator is called after every attempted operation on the stream and, if an error is detected, the function aborts and returns a false signal. (Note that any of those seek/read/write operations could potentially fail.)
So:
Do the above uses of the operator! operator make any sense?
Yes, they do. That's good, exemplary code, which should be commended in any review.
|
71,002,556 | 71,002,585 | Using two time values in while loop. The while loop doesn't stop when condition no longer 1. C++ | My while loop isn't stopping even though one of the values becomes 'greater than' and the condition changes from 1 to 0.
Before the while loops starts I set the time now in milliseconds. milliseconds_now
I also set a time five seconds in the future. milliseconds_then
I have (milliseconds_now < milliseconds_then) in the while loop. It should only be 1 for five seconds. I also print out (milliseconds_now < milliseconds_then) within the loop and it goes from printing '1' to printing '0' after five seconds.
I expect the loop to stop after five seconds. Instead it continues.
This is what I have in the terminal when I run the program at five seconds. It just keeps looping.
1644097691885 1644097692070
1
1644097691935 1644097692070
1
1644097691986 1644097692070
1
1644097692036 1644097692070
1
1644097692086 1644097692070
0
1644097692136 1644097692070
0
1644097692186 1644097692070
0
1644097692236 1644097692070
0
1644097692287 1644097692070
0
1644097692337 1644097692070
0
1644097692387 1644097692070
0
1644097692437 1644097692070
The code.
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();
auto milliseconds_then = milliseconds_now + 5000;
int main() {
while (milliseconds_now < milliseconds_then) {
auto now = high_resolution_clock::now();
auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();
cout << milliseconds_now << " " << milliseconds_then << "\n";
cout << (milliseconds_now < milliseconds_then) << "\n";
usleep(50000);
};
};
| the milliseconds_now inside the loop is not the same milliseconds_now being tested in the while loop. Change it to
while (milliseconds_now < milliseconds_then) {
auto now = high_resolution_clock::now();
milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();
cout << milliseconds_now << " " << milliseconds_then << "\n";
cout << (milliseconds_now < milliseconds_then) << "\n";
usleep(50000);
};
why? you are declaring a new variable inside the loop, often the compiler will warn you about it.
|
71,002,931 | 71,003,042 | Understanding capture by reference in C++ lamdba functions | I thought I understood how capture by reference works in C++ until I faced this situation:
auto inrcrementer = []() {
int counter = 0;
return [&counter]() {
return counter++;
};
};
int main() {
auto inc = inrcrementer();
cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;
return 0;
}
I was expecting this to return 0, 1, 2 but it returns 0, 32765, 32765. Why?
Moreover, if I change it to this:
auto inrcrementer = []() {
int counter = 0;
return [counter]() mutable {
return counter++;
};
};
int main() {
auto inc = inrcrementer();
cout << inc() << ", " << inc() << ", " << inc() << ", " << endl;
return 0;
}
It is fixed and it returns as expected. What is the difference between the two?
| After expanding the outer lambda, your first example can be written as sth like this:
struct incrementer
{
auto operator()()
{
int counter = 0;
return [&counter]() { return counter++;}
}
};
As it's become more visible now counter is a local variable and the inner lambda operates on a reference to local object, a dangling one at the call site.
The second example can be expanded to sth like this:
struct incrementer
{
auto operator()()
{
int counter = 0;
struct inner
{
inner(int cnt) : mcnt{cnt}();
int operator()() { return mcnt++; }
int mcnt;
};
return inner{counter};
}
};
Basically, the lifetime of the counter needs to be preserved for the entire lifetime of the lambda, one way or another.
Yet another way is to store the counter in the outer lambda, e.g.
auto inrcrementer = [counter=0]() mutable {
return [&counter]() {
return counter++;
};
};
This is fine as long as the inner one does not outlive the outer one.
|
71,002,951 | 71,003,103 | Win32 CryptProtectData Method | I was reading this: https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-using-cryptprotectdata
I was wondering about this method. Does this only store it in the process memory while the process is running? If so, is there a persistent data storage that the win32 api provides that's secure and does not create any files on the filesystem? Some sort of keychain/keyvalue store that's secure?
My intention here is to secure a secure login token that can be used for two weeks by a program I am writing for the user to login. I don't think this data should be stored in a file that is accessible by anyone. If someone were to find out about the file, they could steal the file and login with someone else's account as long as the token is valid. Environment variables and the windows registry are also not acceptable solutions. This needs to be inaccessible by the user.
| There's nothing wrong with storing your login token in a file (or in the registry, which I personally would prefer) provided that you encrypt it properly. The documentation for CryptProtectData has this to say:
Typically, only a user with the same logon credential as the user who encrypted the data can decrypt the data. In addition, the encryption and decryption usually must be done on the same computer.
So you're already halfway there. Only the user (and machine) that 'own' the token can decrypt it.
In addition to that, there is this parameter:
[in, optional] pOptionalEntropy
A pointer to a DATA_BLOB structure that contains a password or other additional entropy used to encrypt the data. The [same] DATA_BLOB structure used in the encryption phase must also be used in the decryption phase
So this should be something known only to your program (a GUID would be the obvious choice). Then, only that program can decrypt - and hence use - the token.
You might take some steps in your code to obfuscate this, such as storing it in some mangled form and only demangling it just before you use it. Then call SecureZeroMemory when you're done with it to make life harder for potential snoopers.
|
71,003,073 | 71,003,110 | C++ doesn't give me an output | I'm trying to loop through a 2d array and find the sum of some numbers but for some reason, I don't get any output from the compilier.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int arr[3][3] = { {2,5,7},
{3,6,8},
{5,8,6} };
int oddSum = 0;
int evenSum = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
while (arr[i][j] != 2 && arr[i][j] % 2 == 0)
{
evenSum += arr[i][j];
}
while (arr[i][j] != 3 && arr[i][j] % 3 == 0)
{
oddSum += arr[i][j];
}
}
}
cout << "oddSum = " << oddSum << endl;
cout << "evenSum = " << evenSum << endl;
return 0;
}
| As arr[i][j] is not updated within your while loops, if that condition is true, it will never be false and the loop will never exit.
|
71,003,471 | 71,003,509 | Template partial specialization issues "template parameters not deducible in partial specialization" | I am trying to understand why there is a "template parameters not deducible in partial specialization". I could not find an answer to this with current answers.
Pre:
template<std::size_t, class T, class F>
struct IF {
using type = T;
};
template<class T, class F>
struct IF<0, T, F>
{
using type = F;
};
Actual Issue:
template <std::size_t x, std::size_t y, std::size_t z = x*y >
struct Selector
{
using A = int; //simplified for questioning- uses x,y
using B = float;
using type = typename IF<z, A, B>::type;
};
template <std::size_t x, std::size_t y>
using MyType = typename Selector<x, y>::type;
//Everything is good until here.
template <typename T>
struct XTyp;
// struct XTyp : std::integral_constant<std::size_t, 0> {};
template <std::size_t x, std::size_t y>
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
{
};
error: template parameters not deducible in partial specialization:
struct XTyp<MyType<x, y> > : std::integral_constant<std::size_t, x>
note: ‘x’
note: ‘y’
See: https://godbolt.org/z/673f9WM3G
| Inserting the type alias, your partial specialization reads
template <std::size_t x, std::size_t y>
struct XTyp< typename Selector<x, y>::type > : std::integral_constant<std::size_t, x>
{
};
When the compiler needs to check whether this partial specialization should be chosen for a given specialization XTyp<Arg>, it has to check whether there are values x and y, such that Arg is the same as Selector<x, y>::type. But that is generally impossible, since each specialization of Selector<x, y> could have any type, including Arg, as type.
In terms of the language specification, everything left of a :: is a non-deduced context in which template argument deduction cannot deduce template arguments.
But the x and y template arguments of the partial specialization must be deducible from Arg as if XTyp<Arg> was given as argument in a call to a function template with function parameter XTyp< typename Selector<x, y>::type >.
Since the template arguments of the partial specialization are never deducible, the compiler will reject the specialization outright.
|
71,003,780 | 71,004,000 | Standard compliant host to network endianess conversion | I am amazed at how many topics on StackOverflow deal with finding out the endianess of the system and converting endianess. I am even more amazed that there are hundreds of different answers to these two questions. All proposed solutions that I have seen so far are based on undefined behaviour, non-standard compiler extensions or OS-specific header files. In my opinion, this question is only a duplicate if an existing answer gives a standard-compliant, efficient (e.g., use x86-bswap), compile time-enabled solution.
Surely there must be a standard-compliant solution available that I am unable to find in the huge mess of old "hacky" ones. It is also somewhat strange that the standard library does not include such a function. Perhaps the attitude towards such issues is changing, since C++20 introduced a way to detect endianess into the standard (via std::endian), and C++23 will probably include std::byteswap, which flips endianess.
In any case, my questions are these:
Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?
I argue below that it's possible in C++20. Is my code correct and can it be improved?
Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)
I think I can give a C++23 solution that is OS-independent, efficient (no system call, uses x86-bswap) and portable to little-endian and big-endian systems (but not portable to mixed-endian systems):
// requires C++23. see https://gcc.godbolt.org/z/6or1sEvKn
#include <type_traits>
#include <utility>
#include <bit>
constexpr inline auto host_to_net(std::integral auto i) {
static_assert(std::endian::native == std::endian::big || std::endian::native == std::endian::little);
if constexpr (std::endian::native == std::endian::big) {
return i;
} else {
return std::byteswap(i);
}
}
Since std::endian is available in C++20, one can give a C++20 solution for host_to_net by implementing byteswap manually. A solution is described here, quote:
// requires C++17
#include <climits>
#include <cstdint>
#include <type_traits>
template<class T, std::size_t... N>
constexpr T bswap_impl(T i, std::index_sequence<N...>) {
return ((((i >> (N * CHAR_BIT)) & (T)(unsigned char)(-1)) <<
((sizeof(T) - 1 - N) * CHAR_BIT)) | ...);
}; // ^~~~~ fold expression
template<class T, class U = typename std::make_unsigned<T>::type>
constexpr U bswap(T i) {
return bswap_impl<U>(i, std::make_index_sequence<sizeof(T)>{});
}
The linked answer also provides a C++11 byteswap, but that one seems to be less efficient (not compiled to x86-bswap). I think there should be an efficient C++11 way of doing this, too (using either less template-nonsense or even more) but I don't care about older C++ and didn't really try.
Assuming I am correct, the remaining question is: can one can determine system endianess before C++20 at compile time in a standard-compliant and compiler-agnostic way? None of the answers here seem to do achieve this. They use reinterpret_cast (not compile time), OS-headers, union aliasing (which I believe is UB in C++), etc. Also, for some reason, they try to do it "at runtime" although a compiled executable will always run under the same endianess.)
One could do it outside of constexpr context and hope it's optimized away. On the other hand, one could use system-defined preprocessor definitions and account for all platforms, as seems to be the approach taken by Boost. Or maybe (although I would guess the other way is better?) use macros and pick platform-specific htnl-style functions from networking libraries(done, e.g., here (GitHub))?
|
compile time-enabled solution.
Consider whether this is useful requirement in the first place. The program isn't going to be communicating with another system at compile time. What is the case where you would need to use the serialised integer in a compile time constant context?
Starting at what C++ standard is there a portable standard-compliant way of performing host to network byte order conversion?
It's possible to write such function in standard C++ since C++98. That said, later standards bring tasty template goodies that make this nicer.
There isn't such function in the standard library as of the latest standard.
Should such a pure-c++ solution be preferred to OS specific functions such as, e.g., POSIX-htonl? (I think yes)
Advantage of POSIX is that it's less important to write tests to make sure that it works correctly.
Advantage of pure C++ function is that you don't need platform specific alternatives to those that don't conform to POSIX.
Also, the POSIX htonX are only for 16 bit and 32 bit integers. You could instead use htobeXX functions instead that are in some *BSD and in Linux (glibc).
Here is what I have been using since C+17. Some notes beforehand:
Since endianness conversion is always1 for purposes of serialisation, I write the result directly into a buffer. When converting to host endianness, I read from a buffer.
I don't use CHAR_BIT because network doesn't know my byte size anyway. Network byte is an octet, and if your CPU is different, then these functions won't work. Correct handling of non-octet byte is possible but unnecessary work unless you need to support network communication on such system. Adding an assert might be a good idea.
I prefer to call it big endian rather than "network" endian. There's a chance that a reader isn't aware of the convention that de-facto endianness of network is big.
Instead of checking "if native endianness is X, do Y else do Z", I prefer to write a function that works with all native endianness. This can be done with bit shifts.
Yeah, it's constexpr. Not because it needs to be, but just because it can be. I haven't been able to produce an example where dropping constexpr would produce worse code.
// helper to promote an integer type
template <class T>
using promote_t = std::decay_t<decltype(+std::declval<T>())>;
template <class T, std::size_t... I>
constexpr void
host_to_big_impl(
unsigned char* buf,
T t,
[[maybe_unused]] std::index_sequence<I...>) noexcept
{
using U = std::make_unsigned_t<promote_t<T>>;
constexpr U lastI = sizeof(T) - 1u;
constexpr U bits = 8u;
U u = t;
( (buf[I] = u >> ((lastI - I) * bits)), ... );
}
template <class T, std::size_t... I>
constexpr void
host_to_big(unsigned char* buf, T t) noexcept
{
using Indices = std::make_index_sequence<sizeof(T)>;
return host_to_big_impl<T>(buf, t, Indices{});
}
1 In all use cases I've encountered. Conversions from integer to integer can be implemented by delegating these if you have such case, although they cannot be constexpr due to need for reinterpret_cast.
|
71,003,820 | 71,004,006 | Unable to receive integer return value when calling Python function from C++ | I am calling a Python function from my C++ code. The Python function takes two numbers as input and returns the sum. I am unable to retrieve the sum value in C++ code. Below are code for both C++ and Python files.
C++ code:
#include<iostream>
#include "Python.h"
int main()
{
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.insert(0, '/home/aakash/Desktop/code/testpc')");
//Run a python function
PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
pName = PyUnicode_FromString((char*)"sample");
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule, (char*)"main2");
// pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg"));
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, PyLong_FromLong(5));
PyTuple_SetItem(pArgs, 1, PyLong_FromLong(6));
pValue = PyObject_CallObject(pFunc, pArgs);
auto result = _PyUnicode_AsString(pValue);
std::cout << result << std::endl;
Py_Finalize();
return 0;
}
Python code in sample.py file:
def main2(a, b):
print("getting sum ")
c = a + b
return c
Getting error:- TypeError: bad argument type for built-in operation.
Request to help for other datatypes too.
| I got the solution by replacing auto result = _PyUnicode_AsString(pValue); with int result = PyFloat_AsDouble(pValue);. But I am not fully convinced as I needed an integer, but I had to use a function which looks to be meant for dealing with Float/Double. So, waiting for an accurate answer. Thanks!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.