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 |
|---|---|---|---|---|
62,779,418 | 62,779,699 | How to construct a vector from a line of an unknown number of int // c++ | Usually the number of inputs is given and i can do it with a for loop but not there : https://codeforces.com/contest/469/problem/A
I am trying desesperately to construct a vector from a line of ints , but i just know than the number of ints cannot be higher than 100.
There s 2 lines of inputs.
If i make an infinite loo... | Actually, if you read the question carefully, the number of integers on each line is given.
The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a 1, a 2, ..., a p (1 ≤ a i ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Littl... |
62,779,488 | 63,375,739 | A friend abbreviated template function - clang and gcc differ | The following code compiles with clang but not with gcc:
template<typename T>
class number {
T num;
public:
number(T num = 0): num(num) {}
friend auto add(auto a, auto b);
};
auto add(auto a, auto b) {
// the decltype(a) is needed to make clang happy
// see: https://stackoverflow.com/questions... | Apparently it was a bug in GCC 10.1.0, after working correctly till 9.3.
Bug was opened and fixed in GCC 10.3.
|
62,779,901 | 62,782,437 | Class Template Argument Deduction for template dependent parameter | Let's start with a simple add method for class number:
class number {
int num;
public:
number(int num = 0): num(num) {}
operator int() const { return num; }
};
number add(number t1, number t2) {
return t1 + t2;
}
int main() {
auto result1 = add(1, 2); // auto-casting, works fine
}
Now we want to ... | I think the answer is simple. In the first case, with the free function template, what kicks in first is overloading resolution and function template argument deduction. As the compiler has no way to detect T from the int passed as argument (clang says: candidate template ignored: could not match 'number<type-parameter... |
62,780,373 | 62,780,420 | Violating const correctness: What problems should I expect realistically? | I want to use a function parser library where the member function FunctionParser::Eval() is non-const, because it writes an error code to a member variable. I would like to integrate this function parser into a codebase, where this function would get called through a const member function of a class holding that functi... | If the object is actually defined const, then casting away const-ness to modify the object is undefined behavior.
Consider instead using the mutable keyword, which declares an exception to const-ness for a given field; a mutable field is always non-const even when accessed on an object that is considered const in the c... |
62,780,506 | 62,780,559 | Pass object with derived template to function that accepts object with base template | How do I pass an object with a derived template instantiation to a method accepting those objects with a base template instantiation?
It seems possible, as std::shared_ptr or std::pair seem capable to do it.
E.g.
#pragma once
#include <iostream>
#include <memory>
struct Base {
virtual void print() = 0;
};
struct... | You will need to explicitly add a conversion constructor and/or assignment operator to your Wrapped type to be able to convert from different types.
This is how both std::shared_ptr and std::pair do this internally; shared_ptr<T> can be constructed from shared_ptr<U> types (with SFINAE restrictions that U* is convertib... |
62,780,823 | 62,781,125 | Templated ostream operator << for multiple types within a namespace | I have a namespace with several structs and enum classes inside of it. For each type, I have a toString() method. Here is a small example:
namespace test {
struct A {
int i;
};
struct B {
float j;
};
std::string toString(const A &a){
return to_string(a.i);
}
std::str... | I solved it using concept & requires of C++20 (gcc >= 10.1):
template <typename T>
concept HaveToString = requires (T t) {
{ toString(t) };
};
template<HaveToString T>
std::ostream & operator<<(std::ostream &out, const T& t){
out << toString(t);
return out;
}
int main() {
test::A a;
std::cout << a... |
62,780,931 | 62,791,546 | Linux header files in VS wihout project | I am using VS2019 on Windows to edit c++ code files. The code is for Linux OS and depends on headers like #include <sys/socket.h> There is no project file for the visual studio so I can only open it as directory with files. It does know includes stdint.h and windows.h but not sys/socket.h.
How set VS to know the standa... |
Linux header files in VS wihout project
Actually, <sys/socket.h> is used for UNIX/Linux. And Windows cannot use it.
Instead, you should use <Winsock2.h> on Windows and it corresponds to socket.h on Linux. Also, do not forget to link against Ws2_32.lib.
Suggestion
Use these:
#include<winsock2.h>
#pragma comment(lib, "... |
62,781,111 | 62,790,979 | Make std::cout do not fail with O_NONBLOCK or make stdin O_NONBLOCK keeping stdout blocking? | #include <iostream>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(){
// Make stdin non-blocking
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK);
printf("stdout O_NONBLOCK is: %d\n", fcntl(STDOUT_FILENO, F_GETFL) & O_NONBLOCK);
printf("stdi... | Standard streams do not support non-blocking file descriptors, those are beyond the scope of the C++ standard.
If you insist on using non-blocking file descriptors with standard streams, then you need to implement a stream buffer that can read/write non-blocking file descriptors. You can do that from scratch by derivin... |
62,781,437 | 62,781,516 | how to call function from another class in qt? | here is my code:
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "secd.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionSettings_triggered()... | Prototype of function should be declared for source file directly or in a header:
#include "secd.h"
#include "ui_secd.h"
#include <QMessageBox>
#include "mainwindow.h"
void function1(); // <---------------------------
secD::secD(QWidget *parent) :
QDialog(parent),
ui(new Ui::secD)
{
ui->setupUi(this);... |
62,781,737 | 62,782,047 | What should be the semantics of a reference to const string in C++17? | There are several ways to pass textual information into a function in C++: that could be a c-string/std::string, by value/by reference, lvalue/rvalue, const/mutable. C++17 adds a new class into the standard library: std::string_view. The semantics of the string_view is to provide read-only textual information without o... | Do you need null-termination? If so, you have to use one of these:
// by convention: null-terminated
void read(const char*);
// type invariant: null-terminated
void read(std::string const&);
Because std::string_view is just any contiguous range of char const, there is no guarantee that it is null-terminated, and it's... |
62,782,042 | 62,825,689 | Why is the C++ compiler not detecting a properly declared Class? | According to the error codes, the compiler (MSVC 2019) is not detecting properly declared classes.
In the following code, the compiler halts at the first mention of UACvLogin in the UACcDefault class definition.
[\src\UAC\controllers\UACcDefault.h][1]:
#ifndef MANAGER_UACCDEFAULT_H
#define MANAGER_UACCDEFAULT_H
#inclu... | The circular #includes came from having a includes.h, which also included main.h.
The includes.h file had everything needed by most of the code: wxWidgets, boost::propertytree, SOCI. Due to needing access to some global variables (preferences), main.h was also included.
I have refactored includes.h into separate files ... |
62,782,361 | 62,782,591 | Error "Could not find Boost" (missing: context headers) | I've added boost like this: "-DBoost_INCLUDE_DIR=/boost_1_71_0"
and this is what I get:
Could NOT find Boost (missing: context headers) (found suitable
version "1.71.0", minimum required is "1.71")
Cmake can determine boost version but cannot find boost at the same time!
Is there a way for me to fix it?
This is how... | Boost context and headers are header only libraries and therefore do not need to be mentioned in the find_packages call. Do a simple find_package(Boost 1.71 REQUIRED) and you are done. Later you can reference the Boost header directory either with Boost::boost or Boost::headers in your target_link_librariescommand.
|
62,782,499 | 62,809,301 | WIN32:C++, why is calling the Messagebox function on WM_CLOSE The program is freezing | I'm learning about creating a Windows desktop application using Visual C++.
I am creating a simple window that does nothing, and when I press the close button, I wanted to display a message box to confirm that I really want to close it before I close the window.
So I tried to do this using the Messagebox function when ... | Try explicit use of unicode in your program. for exsmple using MessageBoxW instead of MessageBox and L"終了してもよろしいですか?" instead of TEXT("終了してもよろしいですか?") and change your windowproc a bit:
#include<Windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
ATOM InitApp(HINSTANCE);
BOOL InitInstance(HINSTANCE, int);... |
62,782,682 | 62,782,795 | Override a sub-class to a child-class | How does one go about overriding such a function in the example below?
It's clearly not working the way I wrote it, but is it possible to implement something similar?
class Foo
{
public:
class Kid
{
public:
virtual void DoSomething();
};
};
class FirstBar : public Foo
{
public:
void Foo::Ki... | My take on it - your bars want to have Kids of their own, properly inheriting:
#include<iostream>
class Foo
{
public:
class Kid
{
public:
virtual void DoSomething() {std::cout<<"Kid!\n";}
};
};
class FirstBar : public Foo
{
public:
class Kid : Foo::Kid {
public:
void DoSomethin... |
62,783,102 | 62,783,820 | Why does my counter not function properly when it should be 0, but other values >0 work fine? | What I'm trying to do
Return an integer, which would represent the number of numbers that I would need to add in order to make my array consecutive (once its sorted, first).
Sample input and output
Input: [6, 2, 3, 8].
Output: 3.
Reason: After sorting the vector to [2, 3, 6, 8], we would need 3 numbers in order to make... | The standard library already provides std::adjacent_difference, which can do the vast majority of the work for you:
#include <numeric>
#include <iostream>
#include <vector>
#include <algorithm>
int makeArrayConsecutive(std::vector<int> input)
{
std::sort(input.begin(), input.end());
std::vector<int> diffs;
... |
62,783,351 | 62,903,069 | What's the easiest way to generate type-variant C++ code when templates and macros aren't possible? | In Unreal Engine, I've created a series of structs in C++ that let me generate a replicated version of the TMap struct. It relies on a number of engine resources like Fast Array Serialization, and the structs needs to be recognized by the engine like a normal USTRUCT.
For example, here's there starting piece of one of ... | In case anyone stumbles across this post, the best solution I found is using Visual Studio's T4 Text Templating engine, despite it not being included in C++ project files. In the case of UE4, you can use the UProject file to prebuild a Text Template.
Important Resources:
T4 in C++
UE4 PreBuild
My UProject Code addition... |
62,783,538 | 62,783,627 | How to fix missing default argument on parameter 'args' with clang? | I have a short and convenient code for multi-dimensional vectors, with the ability to choose size and default value during initialization.
#include <iostream>
#include <vector>
using std::vector;
template<int D, typename T>
struct Vec : public vector<Vec<D - 1, T>> {
static_assert(D >= 1, "Vector dimension must be... | int n = 0 an argument with a default value can't be followed by arguments without defaults. Remove the =0
|
62,783,884 | 62,783,987 | How to return a pointer to a C++ object to python using boost if the class of that object is declared in another boost module? | Okay, maybe I'm not finding an answer because I'm not sure how to word it, but I have a class called Info and another class called Packet, both are compiled into Python extensions using boost, and I would like to return a pointer to an Info object from the Packet module.
info.cpp
#include "info.h"
Info::Info(int i_, in... | You only imported Packet.
You also need to import Info.
Otherwise, as the error says, Python doesn't recognise it when p.test() attempts to use it (or, more specifically, to return a pointer to it, to assign to t).
|
62,784,428 | 62,786,641 | Understanding loops within loops C++ | Apologies for the newbie question but I'm new to programming and learning C++. I'm working my way through C++ Primer and I've gotten to the If statement section where this code has been written.
#include <iostream>
int main()
{
// currVal is the number we're counting, new values will be put into val
int currVa... | Your code:
if (std::cin >> currVal) {
int cnt = 1; // Store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to count (cnt)
else... |
62,784,466 | 62,784,532 | Is counter in std::shared_ptr atomic? | At the interview, I was asked what is the peculiarity of the counter in std::shared_ptr(it is an atomic). However, I have heard opinions that std::shared_ptr doesn't work well with multithreading. What is true?
|
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object. If multiple threads of execution access the same shared_ptr without ... |
62,784,579 | 62,784,622 | How to convert a float into an unsigned int in C++? | I want to convert a float to an unsigned int. When I use this code, the terminal print 3 :
#include <iostream>
int main() {
float test = 3.4;
std::cout << "test : " << int(test) << "\n";
}
But when I use this code I have an error :
#include <iostream>
int main() {
float test = 3.4;
std::cout << "test : " << ... | The functional cast (type(expr), that is) requires the type to be spelled as a single word (without spaces, [], *, &, etc).
unsigned int is not a single word, so it's not allowed.
Your options are:
Using the regular C-style cast: (unsigned int)test.
Omitting the int. unsigned alone means the same thing as unsigned in... |
62,785,275 | 63,071,546 | use of variable in EXPECT_CALL | I have a simple mock class for a serial interface:
class MockSerialPort : public drivers::SerialPort
{
public:
MockSerialPort() : SerialPort(){};
MOCK_METHOD((Result<size_t>), Read, (uint8_t *, size_t, (const duration<int64_t, std::micro> &)), (override));
MOCK_METHOD((Result<size_t>), Write, (const uint... | In such "complicated" cases - use lamdba expression - or some other function, functor object:
EXPECT_CALL(port_, Read(NotNull(),_ ,_))
.WillOnce([](uint8_t *data, size_t length, const duration<int64_t, std::micro> &) {
// do with data and length whatever you want
return length;
});
This is poss... |
62,785,314 | 62,788,065 | How to make a submenu do a function onclick in C++ | I am trying to make a simple menu with submenus on the top of any program's window which does any function you'd like on clicking the submenu, Say for example you click on Menu, it opens "sub-menu", you click on sub-menu and it does this function in which the window's title changes using SetWindowTextA.
SetWindowTextA(... | First, you can create an identifier to determine the menu item to control, like #define IDM_SUBSX 1001.
Then use the AppendMenu to specify the menu item by the identifier: AppendMenu(SubSX, MF_STRING, IDM_SUBSX, "Sub-Menu");.
Finally, through the WM_COMMAND message to determine the identifier of the menu item, we can d... |
62,785,346 | 62,785,424 | C++ macro token pasting with a trailing underscore | I am trying to write a macro that automatically creates accessor and mutator methods which set a dirty flag.
#define DIRTY_PROPERTY(type, name, var) \
private: \
type ##var_; \
\
public: \
... | The ## goes between the two tokens you're pasting together. In this case, you're pasting var and _ together, so ##var_ should be var##_.
Live Demo
|
62,785,384 | 62,786,447 | Writing partial unique_ptr for C++03 compiler which operates on common codebase with newer compilers | I need to write an implementation of unique_ptr for C++03 which would only absorb changes made in common codebase under other platforms where C++11 is enabled. Namely, it doesn't need to check anything, everything will be checked by other platforms compilers. But it needs to properly pass and destroy objects.
This is a... | Templates are never copy constructors.
unique_ptr(const unique_ptr<Data>& other)
unique_ptr(unique_ptr<Data>& other)
write these two.
Also similar for operator=.
|
62,785,519 | 62,785,649 | Can I use reverse iterator as ForwardIt? | Based on this question.
std::rotate is defined the following way:
template< class ForwardIt >
constexpr ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last );
Looking at the name ForwardIt, it expects forward iterator.
Question: assuming that my initial collection supports forward iterator (e.g. vecto... | The requirements for reverse_iterator are given in reverse.iter.requirements:
The template parameter Iterator shall either meet the requirements of a Cpp17BidirectionalIterator ([bidirectional.iterators]) or model bidirectional_iterator ([iterator.concept.bidir]).
and the requirements for iterator.concept.bidir:
Th... |
62,785,645 | 62,785,754 | What does line is supposed to mean? | float sqrt_approx(float z) {
int val_int = *(int*)&z; /* Same bits, but as an int */
/*
* To justify the following code, prove that
*
* ((((val_int / 2^m) - b) / 2) + b) * 2^m = ((val_int - 2^m) / 2) + ((b + 1) / 2) * 2^m)
*
* where
*
* b = exponent bias
* m = number of m... | This is called type punning. This particular usage violates strict aliasing rules
By taking the address of the float value z, and reinterpreting it as the address of an integer value, the author is trying to get access to in-memory bytes representing this float but in the convenience of a int.
It's not the same as int ... |
62,785,721 | 62,785,759 | Why i can't use scope resolution operator during the constructor initialization? | using the scope resolution operator in the below code during the initialization in the constructor gives me error. Why can I only use scope resolution operator in front of the function name (i.e.Vector::Vector(int i)?
class Vector {
public:
Vector(int s); // declaration an interface to definition or what pa... | The member-initialisation list is more constrained than some arbitrary expression.
While it is true that you can qualify member names, like Vector::sz, in expressions generally (where sz is in scope), the syntax of a part of the member-initialisation list simply does not support this. You must write name(init) or name{... |
62,786,174 | 62,786,192 | Are classes namespaces in C++? | Are classes namespaces in C++? I am asking this because the following code is valid. Could someone explain why?
Code:
#include <iostream>
class MainClass{
public:
enum Bool{False, True};
MainClass(){
std::cout << "MainClass constructor" << True << std::endl;
}
~MainClass(){
std::cout << "MainClass des... | Classes are not namespaces. However the Bool enum is defined in MainClass's scope, so the scope resolution operator :: applies.
|
62,786,520 | 62,789,792 | Passing in a Template Class | I am designing something to do operatorations from an expression, so for example (3 + 5), the string would be read and the expression will be evaluted and returned. Now I got the correct output, my problem is that I implemented the stack in three different ways, linked list, Vector, and dynamic array, now they all have... | You can use template template parameters as in the following example. A description of the syntax can be found here.
template < typename T >
struct V_H
{
void push() { std::cout << "V_H push" << std::endl; }
void pop() { std::cout << "V_H pop" << std::endl; }
};
template < typename T >
struct D_H
{
void ... |
62,786,586 | 62,786,738 | C++ Only Store Specific Bytes of a double in a char* | Off the bat I am unfortunately using an older version of c++ (I believe 98) so c++11 goodies are unavailable to me.
That aside, I was wondering- is it possible to only store specific bytes of a double in a char* buffer? For example, if I have a double that has a low value and therefore only uses 3 bytes of data can I t... | You are copying over the wrong bytes, you're computer is in little endian and so the 3 bytes you want to copy over will actually be the last three bytes of the double. If you change the copy line of your code to this
memcpy(&buffer[0], (void*)(&value)+5, 3); // Copy the last three bytes
you get a correct result of
000... |
62,786,620 | 62,786,660 | Writing Template function when called without template arguments | So I was trying to write a default function version when there are no template arguments passed in the following code:
struct A{ int x; };
struct B : public A { int y;};
struct C {
void set(const A& v) { v_ = v; }
template <typename T>
const T& get() { return reinterpret_cast<T&>(const_cast<A&>(v_)); }
... | You can delete the template <> part.
struct C {
void set(const A& v) { v_ = v; }
template <typename T>
const T& get() { return reinterpret_cast<T&>(const_cast<A&>(v_)); }
const A& get() { return v_;}
A v_;
};
|
62,786,680 | 62,787,128 | My Code is attemping to a deleted function? | I'm writing a program to manage products, employees and bills of a restaurant in C++.
But I have a problem when writing a function to read information of products from file to the Product struct.
That is C2280 Error and it say something like my code is attemping to reference a deleted function.
I've read for this Error... | The ifstream type has no copy constructor because it was intentionally deleted, meaning that you cannot pass it by value as you are doing in the readProductInformation function. More information about ifstream's constructors can be found here, most importantly the following
(3) copy constructor (deleted)
Deleted (no c... |
62,786,794 | 62,797,363 | How to define a piecewise function in z3 | I am trying to define a very simple piecewise linear function in Z3 with the following C++ code:
context c;
sort I = c.int_sort();
expr x = c.int_const("x");
func_decl f = function("f", I, I);
solver s(c);
s.add(forall(x, f(x) == ite(x <= 2, x, x + 1)));
s.add(f(x) == 2);
std::cout << s.check() << std::endl;
This gene... | Malte described some of the issues that crop up often in handling quantifiers. It's almost always a bad idea to use quantifiers to define functions like this: It unnecessarily invokes procedures that can easily lead the solver to never-ending e-matching loops. The classic (and "official") way to define such a function ... |
62,786,836 | 62,787,391 | What end of stream dup2 change? | What end of the stream does dub2 ( ) change is it the end the OS is connected to or the end connected to application .
int main(){
FILE* file = fopen("test.txt", "w"); // Create file dexcriptor
int num = fileno(file); // Convert FILE* to file descriptor
dup2(num, STDOUT_FILENO); // Make STDOUT... | Before the dup2(), the file descriptor table for the process looks something like this:
0 => terminal (stdin)
1 => terminal (stdout)
2 => terminal (stderr)
...
num => file "test.txt"
After the dup2(), it looks like this:
0 => terminal (stdin)
1 => file "test.txt"
2 => terminal (stderr)
...
num => file "test.txt"
Ther... |
62,787,204 | 62,871,418 | Can I promote base class to child class? | I have a class A, as below:
struct MY_DATA
{
int m_nType;
union
{
DWORD m_dwBData;
double m_dCData;
} u;
};
class CClassA
{
public:
CClassA(BYTE* lpData, UINT uSize);
virtual ~CClassA(void);
MY_DATA m_Data;
};
CClassA::CClassA(BYTE* lpData, UINT uSize)
{
::memcpy(&m_D... | You cannot get the type information at runtime, without adding/getting any type of information about the content of the data. There are some solutions if you can get type information somehow
Either you set struct MY_DATA::m_nType befor processing it by getting it's type by looking at the data (maybe you have some kind... |
62,787,247 | 62,787,291 | Assignment to a function pointer in the global scope | I am trying to define a type for function pointers, in c++. However, once I define the pointer funcp as a fptr, I cannot redefine the pointer as a different function, times. This program does not even compile. Is this because I have to delete the nullptr before reassigning times to funcp?
My code:
#include <iostream>
u... | The problem is that you are trying to do that outside of any function. Try that:
int main()
{
funcp = times;
return 0;
}
Your question has nothing special for C++17. To make it a little more modern and easier to read you may use the using instead of typedef:
using fptr = int (*)(int, int);
|
62,787,309 | 63,247,756 | Runtime errors on using veins and veins_inet content on same simulation | Ubuntu - 20.04 , Omnetpp - 5.5.1 , veins - 5.0 , Sumo - 1.6.0 , Inet - 3.6.7
I'm doing a project where I want to create a DSRC based and wifi based vehicular simulatons in the same simulate environment (same project).
I tried to get RSU and the Car node from veins example to veins_inet example to simulate both there.
p... | Please see the Veins FAQ at http://veins.car2x.org/documentation/faq/ for help on how to debug a simulation, specifically the entry What happened? My simulation crashed. and the entry How can I debug my OMNeT++ simulation models? How do I create a stack trace? (in brief: run the simulation in debug mode and set debug-o... |
62,787,561 | 62,791,623 | Where is the memory leak despite following the rules? | Hey guy's i cant seem to find the memory leak even tho i deleted everything before i initialize the object array and delete it when im not using it anymore. Unfortunately valgrind doesnt tell me where the error is but it does say i have 10/11 memory leak , here is my codes below. Dont mid the repetitiveness of the to c... | You have a leak if you do the following:
#include "basket.h"
#include <vector>
#include <iostream>
int main(int, char **)
{
Fruit fruits[2] = {{"Fruit a2"}, {"Fruit b2"}};
Basket basket2(fruits, 2, 10.0);
Fruit a("Fruit a");
Fruit b("Fruit b");
Basket basket;
basket +=a;
basket +=b;
... |
62,787,906 | 62,788,657 | Getting the size of a struct from a string | I have the following:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
struct headerStruct{
uint8_t header;
uint8_t data_1;
uint8_t data_2;
uint8_t data_3;
uint8_t data_4;
} my_header_0;
struct headerStruct2{
uint8_t data_8;
uint8_t data_9;
} ... | I'd build a map which contains all the objects with their name you want to check.
Then use a preprocessor macro to convert the name into a string.
#include <iostream>
#include <map>
#include <stddef.h>
#include <sstream>
#include <string>
struct headerStruct {
uint8_t header;
uint8_t data_1;
uint8_t data_2... |
62,788,109 | 62,788,605 | Qt and C++: Signal & Slot on multiple PushButtons | i create multiple QPushButtons in the following way:
QList<QByteArray> pBList;
pBList= rec_data.split(',');
for (int i = 1; i < pBList.size() -1; i++){
QPushButton *newpB = new QPushButton(ui->verticalLayoutWidget);
newpB->setText(pBList[i]);
ui->verticalLayoutWidget->layou... | QList<QByteArray> pBList;
pBList= rec_data.split(',');
for (int i = 1; i < pBList.size() -1; i++){
QPushButton *newpB = new QPushButton(ui->verticalLayoutWidget);
newpB->setText(pBList[i]);
ui->verticalLayoutWidget->layout()->addWidget(newpB);
//This will CONNECT al... |
62,788,206 | 62,788,284 | Primitive calculator - Dynamic Programming | So, the problem task is:
Given an integer , compute the minimum number of operations needed
to obtain the number starting from the number 1.
And here is my code for doing this:
#include<bits/stdc++.h>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n+... | You have pretty blatant out of bounds accesses on your vector v.
for(int i = 1; i <= v.size() - 1; i++)
,,,
v[3*i] = v[i] + 1;
3*i is obviously bigger than the size of v for most of your loop.
|
62,788,590 | 62,791,136 | Thread safety for multiple instance of object and multithreading | I want to each of these 3 object instance run in parallel. I have no global variables. Is it thread-safe? or do i need some syncronization mechanism?
class myClass{
public:
myClass();
~myClass();
void myFunction();
}
int main() {
myClass myObj1, myObj2, myObj3;
pthread_t myThread1, myThread2, myThr... |
Could you explain me why or why not need for syncronization?
You need synchronization when there is a data race.
Since in your example there is no data, there cannot be a data race.
You may find video Plain Threads are the GOTO of todays computing - Hartmut Kaiser - Keynote Meeting C++ 2014 instructive.
|
62,788,755 | 62,789,348 | Autotools: how to override the intermediate build product directory? | I noticed that many Autotools-based projects generate binaries into /path/to/project/lib/.lib folder.
This has a side effect for a cross-platform project where the first built project will contaminate the subsequent builds for other platforms.
I know that I could use --prefix and --exec-prefix for configure to specify ... | Create separate build trees for each platform and invoke the configure script from each build tree separately. This will ensure all build artifacts are separated by platform.
|
62,789,873 | 63,550,977 | How to wrap std::vector to use in pure C | In my project I would like to use C++ and STL containers but have a problem that I have to include hw vendor headers (and link vendor lib and use some vendor C sources that also include the vendor headers) written in ANSI C, that contain C++ reserved keywords, for example:
vendor.h:
// Vendor header (read only)
str... | There are methods now to access the raw data array of the Vector:
value_type* data() noexcept;
const value_type* data() const noexcept;
These extensions were added in C++11 exactly for your case, to interface third party libraries that only take the raw data array. Pass the returned pointer to C as an array that is ... |
62,790,077 | 62,790,316 | c++ : Defferentiate templates in an if statement | I seem to have the following problem. I have a class BSK (Binary Knapsack) which contains a struct Item in which an identifier can be std::string or int. Then I have a vector<Items> itemlist_ and I need to insert a new Item in the beginning. I am trying to do something like this and it works for int but does not work ... | You need to instantiate the correct (only one of) part of if at compile time. Normal if statement can not do that. Read more:
Difference between "if constexpr()" Vs "if()"
You need if-constexpr.
Suggestion: In addition, you do not need extra toInsert, pass the temporary, to the itemlist_.
if constexpr (std::is_same<T, ... |
62,790,485 | 62,796,077 | Loop running infinitely C++ for Knight Tour Problem | I'm coding the Knight Tour problem in C++. But the is running indefinitely. I checked my logic and is similar to the logic mentioned here
#include<bits/stdc++.h>
using namespace std;
bool isvalid(vector<vector<int>>board,int i,int j)
{
return i >= 0 && j >= 0 && i < 8 && j < 8 ;
};
bool checkcompletion(vector<vec... | what you are trying to do is recursive function but you do not have exit condition so the function calls itself in a loop. You should put a return in someplace in your function according to the target of your function. for example:
if (tour(board, i + 2, j + 1, steps) == 0)
{
return steps;
}
(this is an example I ... |
62,790,494 | 62,790,646 | Error No instance of overloaded function "getline" matches the argument list | I've searched this website and I have tried most things and they all don't work If anyone knows what I am doing wrong please help, This is my code.
string getlinetest;
cout << "What is the string?" << endl;
cin >> getlinetest;
getline(cin >> getlinetest);
cout << getlinetest << endl;
| std::getline is not used as you are trying to use it. (I think you just made a typo by using >> instead of ,.)
You need to call it like this:
std::string getlinetest;
std::cout << "What is the string?" << std::endl;
std::getline(std::cin, getlinetest);
std::cout << getlinetest << std::endl;
PS:
And I don't get any se... |
62,791,370 | 62,793,196 | How to create a Eigen VectorXd object from pointer without data copy | I have a double pointer, store some data in it.
I want directly create a VectorXd on the pointer without copy. That is, the data stored in VectorXd is just the data stored in pointer. They are shared.
I know it is easy to create a VectorXd object then copy data into it from the pointer. I do not want the element by ele... | You need to use a Map object:
#include <iostream>
#include <Eigen/Core>
using namespace std;
using namespace Eigen;
int main()
{
const int N = 100;
double *ptr = new double[N];
for (int i = 0; i < N; i++)
{
ptr[i] = double(i);
}
Map<VectorXd> vector(ptr, N);
vector *= 2;
cout <... |
62,791,460 | 62,792,349 | checking type of attribute with concepts | I want to check that an attribute of a struct/class fits to my needs with concepts, but compiler complains about.
Example:
struct N
{
char value;
auto Get() { return value; }
};
struct M
{
int value;
auto Get() { return value; }
};
void func3( auto n )
requires requires
{
//{ n.Get() } -> std:... | GCC is actually right (when rejecting the code, not going bonkers). To quote the standard
[expr.prim.req.compound]/1.3
If the return-type-requirement is present, then:
Substitution of template arguments (if any) into the return-type-requirement is performed.
The immediately-declared constraint ([temp.param]) of the ... |
62,791,478 | 62,792,580 | how to check if a value exist in QList? | I have a class to save the ID of customer and his name. After saving I'm inserting the object into a QList and viewing them on table.
What I need:
I need to check if the customer is already added to the table or not.
My approach:
I'm trying to search the list using the customer ID and if I find it I want to update his ... | If you need to access your data through a customerID regularly, I would recommend to use a QMap<int, Customer*>. (use as key the type of your customerID)
Using a QMap will be much faster if the number of customers is getting large.
Then you can do something like::
if (!myMap.contains(customerID))
{
myMap.insert(cus... |
62,791,561 | 62,792,589 | Find the length of longest increasing subsequence C++ | Please help me solve this problem, when input 10 and 1 2 3 1 2 3 3 4 5 6
Output should be 4 but it's 6.
In all other tests, the program is working well.
For Example:
Input: 1 -10
Output: 1
Input: 2 123 123
Output: 1
Input: 2 -1245 234
Output: 2
Input: 5 1 2 3 -1 -20
Output: 3
Input: 5 1 1 2 3 1
Output: 3... | Firstly, the length array values are unitialized, this will invoke undefined behavior, in your case, by chance, it works, but you should expect that whatever garbage values are in the array will be used as a comparison, to avoid this you should fill it with 0s.
Then, this piece of code:
for (int i = 0; i < n; i++)
{
... |
62,791,825 | 62,793,687 | Passing a C# String array to C++ | I have a string array in C# for example:
string[] level = {"results","isPA"}
Now I need to pass this array to a C++ Function.
The wrapper looks like this:
[DllImport("File.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)
public static extern long SetJsonString(string[] Level, string Entry,... | Using SafeArray just like Thinh Tran suggested did the trick.
The code can be found here: codeproject in the "Passing an Array of Strings" paragraph.
|
62,792,200 | 72,481,742 | C++ std string different between debug and release dynamic library | I have a dynamic library in which I send an IP address and try to connect to an instrument. The library is working well when it's build in debug mode but crashes on using release one.
I am trying to use it from a console application and this is what I have:
Main in the console application
#define QT_API extern "C" __d... | Both the caller and the DLL must be built with the same mode type. For example you have function that takes std::string as an argument that is exported from a DLL. If the caller main() is not also compiled in DEBUG it will crash. The compile mode changes the storage definition (secretly) for std:string. So the DEBUG mo... |
62,792,225 | 62,833,048 | Register custom type in Qt with QJsEngine | I have a custom class named LObject, with a method "test" i want to call.I have a method registered in a QJSEngine that returns an instance of LObject.
I get the error message when executing the method :
"Error: Unknown method return type: LObject"
I tried to register my type with Q_DECLARE_METATYPE, but then i can't... | Solved !
qmlRegisterInterface<TObject>("TObject",1);
and then the methods have to return a TObject*.
|
62,792,301 | 62,792,655 | which c++ stl data structure will be the most efficient for storing unique values and their counts? | I have a list of values, with some recurrences, e.g. : {1,2,2,3,3,3,3,7,8,1}
I want to store the unique values in this list in a data structure along with their counts.
--------------
|value |count|
--------------
| 1 | 2 |
--------------
| 2 | 2 |
--------------
| 3 | 4 |... | First note that asking for "the most efficient" data structure is not a proper characterization of your requirements. Do you want a solution which:
is the fastest to use? In what use cases?
takes up the least amount of memory?
is the most maintainable/readable?
is the least bug-prone?
is the fastest to write?
exists a... |
62,792,538 | 62,793,183 | to set a time delay in a IF statement in Qt | I've real-time signal, I need to check if the signal crosses a threshold and set a delay for about 1 second. How do I implement that?
if(a_vertical> onThreshold) //what's the expression to set a time delay?
{
ui->rdo_btn_vertical->setStyleSheet(StyleSheetOn1); // On LED
}
else
{
ui->rdo... | The easy and dumb solution is to start QTimer in single shot mode and check if it's running (should not be) while detecting the pulse. "Easy and dumb" doesn't mean "good".
Depending on the nature of the signal, filtering it might be a viable option.
|
62,792,728 | 62,793,022 | Reading multiple bytes from file and storing them for comparison in C++ | I want to binary read a photo in 1460 bytes increments and compare consecutive packets for corrupted transmission. I have a python script that i wrote and want to translate in C++, however I'm not sure that what I intend to use is correct.
for i in range(0, fileSize-1):
buff=f.read(1460) // buff stores a packet of ... | fseek
doesn't read, it just moves the point where the next read operation should begin. If you read the file from start to end you don't need this.
To read binary data you want the aptly named std::istream::read. You can use it like this wih a fixed size buffer:
// char is one byte, could also be uint8_t, but then you... |
62,792,820 | 63,358,490 | How can I get some information about crashed program in c++ for future debugging | I would like to know is there any way to capture some information when a program crashes in c++. This information can be used for future debugging by developers. For example, this information provides that my program crashes in which line of code and in which function or preferably why.
| google::InstallFailureSignalHandler(); can provide us the information. It also automatically prints call stack.
It is very easy to use.
For more information please see
http://rpg.ifi.uzh.ch/docs/glog.html
|
62,792,963 | 62,792,964 | luaL_dofile fails on known-good bytecode, works with uncompiled version | I've put together a very simple Lua engine but it seems to reject bytecode which works in the lua console. The uncompiled version works in the engine. Am I using luac wrong somehow?
I compile using the given command and run as './a.out'.
res/default.lua:
print("Setting up world structure.")
luac command:
luac -o res/d... | What confused me was that it worked in the lua console but not in my program. I added a call to lua_tostring after the call to luaL_dofile, like this:
rc = luaL_dofile(m_lua, filename.c_str());
std::ostringstream ostr;
ostr << "Could not load lua file. ";
ostr << lua_tostring(m_lua, -1);
THROW_IF_NONZERO(rc, ostr.str()... |
62,793,150 | 62,794,028 | Why does std::function can implicit convert to a std::function which has more parameter? | I have the following:
void print_str(std::shared_ptr<std::string> str) {
std::cout << str->c_str() << std::endl;
}
int main() {
auto str = std::make_shared<std::string>("Hello");
std::function<void()> f = std::bind(print_str, str);
f(); // correctly print: Hello
return 0;
}
I think the type of s... | What std::bind does is correct. It uses the value you provided (str) for the call to print_str. So you don't need to specify it anymore and will always be replaced by the bound value.
#include <iostream>
#include <functional>
int sum(int value1, int value2) {
return value1 + value2;
}
int main() {
std::funct... |
62,793,616 | 62,793,936 | Why are std::vector and std::valarray initializing constructors different? | I have just been burned by the following.
If I want to initialize a std::vector of n elements with a constant X I do this:
std::vector<double> v(n, X);
But if I need to initialize a std::valarray of n elements with a constant X I need to swap the size and initializing constant:
std::valarray<double> va(X, n);
This se... | Because they don't come from the same place: vector comes from the STL library, and valarray doesn't (I haven't been able to find out where it comes from, but there seem to be strong connections to Fortran).
Quoting Bjarne himself:
Most of the time, work on each of these components progressed in
isolation from work on... |
62,793,781 | 62,859,476 | writing to file produces an empty file or no file at all | my GUI runs on a machine that should be shutdown pressing its button (not via windows screen) in case an error occurs.
the GUI writes an error log into a file, using CStdioFile object, and then pops up an error window announcing user to shutdown machine.
It seems that in some cases, windows is deleting this file, or th... | the issue was not with modeCreate. As I wrote, the file was created correctly, but removed when shutting down the machine.
It seems that I found the issue:
after
myFile.Flush();
I added
FlushFileBuffers(myFile)
which causes all buffered data to be written to a file.
and this forced windows to write file to disk. Seems ... |
62,793,825 | 62,808,945 | C++ Higher order templates | I'm trying to create a system in C++ where I can implement many different entities E each with a different type T associated to them. I want to make a generic owner for these so that for implementations E1 associated to T1, E2 associated to T2 ect, I can wrap them inside a container where they can all be managed, somet... | You could use a std::variant and use visitation.
Eg. the queue object could be defined as
using InterfaceVar = std::variant<Interface<E1>, Interface<E2>>;
std::queue< InterfaceVar > eventQueue;
Then you would use visitation to discriminate on the type (It sounds like you want it this way). You could use std::visit for... |
62,794,109 | 62,803,312 | How can I find source code folder within docker container when debugging in VScode | I have a containerized C++ application, I've build the image and also able to run the model executable file inside the container in windows prompt
I'm following this article to setup the debug in VScode.
If I use ls -al Ican see the source code files in it, but I use docker diff, it returns things like this:
docker dif... | Provided the container is still running and has not been terminated or has not correctly been set up (or else docker ps might not list it), as a diagnostic tool, you can use the exec command, available from Docker 1.3 that allows to run a command to an existing running instance of a container. So you can open a shell, ... |
62,794,280 | 62,796,195 | Why does the simple arithmetic subtraction not work in the "if" condition? | I have 2 arrays with elements in them. I used hashing to get the frequencies of each element which occurs more than one time. mapcheckA contains the frequencies of elements of first array and mapcheckB contains the frequencies of the other array. I am trying to delete/erase any duplicates of elements from both the unor... | You have two significant bugs:
working on a copy of the data (already identified in comments). Working with a reference means changes will be reflected in original container, rather than discarded when the copy goes out of scope.
for (auto& i : mapcheckA) { // add the &
undefined behavior
In your "else" case, you r... |
62,794,502 | 62,794,813 | OpenMP: Is array reduction always needed for updating an array in parallel? | I am quite new to OpenMP. I have the following simple loop that I want to run in parallel with OpenMP:
double rij[3];
double r;
#ifdef _OPENMP
#pragma omp parallel for private(rij,r)
#endif
for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
if (i != j)
{
distance(X,rij,r,i,j);
... | You don't need a reduction. It is a feature to avoid copying the same code all over again because they are re-occurring problems (Try to think off, how you would implement a sum-reduction without OpenMP).
What you do right now is working on parallel data (V[i]) which should not overlap at any iteration (as you state in... |
62,795,466 | 62,795,518 | Using member functions in operator overloading definition (error with const) | I am getting error in the operator overloading definition. The error goes away if I remove the consts in the parameters. Is there any way I can get it working without removing the consts in the parameters? Also what is happening behind them?
class Vector3D{
public:
float x, y, z;
float dot(Vector3D& v) {
... | You should qualify the member function dot as const as well, otherwise you can't call this member function on a const object:
float dot(Vector3D const& v) const { // <-- const here
You also need to accept v by const& since you are passing it a const object.
|
62,795,578 | 62,795,637 | Write a program to print all armstrong numbers between 1 and 1000 | Write a program to print all armstrong numbers between 1 and 1000.
My Attempt:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num=1, rem, sum, k;
cout<<"Armstrong Numbers are: "<<endl;
do
{
sum=0;
k=num;
do
{
rem=num%10;
... | Your inner loop is breaking num.
num++; should be num = k + 1; because the value of num is stored to k before the loop.
|
62,795,859 | 62,801,456 | Using C++'s date library to read times | I am attempting to use Howard Hinnant's date library (https://github.com/HowardHinnant/date) to read user input into a datetime object. I would like to use this library since it's modern, and is to be included in C++20.
The program should be able to accept datetimes in ISO 8601 format (YYYY-MM-DDTHH:MM:SS+HHMM etc, eg ... | Good question!!!
You're not doing it quite right, and you found a bug in date.h! :-)
First, I've fixed the bug you hit here. The problem was that I had the wrong value for not_a_year in from_stream, and that bug has been hiding in there for years! Thanks much for helping me find it! To update just pull the tip of th... |
62,795,924 | 62,796,383 | Parameterizing custom CMake toolchain | I'm writing CMake toolchain files for cross-compilation.
I've got several toolchains, that differ very slightly. I'd like to create a single file for cmake that describes all toolchains and have users to specify them from command line: cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/toolchain.cmake -DTOOLCHAIN_NAME=<name>
Howeve... |
I conclude from the output above that supplied toolchain file is processed by CMake at least 3 times. First two times there were proper cache entries, and at the third run they were absent.
Yes, this is very good observation. Technically, only the first toolchain invocation at the project() call is guarantee to see t... |
62,796,448 | 62,796,536 | What types are convertible to std::any? | While writing a clang plugin, I noticed that objects of type llvm::cl::opt<T> are not convertible to std::any, i.e. the following snippet does not compile:
#include <any>
#include <string>
#include "llvm/Support/CommandLine.h"
int main()
{
llvm::cl::opt<std::string> opt("o");
std::any opt_any = opt; // doesn't wo... | llvm::cl::opt is not copyable. Both the copy constrcutor and copy assignment operator are marked as delete.
std::any requires that in construction and assignment that the type be copyable.
You could use a std::unique_ptr<llvm::cl::opt<std::string>> or std::shared_ptr<llvm::cl::opt<std::string>> or even a std::referen... |
62,796,513 | 62,885,177 | Gtesting Type Parametrized Test Instantion and Registration in different namespaces | I am using Gtest's Type Parameterized Testing Facility. Based on my code structure, I need to register and instantiate the Gtest Fixture in two separate namespaces. I get a compilation error when I try to do that. How should I place the instantiation and registration of Gtest Type Parameterized Testing Facility in two ... | For reference to anyone coming across this issue.
It is not possible to instantiate the test suite in a different namespace other than where the tests were initialized and registered.
This is because the Gtest macros use the TestSuite Name as is to declare a new namespace inside the registered namespace something like
... |
62,796,543 | 62,798,408 | Access the corect methods from multiple base classes based on some template parameter and without shadowing them | I have the following sketch
//g++ 7.4.0
#include <iostream>
template<int T>
struct X {
static int type() { return T; };
};
template<typename T>
struct FooBase {
int foo() { return T::type(); }
};
struct Foo : public FooBase<X<1>>, public FooBase<X<2>> {
template<int T>
int foo() { return F... | So here's one way you could do it. As your Foo derives from the bases, you could add the disambiguation one step ahead by adding the following function to Foo:
template<int I>
FooBase<X<I>>& as_base() { return static_cast<FooBase<X<I>>&>(*this); }
The call site would look like
Foo f;
f.as_base<1>().foo();
Still not r... |
62,796,700 | 62,798,353 | Addition Operation from ints in a String | I set up a string filled solely with numbers and using a for loop iterated through it in order to add them together mathematically (Wanted to see if the language would allow this), as a result I got some weird Numbers as the result. Can someone explain why this is happening?
int main()
{
std::string word = "2355412";
f... | The value you get is not what you expect because it is the sum of the ascii code corresponding to the characters you are summing, it's not converted into their value by default.
Also, as mentioned by other, string::operator[] doesn't check if you are trying to reach an out of bound value. In this case, you read 0 becau... |
62,796,703 | 62,798,135 | Boost::posix_time::ptime round to given number of minutes | I want to round minutes to given step(15 minutes). Like this
"2002-01-20 23:35:59.000" -> "2002-01-20 23:30:00.000"
"2002-01-20 23:00:59.000" -> "2002-01-20 23:00:00.000"
"2002-01-20 23:10:59.000" -> "2002-01-20 23:15:00.000"
"2002-01-20 23:55:59.000" -> "2002-02-21 00:00:00.000"
Is there a function in boost to do... | You can do integer rounding down to a period by doing
n = (n % period) * n;
To make it round up from half a period, just offset it:
n = ((n + period/2) % period) * n;
Now do it with time_durations instead. Sadly we can't do / or % with time_duration directly, so we'll convert to seconds first:
ptime round_to(ptime t,... |
62,796,837 | 62,796,874 | Difference between struct and class in older c++ versions | Was it always in C++ that class and struct are different only by the default access specifier? Or in some early version C++ struct was more like C struct?
| Pretty much always.
It has been this way since long before standardisation, practically since the first draft revisions in the 80s.
Frustratingly, Stroustrup's "A History of C++" does not discuss this, but types known as "classes", defined using the struct keyword, could be found as early as "The C++ Programming Langua... |
62,797,178 | 62,797,284 | Code works well on my computer but I am getting unknown signal 11 problem while submitting it to coursera | Task. Given a set of segments {[0, 0], [1, 1], . . . , [−1, −1]} with integer coordinates on a line, find the minimum number of points such that each segment contains at least one point. That is, find a set of integers of the minimum size such that for any segment [, ] there is a point ∈ such that ≤ ≤ .
Input Fo... | This is wrong:
while(segments[i].start<=segments[temp].end && i<segments.size())
You should check the index before you use it to acces an element not afterwards:
while(i < semgents.size() && segments[i].start<=segments[temp].end)
Later you have a loop that looks a bit scary, because you do not check the index at all:... |
62,797,274 | 62,946,930 | how to advance to next block of memory when relocating image | basically i just want to understand how does this works i saw a couple of people advancing to the second PIMAGE_BASE_RELOCATION struct (or second block of relocations) using current_base_relocation = reinterpret_cast<PIMAGE_BASE_RELOCATION>(reinterpret_cast<uint64_t>(current_base_relocation) + current_base_relocation->... | You are asking why the following code works to advance to the next IMAGE_BASE_RELOCATION block when processing a PE file's IMAGE_DIRECTORY_ENTRY_BASERELOC directory:
current_base_relocation = reinterpret_cast<PIMAGE_BASE_RELOCATION>(reinterpret_cast<uint64_t>(current_base_relocation) + current_base_relocation->SizeOfBl... |
62,797,298 | 62,797,579 | Fill vector with alphabets depending on user input and put Start and End on the extremities | I am trying to make a vector to look like this:
alphabet= {start,A,B,C,D,E,F,G,H,I,J,K,etc..,end}
The alphabet doesn't go from A to Z, the user inputs the values.
So if user inputs 5, I want the vector to be:
{start,A,B,C,D,E,end}
I tried using iota but I don't know how to push the "start" and "end" at the extremities ... | For the first 5 letters of alphabet
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
int main() {
// vector needs to be allocated, +2 is for start and end
std::vector<std::string> alphabet(5+2);
// front() gives you reference to first item
alphabet.front() = "start";
// end() gives... |
62,797,492 | 62,797,571 | I'm new to c++ can you explain pointers in this instance | Why does line 18 Node* bob = new(); not give me an error while line 22 node actualValue = new Node; does.
#include <iostream>
using namespace std;
class Node{
Node* node;
public:
int data;
};
int main() {
cout << "Hello, World!" << std::endl;
int a = 200;
int* ptr = &a;
cout << a << " pointe... |
Why does line 18 Node* bob = new(); not give me an error while line 22 node actualValue = new Node; does
The line in question is
Node actualValue = new Node;
new Node returns a pointer, you can't assign it to an instance of the Node class. And you forgot your parantheses after new Node to call the constructor. The c... |
62,797,501 | 62,804,354 | Why should I use std::cerr instead of std::cout in exception Handling? | Is there any significant advantage of using std::cerr instead of std::cout in the below snippest
try{
//codes that can throw go here.
}std::catch(std::exception const& e) {
std::cerr << "Exception " << e.what();
}
.
| The "err" in cerr is short for "error". It's intended for error messages. It writes to the error output stream, which, on UNIX-like systems, still writes to the console when you redirect the standard output stream. When you redirect output to a file, you usually don't want error messages intertwingled with the normal o... |
62,797,594 | 62,872,334 | How can I "convert" ISO-8859-7 strings to UTF-8 in C++? | I'm working with 10+ years old machines which use ISO 8859-7 to represent Greek characters using a single byte each.
I need to catch those characters and convert them to UTF-8 in order to inject them in a JSON to be sent via HTTPS.
Also, I'm using GCC v4.4.7 and I don't feel like upgrading so I can't use codeconv or su... | Ok I decided to do this myself instead of looking for a compatible library. Here's how I did.
The main problem was figuring out how to fill the two bytes for Unicode using the single one for ISO, so I used the debugger to read the value for the same character, first written by the old machine and then written with a co... |
62,797,832 | 62,806,646 | Codeforces: Two Divisors | Here is the question:
You are given n integers a1, a2, …, an.
For each ai find its two divisors d1>1 and d2>1 such that gcd(d1+d2,ai)=1 (where gcd(a,b) is the greatest common divisor of a and b) or say that there is no such pair.
Input:
The first line contains single integer n (1 ≤ n ≤ 5*10^5) — the size of the array a... | The most important thing we need to focus here is gcd(d1+d2 , a[i]) = 1.
For this condition to be true, d1 and d2 should be coprimes.
So, we need to find the 2 coprime divisors of a[i] and to find this, the smallest prime factor and it's multiplicity plays a big role.
For eg:
Suppose, N = p1^k1 * p2^k2 * ..... * pn^kn
... |
62,798,520 | 62,798,726 | Why is it possible to pass an lvalue to `std::async` even though it takes an rvalue reference? | The function std::async is defined like so:
template< class Function, class... Args>
std::future<std::result_of_t<std::decay_t<Function>(std::decay_t<Args>...)>>
async( Function&& f, Args&&... args );
As we can see, it takes both arguments as rvalue-references, or more precisely, as "universal references" (rvalue ... |
As we can see, it takes both arguments as rvalue-references, or more precisely, as "universal references" (rvalue references to the template argument types).
The term "universal reference" (or "forwarding reference") is not a more precise term for rvalue references. It's a different thing.
When you put && on a templa... |
62,798,588 | 62,798,831 | Using declaration on variadic args. How to choose the correct function? | I have a policy based design where I have some function foo() defined in some policies but not others. The base class always inherits from some class called AlwaysBase which has an inferior foo() function.
I want to make it so if a "better" foo() exists (one from a Policy class) that one will always be chosen.
Here is ... | Use recursion. If empty lists are allowed, this is very easy:
// recursive invariant: As<Ts...>::foo is always the foo from the first capable Ts or from AlwaysBase
template<typename... Ts>
class A : public AlwaysBase { // template<> class A<>
public:
// there are no capable Ts
using AlwaysBase::foo;
};
template... |
62,799,120 | 62,799,286 | Why am I getting a "no match for operator*" when using range-based for loop on anything that isn't "*this"? | I'm currently writing some utility functions for a templated container class for which the iterator seems to be working just fine. For example, the following code compiles and works as expected:
(Class name Mat, containing type T)
void scalarFill(T x){
for(auto& i : *this){
i = x;
}
}`
However, when I ... | This fails because at the point where the compiler sees this loop, it has not yet seen a definition for the MatIter template; MatIter<double> is therefore an incomplete type, so the compiler doesn't know about the operator* member function yet.
However, the result variable shouldn't even be Mat<double> here, it should ... |
62,799,337 | 62,799,583 | 'Could not deduce template argument for 'T'' when trying to parse variadic template | I'm trying to pass in a list of struct types into another class, which will take each custom class and add sort of put the struct type into a wrapper and insert that into a tuple. I'm new to templates in general, and can't figure out why the code wont compile.
The template-parser-wrapper thing
namespace engine
{
te... | Not sure... but I suppose you're looking for
template <typename ... Ts>
class ecs_manager
{
public:
std::tuple<component_manager<Ts>...> components;
ecs_manager ()
: components{ component_manager<Ts>{} ... }
{ }
};
Anyway... C++ is a strongly typed language.
So you can't define ... |
62,800,252 | 62,800,478 | What does archive_read_support_filter_all() do? | archive_read_support_filter_all() enables the code to use external programs if an appropriate library was not available at build time. (See https://www.freebsd.org/cgi/man.cgi?query=archive_read_support_filter_all&sektion=3&apropos=0&manpath=FreeBSD%2B10.0-RELEASE).
But libarchive (https://github.com/libarchive/libarch... | That's not what it says. archive_read_support_filter_all() simply "Enables all available decompression filters.".
In addition, there's a remark with the specific filters that says:
These functions may fall back on external
programs if an appropriate library was not available at build
time.
So, _all is just a superset... |
62,800,598 | 62,802,804 | Can not connect sqlite3 with c using mingw on windows | I want to use sqlite3 as a database interface for my c++, so i decided to start from this tutorial: https://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm
I have installed sqlite3 on my computer and add a environment variable for it, but when I try to compile a very simple program as the tutorial suggest by typing
gcc ... | With
gcc test.c -l sqlite3
you are attempting to link to a libsqlite3.a file which you don't have.
From the comments you do have the Amalgamation file sqlite.c. The documentation for this is here: https://www.sqlite.org/amalgamation.html
One simple way to use this is you can just build it with your executable like thi... |
62,800,680 | 62,800,765 | Binding a const pointer reference to a non-const pointer | int val2 = 38;
int *ptr = &val2;
const int *&ptrRef = ptr; // ERROR
int i = 92;
int &ref_i = i;
const int &ref_i2 = ref_i; // OK
Why I can't have a const reference that references to a non-const pointer? I thought that if you access the const ptrRef identifier, it will treat val2 as const. When you access ptr, it wi... | East-const makes it clearer:
int const * & ptrRef = ptr; // ERROR
It's the pointer that is const. However, ptr is a different type. You can't bind a reference to a different type. It requires a conversion, making the initializer a temporary (ptr converted to int const*).
Now, there's a more confusing catch: const ref... |
62,800,816 | 62,806,127 | System.InvalidCastException - SQL to C++ - safe_cast<float> | I need to give my variable a value from SQL, this part of the code it's where the compiler stops, aparently it's maybe a convertion problem. In my database that column is designed as float.
float presion = safe_cast<float>(data[4]);
Here is the code, every value gets to his variable until it reaches the floats
This is... | safe_cast is not a standard c++ type casting.
If you change your code to:
float presion = dynamic_cast<double>(data[4]);
it should work.
|
62,800,940 | 62,801,057 | Problem with OnClick event signature in C++Builder | I would like to create a function which replaces the current image with another one. The problem is that I have 64 pictures to replace. I created a function with a TImage* Sender parameter but it works only when I set Sender as TObject* instead.
How can I change this function:
void __fastcall TForm1::Image1Click(TObjec... | You can't change the signature of the event handler. It has to be what the VCL expects it to be, which in this case is defined by the TNotifyEvent type, which is what the OnClick event is declared as:
typedef void __fastcall (__closure *TNotifyEvent)(System::TObject* Sender);
__property System::Classes::TNotifyEvent ... |
62,802,310 | 62,802,589 | storing class instance with template on std::vector | I have this class, that I created to format some strings based in some conditions...
template <class PropObject, class PropType, PropType PropObject::* Prop>
class FlatFileStructure
{
private:
size_t _startPosition;
size_t _size;
int _fieldStyle;
public:
FlatFileStructure(size_t posicaoInicial, size_t ... | Conisder the public interface only (and rename the template paramters, it is advisable to use different naming convention than for "normal" types):
template <class T, class U, U T::* Prop>
class FlatFileStructure
{
public:
FlatFileStructure(size_t posicaoInicial, size_t tamanho, TipoDoCampo tipoDoCampo);
size_t... |
62,802,422 | 62,802,478 | How to print a set in reverse order recursively in C++? | I've tried the following code to print an std::set<int> in reverse order:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
#include <map>
#include <utility>
#include <set>
#include <stack>
using namespace std;
void setRecursivePrinting(set<int> s, set<int>::iterator it)
{... | I think you need to be passing the set by reference and not by value.
|
62,802,708 | 62,803,068 | When will the dynamic memory be destroyed in a C++ map with unique ptr as value? | I have a std::map:
std::map<uint64_t, unique_ptr<struct stats>> profile_stats;
And my insert and delete functions look like this:
Insert:
WriteLock(profile_stats_lock);
profile_stats_it it = profile_stats.find(id);
if (it == profile_stats.end()) {
profile_stats[id] = unique_ptr<stats>(new stats());
}
Delete:
Write... |
Will the dynamic memory for new stats() allocated during insert be destroyed when the iterator is erased in the delete function?
Yes. That is the whole point of using unique_ptr in the first place. It will free the new'ed memory for you when itself is destroyed, such as when it is removed from the std::map for any ... |
62,802,765 | 62,803,109 | How can I catch a format error from strftime as an exception? | I use ::strftime() in a VS2013 C++ program. Is there a way to handle an "invalid format" error correctly, without the risk of stopping the whole program?
When I run code like the function below with a wrong format, say "%Y- %- m-%d", it's "GAME OVER". I get:
"Debug Assertion Failed ... Invalid format directive"
and ... | The strftime() documentation says:
This function validates its parameters. If strDest, format, or timeptr is a null pointer, or if the tm data structure addressed by timeptr is invalid (for example, if it contains out of range values for the time or date), or if the format string contains an invalid formatting code, t... |
62,803,090 | 62,803,183 | Changing position of data in Input file to a .cpp program Changes output unexpectedly | This is what the code is for:
https://www.codechef.com/LRNDSA04/problems/STACKS
Here is the code snippet:
#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--)
{
int n; cin >> n;
vector<int> a;
... | In this check:
if(pos == a.size()) {
if(a[pos] > x) { // this is UB
if the condition is true, then you are indexing into an invalid position of a, which invokes undefined behavior.
It seems you want to do
if(pos != a.size()) {
instead. The conventional way to check for this condition is
if(it != a.end()) {
|
62,803,390 | 62,803,641 | How to get the calculate the RGB values of a pixel from the luminance? | I want to compute the RGB values from the luminance.
The data that I know are :
the new luminance (the value that I want to apply)
the old luminance
the old RGB values.
We can compute the luminance from the RGB values like this :
uint8_t luminance = R * 0.21 + G * 0.71 + B * 0.07;
My code is :
// We create a function... | You don't need the old luminance if you have the original RGB.
Referencing https://www.fourcc.org/fccyvrgb.php for YUV to RGB conversion.
Compute U and V from original RGB:
```
V = (0.439 * R) - (0.368 * G) - (0.071 * B) + 128
U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128
```
Y is the new luminance normalized to... |
62,803,597 | 64,217,094 | Title bar window appeared briefly in the 2nd window and would disappear a few seconds | I am using Qt Creator 4.5.2 (Qt 5.9.5, GCC 7.3.0 64-bit) and running on Ubuntu 18.04.
I created a Virtual Keyboard with C++ for my project and it worked fine. But, whenever the virtual keyboard appeared on the screen, its Title Bar window would appear briefly (a few seconds) on the top and then disappear. Why? How can ... | Found the answer myself:
Eventually, I found this is an Ubuntu issue and has nothing to do with QT.
Here are how to solve this problem:
Open an terminal in Ubuntu.
Enter "firefox".
Enter into search "noannoyance" and select NoAnnoyance - GNOME Shell Extensions.
Change the extension from Off to On.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.