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 |
|---|---|---|---|---|
66,652,761 | 66,652,872 | istringstream and reading float | This problem was also mentioned by this question.
I am reading a file line by line with std::getline.
std::getline(points_file, thisline);
std::istringstream iss(thisline);
int cnt = 0;
Coordinates.resize(NumberOfNodes, std::vector<float>(3));
for(std::istream_iterator<float> iit( iss );
... | Use push_back or a regular assignment (not >>) to store values in your container:
for(std::istream_iterator<float> iit(iss), iitEnd; iit != iitEnd; iit++)
{
assert( cnt < 3 );
// This means you SHOULDN'T pre-resize()
Coordinates[i].push_back(*iit);
//or
// This means you SHOULD pre-resize()
Coordin... |
66,652,812 | 66,654,790 | Stopping If statement from running entire code at once | I'm creating a password system for an encryption program.
For this i moved my main chunk of code inside an if statement, however now, instead of reading the code line by line, it simply prints it all at once. (e.g. when it comes to std::cout << "Enter here: "; std::getline(std::cin, userin); the user cant input anythin... | Just add std::getchar(); after std::cin >> pass
The problem is that when you enter pass and click enter, this enter keyboard will be considered as your next input. std::getchar(); receives the effect of enter keyboard. Now you can enter userin.
Note: Use std::getchar() only after you get a string by std::cin.
If yo... |
66,652,815 | 66,652,874 | Sorting a linear data structure in place | How do I convert this function into a function that sorts the list a in place? I currently have the following:
template<typename Iterator>
void LISTsort(Iterator curr, Iterator stop)
{
//how to sort in place
}
I failed to wrap around my head about how to "put" the values back to the list a. I know that I can use a... | std::list has a member function for sorting. It's called sort.
Is there any way to accomplish this without using any loops?.
Only way to sort without using loops (recursive or iterative) is to limit the size of the input to a constant.
|
66,653,090 | 66,696,728 | C++ - Simple hello world doesn't work in vscode | I've just started programming in c++ and I've a problem that is probably really simple but I've been trying to solve it for a long time.
Cout prints all built-in variables but when I try to print a string variable, it doesn't work (it doesn't print anything even if there are other couts with other things to print that ... | The solution to errors like "procedure entry point is not found" is:
Make a list of all .dlls located in your compiler's bin directory.
Go through C:\Windows and C:\Windows\System32 and make sure none of those dlls are there. If you find any, move them somewhere else (or delete them).
Add your compiler's bin directo... |
66,653,211 | 66,653,425 | With OpenGL 4.3, how do I correctly use glVertexAttribFormat/Binding? | I was trying to use this feature, here is what I did:
glGenBuffers(1, &m_vbo_id);
glGenVertexArrays(1, &m_vao_id);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id);
glBindVertexArray(m_vao_id);
glEnableVertexAttribArray(0); // Vertices
glEnableVertexAttribArray(1); // Color
glEnableVertexAttribArray(2); // Texture coordina... | The second argument of glVertexAttribBinding is not the buffer object, but the binding index.
The arguments of glBindVertexBuffer are the binding index, the buffer object, the offset and the stride. Stride is (3+4+2)*sizeof(float) for a tightly packed buffer:
int bindingindex = 0;
glVertexAttribFormat(0, 3, GL_FLOAT, ... |
66,653,884 | 66,655,092 | How to replace a function pointer with a template parameter or a std::function? | I run a sonarlint plugin in visualstudio.
I get a major problem about my code as below :
_declspec(dllexport) void GetInformation(void (add)(const char* pCarName))
{
add("N3-988");
add("N3-40");
add("N3-41");
add("N3-428");
}
The error is
cpp:S5205 : Replace this function pointer with a template parame... | It is not a real error, in a sense that you cannot use function pointer as a parameter. You can. Use of function pointers is discouraged for obscurity, flexibility and performance reasons. See https://jira.sonarsource.com/browse/RSPEC-5205 . So you may want to suppress it, if you are not concerned with these considerat... |
66,654,632 | 66,654,851 | Object level locking in c++ | Suppose I have two classes, P and S. Each of the objects of class P has a reference to an object of class S. Suppose there are a total 20 objects of class P, 10 of those have object S1 and the other 10 have object S2, where S1 and S2 are objects of class S. Is it possible to lock S1 and S2 separately such that two obje... | You can use std::mutex.
class S
{
std::mutex mutex;
...
};
This way, all references to S1 will be locked when S1.mutex is locked, and all references to S2 will be locked when S2.mutex is locked. This way they are locked independently. If you instead declare the mutex as static, it will give you the undesired effect,... |
66,654,724 | 66,676,643 | What does boost::hana::always do more than just "always return its first argument"? | At the doc page of boost::hana::always I read that
always(x) is a function such that
always(x)(y...) == x
for any y....
This makes me think that it shouldn't behave any differently than this lambda: [](auto const&...){ return false; }.
However it does. For instance, the following code prints 11, but if I change the ... | In fact, always has different overloads (as it handles reference as return value).
so, with a simplified version:
template <typename T>
struct my_always
{
T res;
template <typename ...&& Ts>
T& operator ()(Ts&&...) /* mutable */ { return res; } // #1
template <typename ...&& Ts>
const T& oper... |
66,654,865 | 66,657,708 | MFC MDI ID_FILE_OPEN Non override, but use the variable for status message | Preface: I have an MFC MDI using the wizard in VS2017 to create the project...it works without issue.
Goal: To use the ID_FILE_OPEN to execute normal document creation without modification but use the same ID to trigger my own function in parallel to write to the output tab at the bottom.
So here is what is happening. ... | Ok, I figured out a a more elegant way to handle this without compromising the solution and default framework.
Using this post here:
MFC trigger ID_FILE_OPEN command
I've reformed the message map:
BEGIN_MESSAGE_MAP(CApplication, CWinAppEx)
ON_COMMAND(ID_FILE_OPEN, OnFileOpen) // Leave active, not used, needed to ke... |
66,655,230 | 66,655,699 | if we had a single file project that contained all the code can we not use the linker? | Linker question:
if I had a file. c that has no includes at all, would we still need a linker?
| You can create a project, which has no typical C startup code, in which case, you may not even have a main(). However, you still need a linker, because the linker creates the required executable file format for the given architecture.
It also will set the entrypoint, where the actual execution starts.
So you can omit t... |
66,655,621 | 66,657,028 | Regular expressions. Search for words without repeating numbers | I need to write the code that will output words without repeating digits. By assignment, I have to use the char array. I decided to do this with regular expressions. At the moment I have this expression:
regex rx ("^(?!.*(.).*\1)[0-9]+$");
If you take each word of the string separately, then regex works, but if you wr... | You can use
\b(?!\d*(\d)\d*\1)\d+\b
See the regex demo. Details:
\b - a word boundary
(?!\d*(\d)\d*\1) - no repeating digits allowed in the number
\d+ - one or more digits
\b - a word boundary
See the online C++ demo:
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::... |
66,655,736 | 66,655,848 | C++ How to communicate with a joinable thread using std::promise? | I'm very confused as to how to implement std::promise for inter-thread communication.
Here's a small example. When I try to compile this I get the error "get is not a member of std::promise".
#include <iostream>
#include <thread>
#include <future>
void printer_function(std::promise<int>* the_promise)
{
// this fu... | You have mixed up the roles of std::future and std::promise.
std::future<T> is a placeholder for T result that does not exist yet. It generates std::promise<T> object into which the promised result should be placed.
In your case the printer function is the recipient of the result - use std::future.
The worker function ... |
66,655,757 | 66,656,106 | c udp socket not receiving/sending correctly | I am currently experiencing some trouble while testing UDP sockets.
So I have 2 c programs, one sends and receives, the other receives and sends a message.
Here is send_recv.c:
#define PORT 1010
int main(int argc, const char *argv[]) {
int socketInfo, opt;
struct sockaddr_in server;
char msg... | The problem is that both endpoints are listening on the same port while running on the same machine, and you have both sides sending to INADDR_ANY.
Also, port numbers below 1024 are privileged ports and therefore require root access to bind to.
Use a different port (1024 or higher) for each side of the connection, and ... |
66,656,033 | 66,656,534 | Declaring variable as i vs &i in the foreach loop | Why do these loops give the same output:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> ar = {2, 3 ,4};
for(auto i: ar) //this line changes in the next loop
cout<<i<<" ";
cout<<"\n";
for(auto &i: ar) //i changed to &i
cout<<i<<" ";
}
They both give t... | The results are the same because in the first loop you copy the variable's value in a new variable i and print its value. (Additional RAM allocated)
In the second loop you access the value of the current element from the memory by assigning its address to i. (No additional RAM allocated)
On the other side:
cout<<&i<<" ... |
66,656,076 | 66,656,229 | How can make pointer valid in std::set? | I have a self defined struct, which i overload the operator >:
struct A {
A(int a) : a_(a) {}
int a_;
friend operator > (const A& a) const {
return a_ > a.a_;
}
};
so i can push this struct into stl container set:
std::set<A> s;
s.insert(A(3));
s.insert(A(5));
s.insert(A(4));
but i am doing a large task,... | Use a custom comparator:
#include <iostream>
#include <set>
struct CustomCmp {
bool operator()(const int* lhs, const int* rhs) const {
return *lhs < *rhs;
}
};
int main()
{
int arr[] = { 3, 1, 4 };
std::set<int*, CustomCmp> mySet;
mySet.insert(&arr[0]);
mySet.insert(&arr[1]);
myS... |
66,657,016 | 66,658,228 | Why does `std::promise::set_value` throw an error when invoked from the main thread? | When I run the following code,
#include <future>
int main()
{
std::promise<int> p;
p.set_value(1);
return 0;
}
std::system_error is thrown. However, when I set the promise's value in another thread,
#include <future>
#include <thread>
int main()
{
std::promise<int> p;
std::thread([&]{p.set_value(... | std::promise is part of the Thread Support Library so it would stand to reason that it requires enabling thread support in your compiler options (e.g. -pthread).
Note that -pthread affects the compilation as well as linkage stages. From man g++:
-pthread
Adds support for multithreading with the pthreads library. This... |
66,657,199 | 66,658,687 | Checking for all instances of a character in a string? | #include <iostream>
#include <string.h>
#include "Header1.h"
using namespace std;
static const char * const wordDataBase[] = {"test","eee","office","minor","town","wrap","treatment","determined","blue","acrid","itchy","organic","impartial","frame","parallel","inconclusive","agreeable","stiff","obsequious","lonely","ext... | Here is a possible solution. I used std::strings because they're just simpler. I hold the actual word, and the player's progress in two strings. It's simply a matter of going through the solution with the guess, character-by-character.
int process_guess(char guess) {
int found = 0;
guess = std::toupper(guess)... |
66,657,387 | 66,665,857 | libvlc - http stream error: local stream 1 error: Cancellation (0x8) | I encounter a bug with libvlc where attempting to play video from YouTube result in error http stream error: local stream 1 error: Cancellation (0x8)
Context
C++ code:
#include <iostream>
#include <thread>
#include <vlc/vlc.h>
#include <vlc/libvlc.h>
#include <vlcpp/vlc.hpp>
int main() {
const char *const arg[] = ... | Since Youtube URLs are not like other URLs for VLC, in the sense that you give a HTML URL to VLC, and that VLC needs to parse that HTML page and reconstruct the actual video URL (that's what the lua script does), you cannot give the HTML URL directly to the mediaplayer as a media.
Create a media from the HTML URL, as y... |
66,658,227 | 66,666,021 | Trying to mimic the fsolve function from Python in a cpp scritp for simple functions | First of all, I'm new to C++. Tbh I find it very hard to "get used to" but the last week I have been trying to "translate" a script from Python to C++ due to computational time requirements.
One of the problem I have is root-finding of simple 1D functions:
First the simple MWE from Python:
Trying to solve ax^2+bx+c =... | What you need is to look into this similar issue with good explanation how to make it work error in GSL - root finding.
To help, you can use https://www.desmos.com/calculator/zuaqvcvpbz to view the function, and you can set initial values like this:
double x_lo = 0.0, x_hi = 1.0;
in your implementation to make it run;
... |
66,658,338 | 66,658,871 | How to use TEMPLATE_TEST_CASE with pairs of types? | I am trying to use catch2 TEMPLATE_TEST_CASE for pairs of types, i.e. instead of templating a single type for each test, I need to use a correlated pair of types. I thought I could use std::variant to store these pairs, but compilation fails with: error: expected primary-expression before ‘)’ token. auto outtype = std:... |
. instead of templating a single type for each test, I need to use a correlated pair of types.
If is only a pair of types, I suppose you can use std::pair; std::tuple, for more types.
I suppose you can try something as
TEMPLATE_TEST_CASE("test", "[test][template]", std::pair<OutputA, InputA>, std::pair<OutputB, Input... |
66,658,476 | 66,678,446 | How to use sha256 in c++ from cryptopp | First of all thank you for reading my question.
I am trying to reproduce what i recieved in python. So bsically I have two numbers and I am trying to make a hash out of them. But with crypto++ library i am a bit confused.
Basically I dont get how to use the update and calculate part.
My codes are
vHash(uint8_t *X,u... | I found the solution I am pasting it here So that it may be useful for someone else.
For calculating right sha256 first to update and then call the calculate function in the manner mentioned below.
hash.Update((byte*) X, 32 );
hash.CalculateDigest( digest, (byte*) y, 32 );
This is optional but to make sure what we are... |
66,658,783 | 66,659,121 | How to work with the C++ class members individually and at the same time as a whole? | I have following C++ code
Rectangle.h
class Rectangle {
public:
Rectangle(int _id);
void draw();
int getId();
private:
int id;
};
Rectangle.cpp
#include "Rectangle.h"
#include <iostream>
Rectangle::Rectangle(int _id) {
id = _id;
}
void Rectangle::draw() {
std::cout << "Drawing rectangle with i... | If you represent your Rectangle member variables instead as a std::array<Rectangle, 4> in your RectanglesCollection, you can then easily access them by index and an operator[](size_t) accessor member function.
#include <array>
#include <cstddef>
#include <iostream>
#include <stdexcept>
using std::array;
using std::cou... |
66,658,806 | 66,659,110 | clang-diagnostic-error - allocating an object of abstract class type 'Base' | #include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void foo() = 0;
protected:
int num{ 1 };
public:
Base() {
cout << "Base class constructor" << endl;
}
virtual ~Base()
{
cout << "Base class destructor " << endl;
}
private:
};
class ... | In your main() function, do this instead:
unique_ptr<Base> b(new Derive());
This is because std::make_unique() takes the actual constructor arguments. You can't do that with polymorphism, but there's nothing wrong with directly instanstiating a std::unique_ptr directly with a heap allocated resource.
Do prefer std::mak... |
66,658,816 | 66,659,091 | Writing file for each process of MPI | I have written this part of the code in order to have a file for each rank and see its content. The question I have is that how can I extend this code to work for an arbitrary size. Here, as I was running with 4 cores; I already knew my size so I wrote my code with 4 if conditions which I think there should be a better... | Because you are running with multiple processes in parallel you do not actually need to specify the conditions:
string local_string = to_string(rank) + base;
read the file with the name local_string
and print the content of the file to the output
If it for debugging purposes you might to want to add a condition so tha... |
66,659,359 | 66,659,430 | Clear struct, which is member of class in C++ | I want to clear a structure, which is a member of class. Example
struct MyStruct
{
int my_int;
char my_array[10];
};
class MyClass {
public:
MyStruct some_struct;
void myMethod() {
// Here I want to reset my structure
MyStruct = {};
}
};
My assump... | Your intuition is correct (but your syntax is off). MyStruct is an aggregate type and some_struct = {} is assignment to a value-initialized aggregate, which becomes zero-initialization because you are using an initializer consisting of empty braces {}. During zero initialization, each element of the array is zero init... |
66,659,548 | 66,659,694 | Socket UDP handling incoming payloads different sizes | i am struggling with handling paylods with different sizes in my udp socket.
My current idea is, find the biggest payload that can be produced, and make a buffer of that size for the socket. This wouldnt be future proof, if i increase my payloads it will fail or be annoying to change everytime. And secondly this would ... | Just use a max buffer of 65535 bytes, UDP packets can't be larger than that. No need to be tricky using a dynamically sized buffer. recvfrom() will tell you how many bytes it puts in the buffer. And honestly, 64K is small enough to not worry about it wasting memory, unless you are coding for an embedded device.
That b... |
66,659,692 | 66,660,819 | Will delete the pointer to pointer cause the memory leak? | I have a question about C-style string symbolic constants and dynamically allocating arrays.
const char** name = new const char* { "Alan" };
delete name;
when I try to delete name after new'ing a piece of memory, the compiler suggest to me to use delete instead of delete[]. I understand name only stores the address of... | As the comments above indicate, you don't need to manage the memory that "Alan" exists in.
Let's see what that looks like in practice.
I made a modified version of your code:
#include <iostream>
void test() {
const char** name;
name = new const char* { "Alan\n" };
delete name;
}
int main()
{
test()... |
66,659,993 | 66,660,275 | Convert char array to byte array | I have a string declared like so.
CHAR bkp[40] = "dc74699a8381da395f10b"; <- this value comes from querying a registry value
In memory (using VS memory window) I see..
0x00000071432FF918 64 63 37 34 36 39 39 61 38 33 38 31 64 61 33 39 35 66 31 30 62 00 .. .. .. ..
I am trying to convert the string to memory so that w... | You need to convert you character array to a binary. Your input array is a hex string so this is rather straigforward.
unsigned char toBinary(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
return (c - 'a') + 10;
}
CHAR bkp[40] = "dc74699a8381da395f10b"
unsigned char b[20];
int bi = 0;
for(int i ... |
66,660,055 | 66,660,587 | Can you instantiate a class and then assign a different class to it using new (e.g. class1 name = new class2) | I was watching a c++ tutorial about the "->" operator on youtube (the link ) in 2:48 of the tutorial. He wrote the code
int main()
{ScopedPtr entity = new Entity();}
from what I understand about instantiating class, the class behind new keyword should be the same as the class you are instantiating. Pls explain how thi... | Yes it may happen for instance when you create a pointer to an implementation of your classes where ScopedPtr is a pointer to the implementation of Entity.
You could have some documentation here or here
#include <iostream>
class Entity
{
public:
Entity(){}
//only for test
void print()
{
std::co... |
66,660,073 | 66,660,948 | The program has unexpectedly finished in QT opencv | I know that this has been posted many times,but I could not find the solution from previous posts. I followed tutorial on How to setup Qt and openCV on Windows from wiki Qt.
My .pro file and mainwindows.cpp are shown below. I wanted to open image following the example. What is wrong here? Checked the opencv version a... | When program crashes like that under Qt Creator, and you have extra libraries, the very likely reason is that the extra libraries are missing from the runtime PATH.
In this case, you need to add C:\opencv-build\bin to the PATH. There are at least 3 ways to go about it.
Edit the system environment, so that the relevant... |
66,660,151 | 66,661,052 | How to validate whether a c++ program is well documented using Doxygen format or not? | Is there a way for Doxygen to report whether source code is documented or not? Is there any way to identify the set of files which are not well documented in a set of C++ source files?
Coding Language: C++
Documentation Tool : Doxygen (This can be changed with some other open tool if it has an option for validation)
... | Doxygen already provides some useful configuration options:
WARN_IF_UNDOCUMENTED
If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag will automatically be disabled.
WARN_IF_DOC_ERROR
If the WARN_IF_DOC_ERROR tag is se... |
66,660,222 | 66,660,373 | Is it valid to return reference for artimetic operator overloading? | As we know, we normally return a copy to a new class when overloading an arithmetic operator. As an example, << operator is normally defined like this:
T1 operator<<(const T1& a, const T2& b) {
// apply b
return a;
}
But I wonder if it is generally valid to return a reference in this case or not. For example,... | Yes, it's not only valid, it's a common idiom when overloading << for stream outputs. For example:
std::ostream& operator<<(std::ostream& os, const MyData& data) {
os << data.a << ',' << data.b << ',' << data.c;
return os;
}
|
66,660,337 | 66,660,631 | Why this code for anagram is not giving correct result only for ravi & vira? | In this program i am trying to sort the string by their ASCII values by taking them as a integer. And then sort them in ascending order and check if they have the same set of elements
#include<iostream>
#include<string.h>
using namespace std;
int len(int a[]){
int l=0;
for(int i=0; a[i]!='\0'; i++)
l++... | There is a bug in your sort.
I removed most of the unnecessary code and kept your sort logic (working example):
#include <algorithm>
#include<iostream>
#include<string>
using namespace std;
void asc_order(string a){
char temp=0;
for(std::size_t i=0; i < a.length() ; i++)
for(std::size_t j=0; j < a.leng... |
66,660,497 | 66,660,604 | In template, no type named type in "std::result_of<int&()>" | i am new to C++ programming, and am confused as to why i cannot supply my template parameters to intialise a packaged_task in cpp.
#include <vector>
#include <queue>
#include <chrono>
#include <thread>
#include <cassert>
#include <future>
using namespace std::chrono;
using std::future;
using std::packaged_task;
using ... | packaged_task wraps a callable object, if you pass aFunc(), you're passing the result of the call, which is an int, in your case it's the same as writing:
packaged_task<task_type> pt{10}; // does not make much sense, right?
If aFunc was a free function (not a member-function), you could pass its address to the package... |
66,660,527 | 66,661,784 | From template parameter to constructor argument | Does C++17 (or earlier but not c++20) allow this?
I need a type_traited conditional class, like a bitset with an internal 32 or 64 unsigned integer storage, depending if the template argument N is lesser then 32 or greater (please forget about more than 64 bits).
But the constraint is to finally implement two and only ... | A new hypothesis, CTAD based
#include <cstdint>
#include <iostream>
#include <type_traits>
template <std::size_t>
struct BitSet;
template <>
struct BitSet<32u>
{
template <typename ... Ts>
BitSet (Ts...) {}
std::uint32_t value;
};
template <>
struct BitSet<64u>
{
template <typename ... Ts>
BitSet ... |
66,660,601 | 66,661,464 | error: no matching function for call to Constructor with NULL as argument? | I get the following error when I try to initialize a Team in main() doing:
Team gt(NULL);
error: no matching function for call to 'Team::Team(NULL)'
I'm unsure of how to go about this, as its a test case, so I can't change it.
I have other subclasses of Team, but I'm not sure how to go about actually initializing a ... | Since you say Team represents a NULL-terminated chain of Team objects, you need a linked-list of Team* pointers, where the last pointer in the chain is NULL.
Try something more like this:
class Team
{
public:
// Each team has a pointer to the next team to forward to
// by default, a team is inactive
Team() = defa... |
66,661,009 | 66,661,085 | Including a .c file in a c++ program | I am working on a project where half my code is in c and half is in c++.
Now I want to include the cprogram.c in my cppprogram.cpp.
When including a c file inside a c program you can use
#include "cprogram.c"
Anyways to do that in c++ for including a c program.
| Besides from that you normally don't include .c files, but .h files instead, and that the following is bad practice, you can include C files into .cpp / .hpp files by wrapping the include into an extern "C":
cppprogram.cpp
extern "C" {
#include "cprogram.c"
}
See here for some examples.
|
66,661,066 | 66,661,241 | How do i flip a number half triangle in c++? | I need to code this in c++ using nested for loops. click thisAnd this is what I have right now.
#include <iostream>
#include <map>
using namespace std;
int main() {
int i, j, k, n = 9;
for(i = n; i >= 0; i--){
for(j = i; j >= 0; j--)
cout << j<<" ";
cout <<endl;
}
}
how do I flip it.
| Currently you are starting with the longest row and going down. Start with the shortest row and go up:
#include <iostream>
int main() {
int n = 9;
for(int i = 0; i <= n; i++){ // start with 0 and go up to n
for(int j = i; j >= 0; j--)
std::cout << j << ' ';
std::cout << '\n';
}
}
To flip in the oth... |
66,661,261 | 66,662,764 | C++ wrapper for the Observer pattern | C++ newbie. I have a class with a vector of listeners following the observer pattern. Listeners inherit from an abstract class defining different methods like on_start, on_stop, on_such_event, etc. These methods are not having the same signature.
I'd like to write an event processing method and call from it, when appro... | You could write a function in this manner:
template <typename ...Params, typename ...Args>
void notify_listeners(void (MyBase::*method)(Params...), const Args &... args)
{
for (MyBase *listener : all_listeners)
(listener->*method)(args...);
}
Where MyBase is a class that all listeners inherit from, that ha... |
66,661,559 | 66,661,666 | How to convert char(or string, other type) -> bits? | In c++,
I don't understand about this experience. I need your help.
in this topic, answers saying use to_string.
but they say 'to_string' is converting bitset to string and cpp reference do too.
So, I wonder the way converting something data(char or string (maybe ASCII, can convert unicode?).
{It means the statement ca... | Q: What is a bitset?
https://www.cplusplus.com/reference/bitset/bitset/
A bitset stores bits (elements with only two possible values: 0 or 1,
true or false, ...).
The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is ... |
66,662,486 | 66,663,081 | How to look for certain keywords in a document and read them into the program (C++) | I've been given a document, from which I have to read certain Information into my C++ program that are preceded by appropriate Keywords looking like this:
...
*useless information*
...
KEYWORD_A : VALUE_A
...
*useless information*
...
KEYWORD_B : VALUE_B
...
What would be the most efficient/correct way for filtering t... | Ok, I'll take a shot
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::ifstream inp("inp.txt");
std::string word;
using valueType = std::string;
//Assuming keywords only appear once in the file
std::unordered_map<std::string, valueType> keywords {{"... |
66,662,602 | 66,662,725 | strrev not working when comparing in an if statement | PD: I am forced to learn "strrev()" as this is part of my bachelors degree, please do not consider recommending me "reverse()".
int n = 0, str, revc=0;
char a[256], v[101][21], *p, sep[]=" :;.,", rev[256];
cin.get(a, 256);
p = strtok(a, sep);
while(p){
strcpy(v[n++], p);
p = strtok(NULL, sep);
}
fo... | strrev() alters the content of the passed char[] in-place, and then returns a pointer to that same char[]. It DOES NOT allocate a new string, like your code is assuming. Thus, the statement:
stricmp(strrev(v[i]), v[i])
Will always return 0, since you are comparing the content of v[i] to itself.
To do what you are at... |
66,662,643 | 66,664,097 | Calculate a sum of an array in Arduino | I am trying to code something where you store 5 integers in an array and then calculate the sum of the 5 stored values. Then the 5 values are printed and also the sum.
I tried this:
const int sizeOFarray = 5;
int b[sizeOFarray] = {10, 20, 30, 40, 50};
int sum = 0;
void setup ()
{
Serial.begin(9600);
}
void loop ()... | In your code:
const int sizeOFarray = 5;
int b[sizeOFarray] = {10, 20, 30, 40, 50};
int sum = 0; // you initialize sum once.
void setup ()
{
Serial.begin(9600);
}
void loop ()
{
// on the first pass sum == 0, no problem.
// on the second pass, sum still holds the sum of values in the array.
// to which you... |
66,663,260 | 66,663,307 | Boost optional conversion from string to uint problem | Could someone explain why the first conversion works and the second with optional does not ?
// Example program
#include <iostream>
#include <string>
#include <boost/optional.hpp>
int main()
{
std::string x = "16";
uint16_t t = (uint16_t)std::stoi(x);
std::cout<<t; // prints 16
std::string x2 = "16";
bo... | boost::optional is kind of like a pointer. It's name, in this case opt, can be converted to a bool and it will be true if it has a value and false otherwise. This is why std::cout<<opt; prints 1. To get the value out of the optional, you can "dereference" it like
std::cout << *opt;
and now you get 16 instead of 1.
|
66,663,303 | 66,663,949 | properly forward a parameter pack in a lambda without discarding qualifiers | I am trying to store lambda functions in a queue to execute them later. In order to do that, i am trying to hide the parameter pack in a lambda without losing scope so I can still access the passed arguments in an upper scope.
Sadly I cannot compile this since the parameter pack does not match the const qualifier.
I ho... | What happens is, here [task, args...] the references are lost; task, args... are captured by value, which, in a non-mutable lambda additionally become const, which subsequently can't bind to non-const references in the call to [&](class_a & a, class_b & b).
You can capture the references by reference. Don't worry about... |
66,663,399 | 66,663,627 | Ways of deleting pointers in a vector [C++ ] | std::vector<Circle*> circles
for(int i=0; i<circles.size(); i++) // 1
delete circles[i];
for(auto & circle : circles) // 2
delete circle;
for(Circle * circle : circles) // 3
delete circle;
for(Circle *& circle : circles){ // 4
delete circle;
If I write it the first way, C... | For completeness, there's one more way:
for(auto circle : circles)
delete circle;
Now, all these ways in this example are equivalent and will do the job of deleting circles elements equally well.
Having a reference to a pointer doesn't matter (the reference is "unwrapped" in expressions - in technical terms an lva... |
66,663,472 | 66,663,497 | C++ turn a std::tuple<char, char, char> into a std::string? | I am writing a lightweight parser combinator library (akin to Boost::Spirit) as hobby project.
One thing I'd like to do, is to automatically be able to convert a Result<std::tuple<char>>, Result<std::tuple<char, char>>, etc. into a std::string.
And similarly, if having e.g. a Result<std::tuple<int, int>> I'd like to be... | template <typename... Ts>
std::string tuple_to_string(const std::tuple<Ts...>& t)
{
return std::apply([](auto... cs)
{
return std::string{cs...};
}, t);
}
live example on godbolt.org
More generic solution:
template <typename T, typename... Ts>
T tuple_to_container(const std::tuple<Ts...>& t)
{
... |
66,663,722 | 66,663,872 | Function that finds prime numbers between two intervals | I have written the bulk majority of the program, I'm just having trouble debugging it. Something must be wrong with my computation of the prime numbers. For anything I try, it says there are 0 prime numbers. Any help would be greatly appreciated. Code and output are below.
Note: For this program, I am not allowed to us... | is_prime has two issues.
If sqrt(num) is less than 2 the loop never executes and your function has undefined behaviour as it ends without returning (your compiler probably should have warned you about this issue)
If the number is not even then in the first iteration of the loop you call return 1 which means all odd nu... |
66,663,920 | 66,665,150 | Horner algorithm implementation in c++ | Implement the Horner algorithm for determining the value of the polynomial. Input data should be given as program parameters: polynomial coefficients and value.
Below is an example call:
/horner 1.0 2.2 -3.3 7.0
-145.3
counts the value of W (7.0), where W (x) = 1.0 + 2.2x ^ 1-3.3x ^ 2
Turn this:
double Horner(int n, do... | Assuming to call the function in the first snippet with the parameters n = 2, A[] = {1.0, 2.2, -3.3} and x0 = 7.0, if we would track its execution, we'd find:
w = A[n] = A[2] = -3.3
i = n - 1 = 1 // <----- Note this.
w = w * x0 + A[1] = -3.3 * 7.0 + 2.2 = -20.9
w = w * x0 + A[0] = -20.9 * 7.0 + 1.0 = 145.3
In the sec... |
66,664,230 | 66,664,231 | Gtkmm Custom Widget throws error when building from Glade file | I have made a custom widget and have struggled all afternoon due to the lack of documentation to get a custom object that extends Gtk::Entry to work. I have gotten to the point where I can add the widget in Glade. I am now getting an error:
terminate called after throwing an instance of 'Gtk::BuilderError'
Upon loading... | As it turns out in the course of writing the question I figured out my issue.
I had forgotten to register my custom objects before trying to use them.
I needed to call custom_widgets_init() prior to calling Gtk::Builder::create_from_file("glade/window_main.glade");
|
66,664,311 | 66,664,374 | 0 divided by 0 results in 1 in g++ 10.2 | The following code prints gcc says: 0 / 0 equals 1 when compiled with g++ 10.2:
#include <iostream>
int main() {
int a = 0;
std::cout << "gcc says: 0 / 0 equals " << (a / a) << std::endl;
return 0;
}
Run it on godbolt
Is this supposed to be this way? (Compiling with clang and executing it returns 136 - Erroneo... | Division by zero is undefined behavior. The compiler will proceed to do whatever makes the code run fastest. And it won't even be consistent about it.
There is no way to make this result in a compiler error, because the compiler won't always know if the denominator is 0 at compile time. You have to do the checks yours... |
66,664,841 | 66,665,066 | Undefined behavior of constexpr static cast from int to scoped enum with non-fixed underlying type compiles in C++17 | I wonder if the following should or should not compile in C++17
enum class E
{
A, B
};
constexpr E x = static_cast<E>(2);
This compiles with both GCC 9.3.0 and Clang 10.0.0 on Ubuntu 20.04.
My question is
Should this compile?
If it should, why?
I don’t think it should.
There are many posts regarding undefined b... | Scoped enums always have fixed underlying type. [dcl.enum]/5 (C++17):
For a scoped enumeration type, the underlying type is int if it is not explicitly specified. In both of these cases, the underlying type is said to be fixed.
So your E has fixed underlying type of int. Then in paragraph 8:
For an enumeration whose... |
66,664,883 | 66,664,933 | Why can't I access the object I created on the heap? | I'm trying to learn C++ and one thing is not clear to me. I know that the new operator creates an object on the free store, so if an object within a block is created with new, it won't be destroyed after the scope ends. But in the following example I cannot access the object allocated by new after the block. What am I... | The new object isn't destroyed. But the only pointer to it is gone, because it is destroyed (which does nothing to what it points to, aside from deny you access to it).
You can see how the allocation survives the block by declaring the pointer outside the block, while still performing allocation within it:
#include <io... |
66,664,955 | 66,665,259 | Looping over a templated C++ function with int type | Is there a solution like this to loop over a function with a templated int parameter that doesn't require creating a new struct with a body() function any time forIdx is needed with a new function? Templated lambdas in C++20 seemed promising, but it didn't seem possible to specify template parameters that aren't automa... | "Templated lambdas in C++20" have you said?
Do you mean something as follows?
#include <iostream>
#include <type_traits>
template <std::size_t I>
void loop_func()
{ std::cout << I << ' '; };
int main ()
{
[]<std::size_t ... Is>(std::index_sequence<Is...>)
{ (loop_func<sizeof...(Is)-Is-1u>(), ...); }
(st... |
66,665,901 | 66,665,967 | call of overloaded 'write(int)' is ambiguous | Right now, i am trying to print a special character to my LCD screen. for some reason- this message appears: call of overloaded 'write(int)' is ambiguous
I have no idea what this means, and help would be great.
Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
byte customChar[] = {
B01110,
B01... | LiquidCrystal is a subclass of Print which has two write() methods:
virtual size_t write(uint8_t); and size_t write(const char *str). With a parameter of 0 either of those could be called hence it is ambiguous.
Try casting to the type you want: write(static_cast<uint8_t>(0))
|
66,665,903 | 66,666,007 | How to make ASIO resolve IP address without knowing the service/port? | How could I get ASIO to resolve a domain name without supplying the port/service name?
As far as I know, ASIO requires a port number or service name while resolving. Why? How would I do something like nslookup example.com? And not supplying the service name simply makes ASIO generate the error "tcp::resolver: service n... | I would pass an arbitrary service port. Like "1". And just ignore that.
To be very purist you can tell the query that the service need not be resolved:
#include <boost/asio.hpp>
#include <iostream>
int main() {
using boost::asio::ip::tcp;
using query = tcp::resolver::query;
query q("www.example.com", "1",... |
66,666,184 | 66,666,638 | Idiomatic DirectX12 structure initialization breaks on C++20 | With MSVC
m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(...));
works fine on C++17 but on C++20 (Preview - Features from the latest working draft) I get the error:
error C2102: '&' requires l-value
Does anyone know how it's not causing an error on 17? Do we just keep using C++17 for now?
ht... | This only compiled before because of an MSVC language extension which has now been turned off by default. Quoting from Conformance improvements in Visual Studio 2019 version 16.8 - 'Class rvalue used as lvalue' extension:
MSVC has an extension that allows using a class rvalue as an lvalue. The extension doesn't extend... |
66,666,798 | 66,667,039 | How does this recursive overload of the insertion operator (operator<<) work? | I'm in the process of learning about recursion. The below is a recursive overload of the insertion operator for a class which provides a linked list of integers. It compiles and runs, but I'm confused as to why.
When overloading the insertion operator, I understand that you normally return an ostream reference so that ... |
it seems that you would be trying to insert an ostream into an ostream
Nope. Your << operator returns an ostream, but it does not mean that you're inserting it into another ostream.
every step you take in the recursive function, you insert something in the ostream and return the same ostream. See:
out << node->value;... |
66,666,894 | 66,672,326 | Three-way operator <=> return struct with implicit conversion function | Consider the following useless code:
struct S{
constexpr operator int() const { return 0; }
constexpr auto operator<=>(S) const { return *this; }
};
static_assert(S{} <= S{});
Clang and MSVC accept this code but GCC rejects it with an error message:
error: no match for 'operator<=' (operand types are 'S' and 'int... | From [over.match.oper] (3.4.1 and 8):
For the relational ([expr.rel]) operators, the rewritten candidates include all non-rewritten candidates for the expression x <=> y.
and
If a rewritten operator<=> candidate is selected by overload resolution for an operator @, x @ y is interpreted as [...] (x <=> y) @ 0 [...], ... |
66,666,978 | 66,667,058 | Can i make base class's deconstructor called before derived class's deconstructor? | I have a base class and a derived class, like:
class Base {
virtual ~Base();
};
class Derived {
~Derived() {
// for some reason, i need base's deconstructor called before derived's
}
}
the normal call order of deconstructor is : ~Derived(); ~Base();
but for some reason, i need to call ~Base() first, how can ... | You can't. Deconstructors are called in reverse order of construction automatically by the compiler.
|
66,666,982 | 66,667,102 | C++ filt not working. C++ name demangling | a symbol in linkmap file
0x10AEB7A48 0x00000034 [14199] __ZZZZZZZZZZN5kinda16FillCardInfoPage6renderEvENK3$_2clENSt3__110shared_ptrINS_12MMViewLayoutEEEENKUlNS3_INS_12MMScrollViewEEEE_clES7_ENKUlS5_E_clES5_ENKUlS5_E_clES5_ENKUlS5_E_clES5_ENKUlS5_E_clES5_ENKUlS5_E_clES5_ENKUlNS3_INS_14MMBankEditViewEEEE_clESF_ENUlRKNS3... | You need to add single quote around the command-line argument, to prevent the shell from expanding the dollar sign ($) in it.
|
66,667,115 | 66,667,308 | What does comparator return really mean in C++ | I am trying to do stable sort in C++ and my array is like this
{{first = "art zero", second = "let3 "}, {first = "own kit dig", second = "let2 "}, {first = "art can", second = "let1 "}}
sort(let.begin(), let.end(),
[](pair<string,string>& a, pair<string,string>& b) {
int comp = a.first.compare(b.first);
if(!c... | If you simply choose std::map as your container, the default ordering provides storage in lexical sort order, e.g.
#include <iostream>
#include <string>
#include <map>
int main (void) {
std::map<std::string, std::string> let {{"art zero", "let3 "},
{"own kit dig", ... |
66,667,174 | 66,667,296 | Why am I not able to use the unordered_map in lamda function ? What is the data type of arguements being passed there? | Here is my code which sorts the string on the basis of frequency of chars.
string frequencySort(string s) {
unordered_map<char,int> umap;
for (int i=0 ; i<s.size() ; i++)
umap[s[i]]++ ;
sort (s.begin() , s.end() , [umap] (char a , char b) {
if (umap[a] ... | The lambda's function call operator () is by default set to const so you must either pass the map by reference (&umap or &), or use the mutable keyword to make the operator () non-const and pass by value ([umap]() mutable{} or [=]() mutable{}):
Passing the map by reference:
#include <iostream>
#include <algorithm>
#inc... |
66,667,227 | 66,668,351 | Getting WA in Google Kick Start Round A: (Workout Problem) | Problem Description
Tambourine has prepared a fitness program so that she can become more fit! The program is made of N sessions. During the i-th session, Tambourine will exercise for Mi minutes. The number of minutes she exercises in each session are strictly increasing.
The difficulty of her fitness program is equal ... | Simply splitting by two an interval and replacing it by its two parts cannot work.
For example, your code fails with n = 2; k = 2; [1 7]. Your code answer is 3, but 2 is the correct answer.
The idea is to keep trace of the original interval size and the number of times the original interval was split in, together with ... |
66,668,047 | 66,668,160 | C++ forward declare class constructor with initialization list | I am trying to separate my classes into header and implementation files:
This works:
header.hpp
class MyBaseClass {
public:
MyBaseClass(int arg1, int arg2);
};
class MyDerivedClass {
public:
MyDerivedClass(int arg1, int arg2, int arg3);
};
implementation.cpp
MyBaseClass::MyBaseClass(int arg1, ... | In the MyDerivedClass you want to call the MyBaseClass constructor, not declare it, so just pass the arguments down, don't try to declare them. So remove the int before arg1 and arg2.
class MyDerivedClass : public MyBaseClass {
public:
MyDerivedClass(int arg1, int arg2, int arg3) : MyBaseClass(arg1, arg2) {... |
66,668,579 | 66,669,182 | Is it possible to access child types in c++ using CRTP? | I have this toy example,
template <typename TChild>
struct Base {
template <typename T>
using Foo = typename TChild::template B<T>;
};
struct Child : Base<Child> {
template <typename T>
using B = T;
};
using Bar = Child::Foo<int>;
which fails to compile. The intention is that I have a parent class t... | Let me post another way to do it:
template<typename TChild, class T>
struct GetB {
using Type = typename TChild::template B<T>;
};
template<typename TChild>
struct Base {
template<typename T>
using Foo = typename GetB<TChild, T>::Type;
};
struct Child : Base<Child> {
template<typename T>
using B =... |
66,669,464 | 66,670,135 | Deep copy unsuccessful | might be a stupid question and if it is, let me know, I will delete it as soon as possible. The thing is I have to make a deep copy in class "Kambarys" (ignore mixed languages, I know I shouldn't do that). Program terminates after trying to call function second time. Probably the problem is my syntax in constructor cop... | You have to allocate memory for k2 and copy the object, not the pointer.
You have to allocate memory in the copy constructor and copy assignment operator.
door=NULL; before delete door; would skip the delete and cause a memory leak.
windows.clear(); is not necessary in the destructor. Keep your code simple.
EDIT: After... |
66,669,651 | 66,669,940 | Substracting a string from an int | I following code illustrates the use of c_str function
#include <iostream>
#include <string.h>
using namespace std;
int main() {
std::string str("Hello world!");
int pos1 = str.find_first_of('w');
cout<< "pos1: "<< pos1 <<endl;
int pos2 = strchr(str.c_str(), 'w') - str.c_str(); //*
//int pos2 =... | .c_str() returns the address to the start of the string. strchr the address to the first occurence of a specific character inside the given string or a nullptr, if the character is not found.
If you subtract one address from another, you get the distance of the to pointers, which is the offset of the character inside t... |
66,670,096 | 73,560,154 | Example uses of hint parameter in the implementation of an allocator | Standard allocators can optionally hints as default parameters https://en.cppreference.com/w/cpp/memory/allocator/allocate
T* allocate( std::size_t n, const void * hint);
Leaving aside that this is formally deprecated in C++20 (which apparently doesn't mean that an allocator cannot have the hint argument):
Do you know... | Work by Alin Jula and Lawrence Rauchwerger
The paper "Two memory allocators that use hints to improve locality" by Alin Jula and Lawrence Rauchwerger from 2009 introduces
Two locality improving allocators that can use allocation hints
provided from the C++ STL library and outperform state-of-
the-art allocators, such ... |
66,670,394 | 66,682,537 | QT c++: drop in multi line edite | Im beginner in qt and i do my first project. I am encountering a problem.
I put somes edit line in a scroll area. All of this edit text should countains path to files. To make this app more userfriendly i decided to implement a drag and drop. By this way, users can just take a file from their explorer and drop it to li... | Ok i find a solution. I dont really like it because i dont find it really clean but that works. If others have cleaner solution im open to it. I put my solution here. Maybe that could help someone in the future. I finaly didn't use drop methode but i used an eventFilter which give me the posibility to have a better man... |
66,670,995 | 66,671,469 | A c++ class include a static member with the same type of itself. Why this pattern? | I inherited a project from a former colleague, and I found these code snippets (and some similar ones in SO questions: can a c++ class include itself as an member and static member object of a class in the same class)
// Service.h
class Service
{
// ...
public:
static Service sInstance;
void Somememberfunc();
/... | Notice that the member is a static, so it's part of the class, not of instantiated objects. This is important, because otherwise you would be trying to make a recursive member (since the member is part of the object, it also contains the same member and so on...), but this is not the case here.
The best pattern to desc... |
66,671,078 | 66,671,474 | couldn't interface C++ and Qml (connections) | I am working on a project on my raspberry pi 4 that uses GPIO.
I cross compiled Qt 5.14.2 and I created a QtQuick application
so I am working with the wiringPi library, I followed this tutorial https://www.youtube.com/watch?v=HxNHlhv74tA and I created a GPIO class that contains a private attribute m_value (it didn't wo... | When you emitted a signal to Qml side, you can reach the emitted parameter by its name. If you change the code like:
Connections
{
target: input3
onInputChanged:
{
if(value ==0 )
rectInput3.opacity = 0.0
else
... |
66,671,366 | 66,671,762 | C++ variables and where they are stored in memory (stack, heap, static) | I've just begun learning C++ and I wanted to get my head around the different ways to create variables and what the different keywords mean. I couldn't find any description that really went through it, so I wrote this to try to understand what's going on. Have I missed anything? Am I wrong about anything?
Global Variab... | Mostly right.
Any variable that is accessed with a pointer is stored on the heap.
This isn't true. You can have pointers to stack-based or global variables.
Also it's worth pointing out that global variables are generally unified by the linker (i.e. if two modules have "int i" at global scope, you'll only have one g... |
66,671,872 | 66,672,083 | C++ does this function cause a undefined behavior? | Hello i think this is causing an undefined behavior but not sure
PlayerMoving *unpackPlayerMoving(BYTE *data)
{
PlayerMoving *dataStruct = new PlayerMoving;
dataStruct->packetType = *(int *)(data);
dataStruct->netID = *(int *)(data + 4);
dataStruct->characterState = *(int *)(data + 12);
dataStruct->... | The behaviour of your code is undefined.
Even if BYTE is an unsigned char type (unsigned char is an exception to the strict aliasing rule), there is no guarantee that
*(int *)(data + 4);
and so on meets the alignment requirements for an int.
Your best bet is to memcpy the data from the BYTE array to each structure mem... |
66,672,068 | 66,673,013 | How to call a C++ member function in python (SWIG)? | I want to expose my C++ library class to python and be able do call any function contained in that class in python.
My example Library looks like this:
#include "example_lib.h"
lib::lib(){};
int lib::test(int i){
return i;
}
With the header:
class lib{
lib();
int test(int i);
};
My interface file:
/* example_lib... | Default accessibility is private in C++, you then need to move it in a public: section :
class lib{
public:
lib();
int test(int i);
};
Also note that test is a instance method, you need to instantiate the class.
|
66,672,987 | 66,673,004 | integer overflow in c++ | can you explain why i am getting an integer overflow in first code but not in second?
#include<bits/stdc++.h>
using namespace std;
#define ch "\n"
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int g = (1000000 * 2) * 1000000;
// long long int k = f * 1000000;
cout << g % 10... | All the literals in (1000000 * 2) * 1000000 are int types, and the compiler is warning you that this overflows the int on your platform.
It doesn't matter that you are assigning the result of this expression to a different type.
One solution is to use (2ll * 1000000) * 1000000 which forces the implicit conversion of th... |
66,673,542 | 66,758,822 | Do I have to block signals on the main thread to handle cancel point on another thread? | When I was working on a TCP server running in a dedicated thread, I noticed strange behavior in signal handling. I have prepared the following MWE (I've used cerr to avoid race condition on debug printing):
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include <chrono>
using namespace... | As you noticed, my problem was that sigaction() has been connect signal handler to both main() thread and runSelect() thread so SIGINT signal could be caught by main().
Now I have prepared a version in which only the main thread handles SIGINT signal and sends SIGUSR1 signal to specific threads with pthread_kill().
#in... |
66,674,463 | 66,674,723 | Nested generation of comparison operator with three-way operator? | Consider the following two overload operator<=> for S:
#include <compare>
struct S {};
int operator<=>(S, int) { return 0; } #1
S operator<=>(S, S) { return {}; } #2
If I compare an object S with an int, the #1 will generate the right operators for me, so expression like S{} <= 0, 0 < S{} or 0 <=> S{} would be ... | This is ill-formed, although admittedly the error message is quite confusing.
The rule, from [over.match.oper]/8 is (emphasis mine):
If a rewritten operator<=> candidate is selected by overload resolution for an operator @, x @ y is interpreted as 0 @ (y <=> x) if the selected candidate is a synthesized candidate with... |
66,675,078 | 66,677,003 | How to use in c++ a dll created in visual studio without visual studio |
I have made a c++ dll with visual studio, I succeeded to use it with visual studio but i can't find how to use it with just vscode or more generally with just command line. My goal is to put my library on github with the documentation explaining how to use it but i am not able to compile a program in command line.
I t... | The short answer is, you can't.
You can't use a C++ DLL generated by compiler A from compiler B and vice-versa, because they generally don't use the same ABI (application binary interface).
To keep explanations short, several of these elements probably differ (this isn't an exhaustive list):
The organisation of object... |
66,675,534 | 66,675,681 | C++ pattern for pointer deletion? | I was wondering if there was a pattern for the deletion of pointers. More specifically when you need to call some kind of intermediate function for data. Here is a example of what I was thinking:
int main() {
// some code here
char* return_of_function1 = function1(int_array);
int return_of_function2 = func... | The general practice is to move away from raw pointers the way you're using them. If your char * is really a string, then use std::string, for instance.
RAII stands for Resource Acquisition is Initialization. What matters for this is that you wrap your resources with an object, and you let the object go out of scope. I... |
66,675,648 | 66,675,821 | Force a derived class to override one of a set of virtual functions | Given a base class which has some virtual functions, can anyone think of a way to force a derived class to override exactly one of a set of virtual functions, at compile time? Or an alternative formulation of a class hierarchy that achieves the same thing?
In code:
struct Base
{
// Some imaginary syntax to indicate... | No, but you can fake it.
Base has non-virtual float and int methods that forward to a pure virtual std variant one.
Two helper classes, one int one float, implement the std variant one, forwarding both cases to either a pure virtual int or float implementation.
It is in charge of dealing with the 'wrong type' case.
Der... |
66,675,912 | 66,676,893 | How to pass an Auto variable as input to another function | I really want to pass a variable that is auto (function) as input in another function.
Here is a structure that receives parameters for my xroot f:
struct my_f_params {
double flag;
auto inter_auto(double x, double y);
};
Here is the function I essentially want to have (it's based on a GSL library, so the fo... | auto is just a placeholder for a compiler-deduced type, depending on the context in which auto is used.
In your example, you can't use auto as the return value of my_f_params::inter_auto(), because the compiler has no way to know what type inter_auto() actually returns, so it can't deduce the type of the auto. You wou... |
66,675,925 | 66,676,039 | Why do we include header files and not source files? | I've seen similar questions asked yet they still do not make sense to my ape brain.
Here is an example. If I declared a function in a header file named Bob.h: void PrintSomething(); and in the .cpp file I say: void MyClass::PrintSomething(){std::cout << "Hello";} . I've seen people in another .cpp file for example Fran... | The moment you include Bob.h the compiler has everything it needs to know about PrintSomething(), it only need a declaration of the function. Frank.cpp does not need to know about Bob.cpp which defines PrintSomething().
All of your individual cpp files output object files generated by the compiler. These in themselves ... |
66,675,988 | 66,677,041 | Create inherited object based on runtime value | Is there a way in C++ to create an instance of class based on runtime argument ? Here is code example :
class base
{
public:
base(int a) : a_(a) {}
virtual void print()
{
cout << "base";
}
int a_;
};
class A : public base
{
A(int a = 5) : a_(a), base(a) {}
void print() override
... | The short answer to your question (Is there a way in C++ to create an instance of class based on runtime argument?) is yes. The response to what you don't want is "unfortunately you don't have a choice."
However, this is mitigated by doing it in a function that you only have to write once. The code below is a simple fa... |
66,676,246 | 66,676,631 | std::sort of polymorphic types not sorting as expected | I have taken sample code from ch9 Open Closed Principle in Agile Software Development, as below, which is supposed to sort shapes by precedence in the order given by the table typeOrderTable in the code below. Well, I did have to add a main and test code but pretty much copied the book code. But the output shows it is... | You need to change your call to std::sort(...) to use a comparator. The way you have it, it is pointers to shapes being sorted not shapes so the operator< defined for shapes will not be called, instead the numeric values of the pointers will be compared.
One way to fix this is to sort like this
sort(orderedList.begin()... |
66,676,248 | 66,676,439 | Do while loop.. right now: infinite, goal: not infinite (ask until loop) | So when i enter a char or string, it asks the question again but infinitely... but i want it to ask once every time wrong, then again if wrong. Get it... ? :( right now the loop is infinite.
#include <iostream>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
cin >> ... | You are not validating and clearing the cin stream's error state. Try this instead:
#include <iostream>
#include <limits>
using namespace std;
int main() {
float money;
do
{
cout << "How much money do you have? " << endl;
if (cin >> money) {
// a valid float value was entered... |
66,676,676 | 66,678,504 | Qt qOverload - undeclared identifier | I'm trying to learn to use QComboBox, I tried to compile a chunk of code from https://zetcode.com/gui/qt5/widgets/ but I always get the same error message “use of undeclared identifier 'qOverload' ”
I red all I can find about it on the net, but nothing helped.
I'm using Qt Creator 5.15 and C++11.
combobox.h :
#pragma o... | I checked the qt documentation for qOverload and you might require C++ 14 and you might need to insert this in your .pro file-> CONFIG += c++14.
Reffer to the link for more details:-
http://doc.qt.io/qt-5/qtglobal.html#qOverload
But you can still work around this using the helper methods ,since in c++11 you can use the... |
66,676,695 | 66,677,006 | How can I do this table in C++? | I tried to make a C++ algorithm to show me this:
1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4
1 2 3 4 5
And that can be to the infinite, depends by the cin number.
So I made this:
#include <iostream>
using namespace std;
int main()
{
... | #include <iostream>
using namespace std;
int main()
{
int n,i,j;
cin >> n;
for(i=1;i<=n;i++)
{
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
for(int k = i+1; k <= n; k++) {
cout << i << " ";
}
cout << endl;
}
return 0;
}
Hope,... |
66,676,771 | 66,676,853 | Passing "Alias" to functions in C++ | How to pass something like this to a function
using PIN1 = GpioOutputB1;
using PIN2 = GpioOutputB2;
using PIN3 = GpioOutputB3;
using PIN4 = GpioOutputB4;
using PIN5 = GpioOutputB5;
passing these PIN1, PIN2 ... etc to a function like this.
static void initilize() {
PINx::setOutput();
}
Sorry that I am not including th... | What about as template parameter?
template <typename PINx>
static void initilize () {
PINx::setOutput();
}
En passant: I suppose that setOutput() is a static method.
Given that (in this example) PINx can't be deduced, you have to call initialize() explicitly passing the type
initialize<PIN3>();
Take also in count ... |
66,677,113 | 66,677,438 | std::is_trivially_copyable / std::is_trivially_copy_assignable and array wrapping classes | I am trying to wrap my head around std::is_trivially_copy_assignable<T> and std::is_trivially_copyable<T>.
As far as I understood, std::is_trivially_copy_assignable<T> checks for a trivial (non-user defined, default) copy operator, whereas std::is_trivially_copyable<T> checks to see if it safe to use memcpy on Type T. ... | It's important to note that the rules for trivially copyability for standard-defined types (like arrays) are different from those of class types. For standard-defined types, they are trivially copyable by fiat: because the standard says that they are.
An array of elements of the type T is trivially copyable to the exte... |
66,677,195 | 66,679,425 | C++ Unable to call template class function after passing it to another function | I have an Observable template.
template<typename T>
class Observable {
public:
~Observable() {
observers.clear();
}
void registerObserver(const std::shared_ptr<Observer<T>> & observer) {
observers.push_back(observer);
}
void update(const T & record) {
for (auto &observer: observers) {
obs... | You are inserting null pointers and you push those in the list:
// catObserver is nullptr
auto catObserver = std::shared_ptr<CatObserver>();
Indeed, just like creating a raw pointer with no parameter, it will be null:
CatObserver* rawCatObserver{}; // null
To actually create a CatObserver, you have to call std::make_... |
66,677,343 | 66,677,837 | c++ How to put path from command line argument to fprintf | I am having trouble figuring out how to take a path from the command line argument and having my program write to that folder using fprinf. For example: /here would write the file to the "here" folder with /here being the path from where the program is to where it needs to be written. Same for if the path were /there/h... | Here's an example using std::filesystem (C++17):
void write_file(int sockfd, const char* path)
{
auto filename = std::filesystem::path(path) / "file1.txt";
std::ofstream out{ filename, ios::trunc | ios::out };
if (!out) {
std::cerr << "ERROR: " << std::strerror(errno) << "\n";
exit(EXIT_FAIL... |
66,677,696 | 66,677,784 | difficulties with handling big matrices in c++ | I try to work with a - not even tooooo - colossal matrix in C++ but there seems to be a memory problem and I could need some help.
The following code compiles without a warning with g++ -Wall -Wextra -o matrix main.cpp
But when I want to run it, I get the following message: zsh: segmentation fault ./matrix
My compiler... | Of cause std::array is not suitable for VERY large matrix if you place it on stack, like you did. Stack is limited and sometimes it may be below 1MB in size.
Try using std::vector or allocate std::array on heap. Heap is not limited, it can grow almost up to size of whole RAM.
Next example is using std::vector, on my ma... |
66,677,748 | 66,679,140 | Mingw g++ shows garbage output, while it runs in other IDEs and Ubuntu g++ | I have a simple C++ code, it is giving garbage values when executed in my friend's Windows 10 machine with Mingw g++. But it gives a correct output when executed in my Ubuntu(g++) and various other online compilers.
g++ --version
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Soft... | As @drescherjm pointed out in the comments,if (dist[i][j] > dist[i][k] + dist[k][j]) was causing overflow (when used with long).
This was working for other compilers and not on the windows machine with MinGW g++ because it allocated 4 bytes for long. It worked with long long as it allocated 8 bytes for long long and he... |
66,677,850 | 66,678,248 | Is there a way to implement generic function in C++ without the use of templates and without the use of void pointers? | I want to know that can we implement a function whose instance can be created for different data types during runtime but we are not allowed to use either templates or void pointers.
Any help is appreciated.
| Yes, use a macro.
#define instantiate_generic_function(Type) \
void myGenericFunction(Type param) { \
std::cout << param; \
}
and then instantiate like thus:
instantiate_generic_function(int)
This makes a series of overloaded functions named myGenericFunction
Another option that Jarod42 reminded me that there's ... |
66,678,231 | 66,678,309 | why it does not give proper result when member function is called without values | why my code does not work when i call the gett function and try to print the output(second code)
where as it gives proper output when i pass the argument from main(first code). I called my function using rs.power(arguments) in first and in second using get function i am getting - output in the second code
code-1
#inclu... | In the second code block, you haven't done anything to compute result.
Try
rs.gett();
rs.power();
rs.display();
I would recommend using:
#include <iostream>
#include <cmath>
using namespace std;
class powm
{
public:
double result;
public:
// Make sure constructor initializes the member variables ... |
66,678,501 | 66,678,810 | Why do we need to decrement iterator while deleting from vector? | I have a below program. I need to understand why do we need to decrement pointer when we use erase method?
Also is there any better way which does not create a such confusion ?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myvector{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (a... |
I need to understand why do we need to decrement pointer when we use erase method?
You don't, and shouldn't. The correct thing to do is use the return value of erase. At the moment your program has undefined behaviour because you are modifying an invalid iterator.
for (auto i = myvector.begin(); i != myvector.end();)... |
66,678,544 | 66,678,771 | defining preprocessor definitions on a single file | I'm in the process of migrating a project to C++17. There are a couple instances of old code with deprecation warning not within my control. An example of one of these warning is, _SILENCE_CXX17_SHARED_PTR_UNIQUE_DEPRECATION_WARNING. In visual studio, I've been adding these to properties->Preprocessor Def. So far thi... |
is there a way to minimize the scope of the preprocess definition down to a single file?
Yes, it is possible to have different preprocessor macros for a single file in Visual Studio.
In the Solution Explorer, RMB -> Properties on a specific file to change its properties.
|
66,678,665 | 66,678,788 | Can I cache after using std::make_shared? | I am reading Effective Modern C++ (Scott Meyers) and trying out something from item 21. The book says a side effect of using std::make_shared is that memory cannot be freed until all shared_ptrs and weak_ptrs are gone (because the control block is allocated together with the memory).
I expected that this would mean tha... | It is true that when you use std::make_shared the storage for the new object and for the control block is allocated as a single block, so it is not released as long as there exists a std::weak_ptr to it. But, when the last std::shared_ptr is destroyed the object is nonetheless destroyed (its destructor runs and its mem... |
66,678,982 | 66,679,063 | Thread Safety of Shared Pointers' Control Block | I am working on a small program that utilizes shared pointers. I have a simple class "Thing", that just is an class with an integer attribute:
class Thing{
public:
Thing(int m){x=m;}
int operator()(){
return x;
}
void set_val(int v){
x=v;
}
int x;
~Thing(){
std::cout... | In a multithreaded environment, use_count() is approximate. From cppreference :
In multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed load)
The control block for shared_ptr is otherwise thread-safe :
All member functions (including copy const... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.