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,264,241 | 62,264,490 | I am trying to get this output but its showing wrong output from a website but my answer is correct | With the help from a website I am trying to solve the question of data types but I am getting wrong answer even my answer is right in output
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int a;
long b;
char c;
float d;
double e;
scanf(" %d %ld %c %f %lf",&a,&b,&c,&d,&e... | You made mistakes somewhere. You added extra spaces and did not add newline.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int a;
long b;
char c;
float d;
double e;
scanf("%d %ld %c %f %lf",&a,&b,&c,&d,&e);
printf("%d\n%ld\n%c\n%0.3f\n%0.9lf\n",a,b,c,d,e);
retu... |
62,264,743 | 62,264,848 | access to an object member passed by unique_ptr | I wrote the following code to check if a node is in the BST:
bool BST_Node :: BST_Find(unique_ptr<BST_Node> root, int key){
if(!root || root->key == INT_MIN) return false;
if(root->key == key) return true;
else if(key < root->key) BST_Find(move(root->left), key);
else BST_Find(move(root->right), key);
... | Try this
bool BST_Node :: BST_Find(unique_ptr<BST_Node> const &root, int key){
if(!root || root->key == INT_MIN) return false;
if(root->key == key) return true;
else if(key < root->key) return BST_Find(root->left, key);
else return BST_Find(root->right, key);
}
BST_Find(bst, 42) // no move
|
62,264,951 | 62,278,236 | handle logical "OR" for predicates in std::enable_if<...> | Say, I have this return type definition for my method (template and method are irrelevant hence not shown), which requires handling logical "OR" for enable_if predicates:
typename std::enable_if<{predicate_1} or {predicate_2}), void>::type>
my_method(...) { ... }
Naturally it won't work, as once either of predicate su... | Suppose you are using SFINAE like this to check if a type has either a T::bar or a T::type and either of them should be int:
template <typename T>
typename std::enable_if<
std::is_same<typename T::bar,int>::value ||
std::is_same<typename T::type,int>::value, void>::type asdf(){ std::cout << "0";}
template <typ... |
62,264,983 | 62,265,102 | Why is std::invocable concept blocking this code from compiling | I do not understand why neither the lambda nor the function are recognized as an std::invocable compliant types in the following code:
#include <concepts>
#include <iostream>
void f( std::invocable auto callback)
{
callback(47);
}
void function_callback(int i)
{
std::cout << i << std::endl;
}
auto lambda_cal... | If you look at the definition of invocable (or in the standard):
template< class F, class... Args >
concept invocable =
requires(F&& f, Args&&... args) {
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
/* not required to be equality preserving */
};
What this means:
void f( std::invocable a... |
62,265,006 | 62,265,300 | How do I compare elements of vectors in C++? | I currently have this code:
std::vector<std::string> words { "apple","banana","broccoli","lettuce" };
std::vector<std::string> disliked_words { "broccoli","carrot","tomato","lettuce" };
for (int i = 0; i < words.size(); i++)
if (words[i] == disliked_words[0] || words[i] == disliked_words[1] || words[i] == dislike... | Use a nested loop (loop in another loop).
std::vector<std::string> words { "apple","banana","broccoli","lettuce" };
std::vector<std::string> disliked_words { "broccoli","carrot","tomato","lettuce" };
for (unsigned int i = 0; i < words.size(); i++){
for(unsigned int j=0;j<disliked_words.size();j++){
i... |
62,265,522 | 62,268,755 | serial read changes input & doesn't read whole line | Large strings sent over serial are not correctly read using an Arduino Uno and the Arduino IDE. When the typed command is too long, not the whole data is returned and sometimes is is even random numbers.
99,3,0,1,0,0,0 Results correctly in (not sure why there is an ending , tho):
receivedValues are: 99,3,0,1,0,0,0,
99... | I found the solution to this problem. Changing uint8_t was not the answer.
A byte of 8 binary bits can represent 28 = 256 numbers: 0 - 255. The
serial connection sends data byte by byte, so if you want to send a
number larger than 255, you'll have to send multiple bytes
Link to source:
https://forum.arduino.cc/in... |
62,265,646 | 62,265,782 | Error C2711 building DLL from a C++ project that uses tbb | I'm trying to build some dll to wrap some Computer Vision methods in a c++ software to use them a c# software, and I need to call some tbb (Threading Building Blocks) methods from the c++ methods to process some frame. I'm developing in CLR using Charset Unicode, in visual studio, and once I call the tbb header
#inclu... | This sounds like you're trying to build an application using CLR, but it doesn't like some of the code in tbb's header. Error C2711 happens when trying to compile code as managed that it is unable to manage (for example, using inline assembly).
If you don't need CLR, you should just be able to disable it (remove /clr)... |
62,265,693 | 62,265,778 | Getting substring of wchar_t[] | I have:
wchar_t str[32];
I want to get a new substring of it, from place 0 to 5. How can I do it?
| std::basic_string does have the constructor you're looking for:
constexpr basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
So you may do:
std::wstring substr{str, 5};
|
62,265,706 | 62,265,968 | how can i count digits of a number using recursion? | yes i know other ways to count digits and returning to main function from the recursion function, but i'd like to print it in the void function. im having difficulty with it. could somebody help?
#include <iostream>
using namespace std;
void recursive_function(int num)
{
int sum=0;
while(num!=0){
recurs... | If you do not want to use the return-stack to count your digits, you will need to pass the current count throughout the call stack as function parameter:
void recursive_function(int num, int count=1)
{
if (num>=10) {
recursive_function(num/10, count+1);
} else {
cout<<count<<endl;
}
}
|
62,265,769 | 62,265,847 | meaning of these pointers, pointer-to-pointer, function pointer and array pointer | I'm a university student, our teacher told us to tell the meaning of these pointers, but I only manage to figure out some of them:
1. int *p1;
2. int *p2[10];
3. int (*p3)[10];
4. int (*p4)();
5. int **p5();
6. int (**p6)[10];
7. int (**p7)();
8. int *(*p8)();
9. int (*p9[10])();
10. int **p10[10];
This is what I've f... | cdecl.org can be used to decipher messy declarations like your examples:
int (*p9[10])(); => declare p9 as array 10 of pointer to function returning int
Failing that, you can use Clockwise/Spiral Rule to grind through them manually.
|
62,266,115 | 62,266,359 | C++ - object padding intricacies | I'm trying to understand struct and class padding in depth, so I devised an example I considered more challenging than many of the examples I found in tutorials on the topic. I compiled it in an x64 machine with g++, without enabling any code optimization. My code is as follows:
class Example
{
private:
lon... | You forget about the final padding. sizeof returns a number of bytes between two adjacent members in an array. In your case, alignof(long double) is very likely 16, therefore each Example instance requires to be at 16-byte aligned address.
Consequently, if you have first instance of Example at a 16-bytes aligned addres... |
62,266,250 | 62,269,349 | Problem with the copy constructor of an class holden in boost::variant | I've tried to construct a tree structure using boost::variant and now I have some problems.
I implemented a copy constructor in the class holden in boost::variant and call the copy constructor
just like this code:
#include <iostream>
#include <boost/variant.hpp>
struct Hoge{
int i;
Hoge(int j) : i(j){};
Hoge(Hoge con... | You're not copy constructing: that would be like saying:
var hogehoge = var(hoge); // elided assign of copy-ctor
Or indeed just
var hogehoge(hoge);
var hogehoge = hoge;
So, what you need is to SAY you want a Hoge to copy,
var hogehoge = boost::get<Hoge>(hoge); // may throw if `hoge` holds int
So you copy-construct H... |
62,266,291 | 62,266,989 | C++ value initialized vector iterator comparison | Is the following code legal in c++17?
std::vector<int> x{1,2,3};
std::vector<int>::iterator it{};
bool result = x.begin() != it;
The following is quoted from https://en.cppreference.com/w/cpp/named_req/ForwardIterator :
Equality and inequality comparison is defined over all iterators for the same underlying sequence ... | Visual Studio is correct. You are getting an assertion (in debug only!) because your code has undefined behaviour, and the implementation is warning you about that.
Value-initialised iterators can only be compared to other value-initialised iterators. This is a generalisation of the rule that comparing pointers or iter... |
62,266,445 | 62,318,404 | How to get extended port information when enumerating ports using Windows API | I'm using some legacy code to enumerate ports on my machine:
#include <windows.h>
#include <devguid.h>
#include <setupapi.h>
#include <string>
#include <iostream>
#include <assert.h>
bool GetTextProperty( std::string& sProperty,
HDEVINFO dev,
_SP_DEVINFO_DATA* pDeviceInfo... | With the help of Ben Voigt and Simon Mourier, I could achieve this, here is the piece of code:
// More includes:
#include <initguid.h>
#include <devpkey.h>
#include <cfgmgr32.h>
// A new dependency:
#pragma comment (lib, "Cfgmgr32.lib")
bool GetDeviceProperty( const std::string& what,
DEVINST ... |
62,266,642 | 62,266,747 | How can i read from a vector of strings in c++ | for example how can i read just the first character of the first string:
vector <string> vec= {"aa","ab","abc","efg"};
Thank you.
| You can read it like this:
std::vector <std::string> vec = { "aa","ab","abc","efg" };
std::vector<char> result;
for (auto it = vec.begin(); it != vec.end(); ++it)
{
result.push_back((*it)[0]); // (*it)[0] == vec[i][0]
}
Now result is a vector of first elements of each string
|
62,266,682 | 62,266,770 | c++ find() returning a different value when stored as a variable | I was helping someone with some homework when I came upon something strange.
I don't use C++, but I figured the function find() would work like any other language.
However, in the first example below, an email with the name ericsomthing@gmail.com does not evaluate to false when looking for a space using find(' ').
if (... | .find(' ') >= 0 is a bad comparison.
I'm guessing you expect that find will return -1 if it can't find what you're looking for? When you cast the result to an int (which you're implicitly doing when you assign it to an int variable), it will be -1. But the return type of find is actually unsigned, so if you just look a... |
62,267,113 | 62,267,652 | C++: Behavior of abstract union and new placement operator? | It's my understanding a union's size is that of the largest member on that union. Does anyone know how a union behaves when a non-fixed size container such as a string is added to it? What is the size? Also, how does the size change when the new placement operation is used? Thanks!
Here is an example:
#include <str... |
It's my understanding a union's size is that of largest member on that union.
Not quite exactly. If one member has stricter alignment requirement, and another member is larger, but not a multiple of the mentioned alignment, then the total size of the union may be larger than either member.
Does anyone know how a uni... |
62,267,378 | 62,267,486 | How do I feed a byte array with null characters into a std::iostream? | I have to feed a byte array, which contains null characters, into a derivative of std::iostream. The raw data looks as follows:
FF 73 00 05 73
I stored this chunk of data into a char array:
char *tmc_command = new char [5]; // array size may vary
SerialStream tmc_receiver_handler; // a derivative of std::iostream
tm... | The ostream inserter operators are for formatting. If you do not want to print your data as a formatted string, the formatted insertion operator is not what you want.
Try using the ostream write() member function instead.
|
62,267,577 | 62,267,651 | Why does adding 1 to numeric_limits<float>::min() return 1? | How come subtracting 1 from float max returns a sensible value, but adding 1 to float min returns 1?
I thought that if you added or subtracted a value smaller than the epsilon for that particular magnitude, then nothing would happen and there would be no increase or decrease.
Here is the code I compiled with g++ with n... | std::numeric_limits<float>::min() returns the smallest normalized positive value. To get the value that has no value lower than it, use std::numeric_limits<float>::lowest().
https://en.cppreference.com/w/cpp/types/numeric_limits/min
|
62,267,732 | 62,267,936 | Is there a downside to including a cpp file over a header file? | I understand that header files have their uses, especially in the case of interfaces, but is there any reason you shouldn't include a cpp file directly? You can still use include guards and/or pragma once inside a cpp so is there really any reason besides maybe going against standard practice?
| We have header files for a reason. It (mostly) separates the interface of some code from its implementation. Some of the benefits include the compiler having to go through less code and not having to recompile every file that uses a function when you change its definition. Including source files can also violate ODR as... |
62,267,821 | 62,281,760 | C++Concurrency in action:Can the Listing7.6(An implementation of pop() using hazard pointers) really detect nodes that can't be reclaimed? | I'm reading the book C++ Concurrency in Action. There is an example of using hazard pointer to implement a lock-free stack data structure. I am really puzzled, can the implementation of pop() really detect nodes that can't be reclaimed? The code is as follows:
std::shared_ptr<T> pop()
{
std::atomic<void*>& hp = get_h... |
Now, hp of thread A have not changed, but old_head points to b.
Yes, but only temporarily after the compare_exchange attempt. Thread B has updated head via its compare_exchange to b, so when thread A attempts to pop a, the compare_exchange fails and updates old_head to point to b, but then thread A starts another ite... |
62,267,826 | 62,268,143 | How to parse the division of two very large numbers into a double? | I have a geometric algorithm which takes as input a polygon. However, the files I am supposed to use as input files store the coordinates of the polygons in a rather peculiar way. Each file consists of one line, a counterclockwise sequence of the vertices. Each vertex is represented by its x and y coordinates each of w... | If you are after a ratio of two large numbers as string, you can shorten the strings:
"194725681173571753193674" divided by "635482929374729202" is the same as
"1947256811735717" divided by "6354829293" to at least 9 digits (I just removed the same amount of digits on both sides). Depending on the needed precision, thi... |
62,267,856 | 62,267,993 | KernelBase.dll exception code 0x0EEDFADE (but no crash) when Visual Studio is NOT run as administrator (GLFW/glad application) | I'm using Visual Studio 2019 and have the following simple OpenGL program as a minimal example (using GLFW and GLAD):
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
void error_callback(int error, const char* description) {
std::cout << "GLFW error: " << description << " (" << error << ")\n";
}
... | According to Google, that's the OS exception (structured exceptions) code used by Delphi. Since you aren't writing in Delphi, it's likely some program written in Delphi is hooking into all running processes. When you run in admin mode, your process is sufficiently privileged that the hook can't touch it.
If you want ... |
62,267,859 | 62,274,946 | Application with multiple windows in Qt | What is a good way to create application with multiple windows in Qt? Something like GIMP. I have already read this answer and it is not what I need.
I have two windows, one with controls and one with OpenGL inside. Right now I have something like this:
int main()
{
// some code
MainWindow mw;
mw.show();
... | You are doing right, but with the following simple tricks, you can resolve both issues that cause you do not like your right method:
To activate both windows, just do as follows:
MainWindow mw;
mw.show();
mw.activateWindow();
GLWindow gw;
gw.show();
gw.activateWindow();
To resolve the quit ... |
62,268,109 | 62,268,821 | Variadic template as first arguments | I want to write a generic template function that accepts and calls a number of different functions and performs additional setup and teardown operations. The functions signatures differ in the first arguments, such as:
void foo(int i, void* self, (*callback)(void*, int i));
void bar(bool s, bool r, void* self, (*callba... | Depending on your use-case, you can either accept callback and self as first arguments, before a parameter pack, and then merge those two in proper order:
#include <tuple>
#include <functional>
template <typename F, typename... Ts>
void wrap(F f, void* self, void (*callback)(void*, int), Ts&&... ts)
{
// change se... |
62,268,207 | 62,268,532 | Change base class from derived class permanently? | So, my problem is that i want to modify my parent class Board from a derived class in such a way that it applies to all other objects of the derived class. Ex. If I input a 3 on getTest() in players[1] players[2] will be able to print that same value. Is this posible?
class Board {
public:
int test;
... | It is indeed possible to share state between all instances that derive from Board.
As mentioned in the comments, if Board::test were given the static storage-class duration, this would be a variable shared across all instances of Player and any other classes that derive from Board now and forever. Technically, the vari... |
62,268,765 | 62,269,256 | Please find out the error in my code it is working for all my test cases still while submitting getting the wrong answer |
here is the link to the problem https://www.codechef.com/JUNE20B/problems/CHFICRM I have two written two different codes both are working fine according to me but still getting wrong answer this is my second approach.
https://www.codechef.com/JUNE20B/problems/CHFICRM
please some can help me ou.....
#include <bits... | In practice, a simple iterative procedure seems needed.
At a given instant, just count the number of "5" coins and "10" coins available.
#include <iostream>
#include <vector>
int main() {
int t;
std::cin >> t;
while (t--) {
int n;
std::cin >> n;
std::vector<int> arr(n);
... |
62,268,820 | 62,268,853 | c++ reference: What is the difference in the two statements? | I am confused by the meaning of the codes.
int x= 25;
x = int &y; vs int &y=x;
I tried testing it out and noticed one of the case is an error. But i do not get the difference between the two codes.
| the first case is not a legal code in C++.
in the second one, you are telling the compiler to give x another name which is y.
That's called reference
|
62,269,513 | 62,277,117 | How to go back to previous step in c++ | I am a C++ beginner and I am making a tool where I can access all my selfmade tools. But the problem is that if I press something and go back I can't choose another option.
for example if I choose '3' and go back I cannot acces '1' or '2' Does someone know a solution? I want to do this with multiply steps.
thanks!
... | It looks like you are populating the firstchoice twice - once in the beginning of the while loop and once when you prompt the user at the end of choices 2 and 3. You only need the one in the beginning. And I would recommend decomposing your code a bit like shown.
#include <stdio.h>
#include <cstdio>
#include <iostream>... |
62,269,718 | 62,270,264 | Best practices for creating a two dimensional array of std::strings | I am new to c++ and learning how to declare, use and delete a two dimensional array of std::string.
Because this is a learning exercise I am ignoring the idea of using vectors (for now).
I wrote a program that creates a small two dimensional array, adds data and then deletes the 2d array trying to use best practices al... | If the second dimension of your array is constant, I think you can be fine using a single new and delete operators. Something like this:
#include <stdio.h>
#include <string>
int ROWS = 3;
const int COLS = 4;
typedef std::string arr4[COLS];
int main()
{
arr4 *a;
a = new arr4[ROWS];
for (int ... |
62,270,389 | 62,290,590 | Accessing assets from C++ plugin through Flutter | I'm trying to use Google Oboe for a 3D audio processing app due to it's low latency. The app will have a C++ backend, which does the processing, and the frontend is done with Flutter. I'm running a couple of tests to see if it'll work but I'm having issues loading assets from Flutter to Oboe. I checked the example Rhyt... | 1 - what format is your WAV file in? Is it 32 bit floats? Don't forget that WAV files have a header, so you should discard the first few tens of bytes (up to the data segment). Be sure that you start reading the audio data on a float boundary (which may not be a multiple of 4 if the header isn't). If necessary, just us... |
62,270,842 | 62,280,937 | Gtkmm Window is blank, not showing any widgets or title | I'm learning gtkmm in order to program Conway's Game of Life as a demo. Currently I'm trying to show two buttons in a header bar, and I'm following a tutorial, but nothing is showing up in the window. Here's my code:
Display.h:
#include <gtkmm/window.h>
#include <gtkmm/headerbar.h>
#include <gtkmm/button.h>
class Disp... | The problem is that you are not using constructor delegation correctly. Try to write your default constructor as follow instead:
Display::Display()
: Display(600, 600) // Delegate here, not in body...
{
}
and it should work. Note that this is a C++11 feature.
|
62,271,085 | 62,271,267 | Visit all std::variants in a list and capture an additional value for every visit | I'm trying to implement a state store, which is basically a map of key-value pairs where the value is a std::variant.
The following class works fine. Note that it not only prints the visited value, but also the keys:
class StateStoreTest
{
typedef std::variant<float, std::string> StateValue;
private:
std::map<... | It seems to me that as follows should works
template <typename L>
void VisitAllValues (L const & visitor)
{
for (auto& it : States)
{
auto key = it.first;
std::visit([&](auto&& value) { visitor(key, value); }, it.second);
}
}
Off Topic: maybe using std::forward is you use forwarding references... |
62,271,258 | 62,413,985 | LLVM ORC V2 Symbol to Global Variable | I am trying to access a variable in the host program from LLVM IR, with a global variable, but I am having problems getting it to work. I am declaring a symbol with the required variable address in the main JitDylib. After that I create the Global variable with the same name, with external linkage so the linker can fin... | A JITDylib needs to be told to search for symbols in the host program like so:
JD.addGenerator(cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess(DL.getGlobalPrefix())))
Your method of defining absolute symbols should also work. However, I don't think you need to mangle the variable name in this case. You al... |
62,271,596 | 62,271,742 | Why can I use memcpy to copy one object variable to another | I have this class
class TestClass
{
public:
int* tab;
};
int main()
{
TestClass a;
a.tab[0]=8;
a.tab[1]=5;
TestClass b;
memcpy(b.tab,a.tab,sizeof(int)*2);
cout << b.tab[0] << endl;
return 0;
}
and I want to copy tab from a to b tab. But this code doesn't work.
I tried to copy tab to ... | You're causing undefined behavior by trying to use the subscript operator with an uninitialized pointer. Instead of doing any of these, use std::vector or std::array, depending on what you are trying to achieve:
#include <iostream>
#include <vector>
class TestClass
{
public:
std::vector<int> tab;
};
int main()
{
... |
62,271,914 | 62,271,938 | copy constructor and shallow copy | I wrote the following code to see shallow copy. I was expecting v2 to be a shallow copy of v1 since no copy construtor is defined , so I was hoping that changing v1.n would also cause v2.n to change, but it didn't. What I am doing wrong?
#include<iostream>
using namespace std;
class Vector
{
public:
int n;
flo... | You are not doing anything wrong, it's just that a shallow copy of an int is still a copy.
v1, and v2 have their own copies of n, and changing one won't change the other.
If you want to see the shallow copy behavior that you expect, use the pointer v. This copy only copies the pointer, not the memory it's pointing to, ... |
62,272,008 | 62,272,052 | Changing values in arrays of a different class | (c++ problem) I have two classes A and B, and the main class(int main). I have an array in class A. In the main class, I want to make a change to the array in class A. When class B reads the array from class A, it should read the changed values. However, changes to the array I make in class A through int main take effe... | If you want changes to the array in A to be visible globally, then you can make array a static variable like this:
class A {
public:
static int array[5];
// ...
};
int A::array[5] = { 0,0,0,0,0 };
From c++17, you could also define array inside the class:
class A {
public:
inline static int array[5] = { ... |
62,272,015 | 62,274,692 | Access Violation using ReadProcessMemory to get a string value | I'm new to reverse engineering, and quite new to C++. I'm trying to collect a player's character name in a game using ReadProcessMemory() from the Win32 API, but it throws an exception whenever I try to read it:
if (procId != NULL) {
hprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procId);
ModuleBase = getMod... | First, you need to determine whether the string you want to read is a wide-byte (wchar) or multi-byte (char) version, then you could use std::string/char* or std::wstring/wchar_t*.
Second, do not use sizeof(std::string), you need to determine the length of the string you want to read.
For wide-byte:
&(std::string)name ... |
62,272,409 | 62,276,664 | Build C++ code for Linux environment with Intel C++ compiler in Azure DevOps build pipeline | I'm seeking advice on how to build C++ code for Linux environment with Intel C++ compiler in Azure DevOps build CI pipeline. It's a common practice if using gcc instead of Intel C++ compiler. But when it comes to Intel c++ compiler, any advice to have a license (either named user or floating) integrated into the build ... |
But when it comes to Intel c++ compiler, any advice to have a license
(either named user or floating) integrated into the build process?
For your scenario, it's recommended to use Self-hosted agent instead of Hosted agent.
Here's the list of preinstalled software in Microsoft-Ubuntu-hosted agent, we can find that it ... |
62,272,452 | 62,272,567 | C++ Will a lambda shallow copy const Type& if it is given a named capture like [copy=val](){}? | I'm doing some work that requires multiple frames to process and I want to know if the named copy-by-value syntax for lambdas will copy the data from a const ref, or if it will create a new refernce to that data. In my case the data is on the stack and I need the lambda to hold on to a copy of the data.
consider the v... | Capture by value works like any other assignment by value. In your example, the lambda's copy member will be a copy of the FData that in refers to, copy will not be a reference to that FData. It doesn't matter that in is itself a reference, because copy is not a reference.
You can easily prove this without resorting ... |
62,272,549 | 62,272,596 | using functions of non-static class functions in C++ | I have a class containing several functions, and I would like to be able to use functions of these functions. When I try to do something like the code below, I keep getting the compiler error message "invalid use of non-static member function".
class MyClass{
protected:
void f(int a, int b);
void g... | Yes, you just need to accept a pointer to member function, not a regular function.
Change the definition to:
void MyClass::do_something_with_function(int count,
void (MyClass::*func)(int, int)) {
// ...
func(1, 2); // and use func
}
(and the declaration must be changed as ... |
62,272,584 | 62,278,789 | Does an atomic acquire synchronize with mutex lock release? | I have an object that stores some settings in an unordered_map with string keys and variant values. As my library might be used from several threads and reads will very likely outnumber writes by a large margin, I've thought about a copy on write implementation where the "get" operation is lock free and the "put" opera... |
will the atomic acquire synchronize with the mutex unlock which is a "release" operation?
No, in order for an acquire operation to synchronize-with a release operation, the acquire operation has to observe the changes of the release operation (or some change in a potential release sequence headed by that operation).
... |
62,272,590 | 62,272,672 | fixing shallow copy with a copy constructor | I defined a copy constructor to avoid having a shallow copy of the data member n, but it is not working, v2 is still getting changed when I change v1, what I am doing wrong?
#include<iostream>
using namespace std;
class Vector
{
public:
int *n;
Vector();
Vector(const Vector& vector );
};
Vector::Vector()
{
... | The problem is that your copy constructor is implemented wrong. You try to fix the shallow copy issue, but your code includes a statement that re-introduces the same issue again.
On this line:
n=new int;
You correctly allocate a new int, which is fine.
But on this line:
n=vector.n;
You are throwing away the int you ... |
62,272,695 | 62,272,862 | Generate random .txt file, 10 rows, 10 columns. Filled with randomised: "*","#","@". Then replace random character with 'P' | I'm beginner in C++. Learning mostly from YouTube courses. I was doing the task when I came across the problem which stops me from finishing. I would like to ask for help with the part of code.
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstrea... | The problem is that there are CR, LF characters (\r\n) at the end of each line, which shouldn't be touched. But you generate a random number between 0 and 119, which can hit those and damage the file.
I can think of 2 possible solutions:
loop and get a new random number if the remainder of dividing by 12 is >= 10 (you... |
62,272,838 | 62,281,239 | C++ :: how to capture matrix created by void function | I usually code in python, but due to combinatorial explosion, I decided to use C++ for a problem. My idea is to save numpy array in a npy file, then I will feed my C++ function that npy file. Since I have limited understanding of C++ pointers and reference, I can't wrap my head around how to get the value of a void fun... | There is so many things wrong with the code you posted
#include <iostream>
#include <Eigen/Dense> // minor remark: Often you just need <Eigen/Core> here
#include "cnpy.h"
#include "opencv2/highgui.hpp" // Do you actually need OpenCV here?
using namespace std;
using namespace Eigen;
using namespace cv;
(Almo... |
62,273,163 | 62,273,901 | Creating and pushing dynamic objects into a vector | I am concerned about creating and then pushing the dynamic objects into vector of pointers. I would like to know how to implement this correctly to avoid any kind of memory leaks. Here's what I have:
//THIS CREATES VECTOR
vector <combustion_car*> combustion_car_list;
//THIS IS CREATING AND PUSHING THE OBJECT
combustion... | Taking your original code sample, following are some suggested modifications to make it safely avoid memory leaks.
Rather than use a std::vector of bare pointers, use a collection of std::unique_ptr objects:
//THIS CREATES VECTOR
std::vector<std::unique_ptr<combustion_car>> combustion_car_list;
Create your temporary ... |
62,273,226 | 62,273,547 | How advantageous is using fused multiply-accumulate for double-precision? | I am trying to understand if is advantageous using std::fma with double arguments by looking at the assembly code that is generated, I am using the flag "-O3", and I am comparing the assembly for this two routines:
#include <cmath>
#define FP_FAST_FMAF
float test_1(const double &a, const double &b, const double &c ){
... | If your question is related to the number of memory operations only, it is important to note that mulsd and addsd are also memory operations in your example. Memory operations are indicated by the square brackets around the register name, not the assembly mnemonic itself.
If you're still curious if it's advantageous t... |
62,273,521 | 62,273,683 | argument of type "int*" is incompatible with parameter of type "int**" error in C++ | I was asked by my professor to create functions and use pointers to
pass an array of integers as parameter for each of those functions but when I inserted the test code that he created, I got the argument of type "int*" is incompatible with parameter of type "int**" errors.
#include <iostream>
#include "homework.h"
us... | If your professor wants to show pointers you can do this:
void Homework::print_array(int *numArr, int size)//exact same as int numArr[] as it decays to a pointer
{
for (int count = 0; count < size; count++) {
if (count == 0) {
cout << numArr[count];
}
else {
cout << ", " << numArr[count]... |
62,273,530 | 62,280,072 | Error when trying to push sf::Texture* into std::vector | I'm working on a C++ project that uses SFML and lua
The thing is when I tried to push the texture pointer that I loaded it crashes.
Here's my code
sf::Texture* tex = new sf::Texture;
if(!tex->loadFromFile(lua_tostring(L, -1))) std::cout << "Failed to load texture!" << std::endl;
std::cout << "Got here!" << ... | Apparently the player is NULL in the first place after I loaded the userdata from lua. I'm on the wrong stack index
|
62,273,909 | 62,330,030 | Sleeping using Windows API CreateWaitableTimer executes differently on Xeon compared to i7 processor | I'm working on a program that needs a consistent ~1ms sleep. The sleep is used in order to generate a hardware pulse of length ~1 ms.
I am using the following code for the sleep
void usleep(__int64 usec)
{
HANDLE timer;
LARGE_INTEGER ft;
ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative va... | Windows is not a real-time operating system, so getting super precise sleep times in user code will never be guaranteed. There are a bunch of things in play.
The OS may shift expiration times to save power. This is called timer coalescing. Waking up once to handle a few events is more power efficient than waking mo... |
62,274,068 | 62,274,298 | cross forward declarations in template classes/functions | I get two heads:
header1:
#ifndef CPPSH_A_H
#define CPPSH_A_H
class B;
class A {
public:
template<typename T>
void Function1() {
b_->Function2<int>();
}
template<typename T>
void Function2() {
}
private:
B* b_;
};
#endif //CPPSH_A_H
and header2:
#ifndef CPPSH_B_H
#define CPPSH_B_H
class A;
class B... | You can merge the two headers into one, e.g.
// forward declaration
class B;
class A {
public:
// member function template declaration
template<typename T>
void Function1();
template<typename T>
void Function2() {
}
private:
B* b_;
};
class B {
public:
template<typename T>
void Function1() {
... |
62,275,083 | 62,275,147 | How can one write a templated function that takes a generic iterator as a parameter | I've been writing a templated static class. For one of the methods, I want to be able to pass in any iterator not just one from a specific data structure like List.
template <class T>
class Foo
{
public:
template<typename InputIterator>
static bool bar(T&, InputIterator start, InputIterator end);
};
temp... | The correct way to define a nested member function template is:
template <class T>
template <typename InputIterator>
bool Foo<T>::inRange(T&, InputIterator start, InputIterator end)
{
typename InputIterator::const_iterator it = start;
while(it != end)
{
//logic here
it++;
}
return tr... |
62,275,182 | 62,275,402 | Sorting names in an array variable inside a structure alphabetically | I'm making this student record program that my prof asked us to do. It keeps saying cannot convert 'StudRec' to 'StudRec' in assignment and sometimes it says cannot convert char* to const char*. StudRec is my struct variable and this is the function that should sort the recorded names alphabetically.
void sort_name(Stu... | Ok, assuming that the StudRec has all necessary operations (assignment, default constructor, etc.), you don't need to pass an array of temp values:
void sort_name(StudRec name[], int studcount)
{
StudRec temp;
// ...
}
That should fix one issue: you are trying to assign an element to the whole array:
t... |
62,275,285 | 62,312,562 | How To Detect If An Actor Is Hit In Unreal Engine C++? | I'm new to Unreal Engine. I'm trying to create a basic game where you control a ball and roll around, trying not to fall out of a tube and stuff. My ball looks like this:
PlayerBall.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "PlayerBall.generated.h"
UCLASS()
class ROLLINGBALL_API... | What you want to be doing is binding to the AActor::OnActorHit event with OnActorHit.AddDynamic(this, &FunctionPointer).
The RecieveHit function is internal and will be what broadcasts this event.
|
62,275,619 | 62,282,560 | How do I #include plugin source files in my custom Unreal Engine module? | I'm working with a C++ Unreal Engine project and made my own custom module called MyActor, Unreal Engine automatically created the .cpp and .h files for me. That much appears to be working.
So now I want to include classes or methods from the AppleARKit plugin then override and call them from my custom MyActor module.
... | When I ran into the issue of including files from a plugin, in my case LidarPointCloud, the following steps worked for me:
1) In my <project-name>.Build.cs file, I added the module name I wished to use (LidarPointCloudRuntime) to the public dependency list
PublicDependencyModuleNames.AddRange(new string[] { "LidarPoint... |
62,275,710 | 62,493,672 | What is difference between "owned pointer" and the "stored pointer" for std::shared_ptr? | As per this documentation, which says (emphasis mine):
http://www.cplusplus.com/reference/memory/shared_ptr/owner_before/
Unlike the operator< overload, this ordering takes into consideration the shared_ptr's owned pointer, and not the stored pointer in such a way that two of these objects are considered equivalent (i... | In order to support things like converting a shared_ptr<Derived> to shared_ptr<Base> even when no virtual destructor exists (which is allowed in that case even if it isn't a great idea in general for dynamically allocated classes), and for a few other features, shared_ptr needs to have one pointer to the object designa... |
62,275,870 | 62,275,942 | How to understand the dynamic binding in this C++ code? | This is my code. I need help making this Dynamic Binding work.
#include<iostream>
#include<conio.h>
using namespace std;
class Shape {
protected:
double x,y;
public:
void get_data(double a,double b=3.14) {
x=a;
y=b;
}
virtual void display_area(){
};
};
class Rectangle ... | You are assigning ptr incorrectly. You should not be dereferencing it when assigning an object to it.
Change this
*ptr = ...;
To this
ptr = ...;
Also, you are leaking the objects you allocate with new. You need to call delete ptr; when you are done using each object. Which also means you need to add a virtual destructo... |
62,276,180 | 62,276,828 | Stop taking input when a blank line encounters | I am trying to stop the loop when user gives a blank line, otherwise push name and score to a vector pair. But this code is not working.
Input format:
<name><score>
e.g.:
Akash 45
My code is below:
int m;
cin>>m;
vector<pair<string,int>>player;
string name;
int score;
while(1)
{
cin>>name;
if(name.... | operator>> ignores whitespace, and line breaks are treated as whitespace, so cin>>name will never return a blank string (baring an input failure).
To accomplish what you are attempting, you need to use get::getline() instead to read an entire line at a time. You can then test for blank lines, and can use std::istringst... |
62,276,235 | 62,276,402 | How to calculate the maximum number of concentric polygons from a given set of points? | Given a set of points we have to find the maximum number of simple polygons which all lie inside one another (Basically be kind of concentric) .
And it is not important to select all points.
| Build convex hull for all points.
Remove points belonging to the hull.
Repeat for the next layer and so on ("onion peeling" approach)
Note there is O(nlogn) algorithm for building all convex layers cited here
Chazelle, Bernard (1985), "On the convex layers of a planar set", IEEE Trans. Inf. Theory, 31 (4): 509–517,
|
62,276,252 | 62,279,714 | Call a member function of a vector of elements with a vector of arguments in parallel | Given this piece of code:
struct T
{
void f(int const);
};
void f(std::vector<T> &u, std::vector<int> const &v)
{
for (std::size_t i = 0; i < u.size(); ++i)
u[i].f(v[i]);
}
Is there a standard way to parallelize the body of void f(std::vector<T> &u, std::vector<int> const &v)?
This happens to work by chance (... | Staying within std, your best bet is std::transform with an output iterator that ignores what is given to it
struct unit_iterator {
using difference_type = std::ptrdiff_t;
using value_type = std::tuple<>;
using pointer = std::tuple<> *;
using const_pointer = const std::tuple<> *;
using reference = s... |
62,276,869 | 62,276,931 | C++ "Invalid use of 'this' in non-member function", | Below are the .cpp versions of my character class and its subclasses. I am trying to get the attack() function to work. I made some changes and the current error deals with "invalid use of ‘this’ in non-member function" in the adjustHP() function. In my main class, I am instantiating a Warrior object which the player p... | In goblin.cpp you defined adjustHP as a non-member function.
It should have been:
void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}
|
62,277,128 | 62,277,366 | Adding a type to an existing template with out it being dropped c++17 | My goal is to be able to include my own extra type at declaration and have it passed to my template function. How would I be able to declare my type so that the compiler would not drop my extra template parameter.
For example I have this code:
#include <iostream>
#include <vector>
// my_vector is an alias for std::vec... | You can read in cppreference that, when aliasing:
Alias templates are never deduced by template argument deduction when deducing a template template parameter.
|
62,277,232 | 62,277,593 | Sorting algorithm correctness verification | I am trying to verify the correctness of a sorting algorithm S that is sorting a large array A of at least 4 GB. Assuming S is sorting in non-decreasing order, checking only A[i - 1] <= A[i] for 1 <= i < n is not sufficient. This is because the keys produced by S, even though sorted, may contain one or more keys that d... | You can treat your algorithm as a message being transferred over an unreliable channel, and utilize error detection/correction methods. Main different is your data is getting out of the original order while most error correction are sensitive to the position, though not all of them.
One simple solution is store the XOR... |
62,277,727 | 62,277,948 | nested lists to implement adjacency lists in c++ | i was going through the code for topological sorting on this website.
i understood the code except for one part which is the declaration of the adjacency list (on line 15), which is
list<int> *adj;
basically, to me, adj should be a pointer to a list of integers but in this case based on how they have used it, it is... | You could also do it like that, however what this website is creating is an array of lists, not exactly a list of lists. I think this approach (array of lists) is the usual way to represent adjacency lists in lots of programming languages.
In this way the vertices are numbered from 0 to V-1, and you can access the list... |
62,277,754 | 62,280,307 | Code not working in Visual Studio 2017 but works in VS code | I am writing a project for my algorithms classes and I need it to work on Visual Studio 2017. Everything works fine when I compile it with g++ through command line, but when I try to start the program through VS 2017 it goes into infinite loop in this funciton (its part of dinic`s max flow algorithm):
bool Graph::BFS(i... | The geeksforgeeks site from which the above code derives is bugged. The error is in the Graph::DinicMaxflow method. The code assumes that in this line
int *start = new int[V+1];
the start array will be initialised to zero, but C++ does not guarantee that. It will be initialised to zero by some compilers and not others... |
62,277,828 | 62,277,902 | alias template is not a class template? | I am trying to write a type trait to detect if a type has a T::type of certain type. I am using code from this answer. For reference this is the part of the code I am using:
// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.
template <typename...>
using void_t = void;
// Primary template handle... | You need to indicate that the nested thing is a template:
template <typename T, typename X>
using has_X_type = detect<T, has_X_type_helper<X>::template type>;
// ~~~~~~~~~^
|
62,277,907 | 62,281,075 | Determining cell value using bitwise operation with adjacent cell values | A r*c grid has only 0's ans 1's . In each iteration , if there is any adjacent cell (up,down,left,right) same to it, the value of the current cell will be flipped . Now , how to come up with a bitwise formula to do this . It can be done with a simple if condition , but I want to know the bitwise operation to do this so... | For the start, consider s[i], l, r, u, and d to be single bits, that is, boolean variables.
s[i] (abbreviated as s in this answer) is the old color of the cell to be updated.
l, r, u, and d are the colors of the adjacent cells left, right, above (up), and below (down) of the cell to be updated.
ans[i] (abbreviated a... |
62,277,920 | 62,278,181 | Problem with iteration on array in For loop | I'm having a trouble for a long time in a problem related to array and loops.
Assume an array like:
int arr[] = {2, 3, 5, 3, 6, 8, 10, 1, 9};
The program should print the expected column as shown (note that the table is an idea for clarification of what I actually want to achieve):
max: expected arr[index] for max... | So I rewrote your code, frankly I couldn't follow it, it seems a bit confused with variable names that seem a bit off.
Here's some working code. The two key concepts in the code are the place where each block starts (the variable start) and the size of each block (the variable count). Plus I use the size of the whole a... |
62,278,018 | 62,278,117 | Reversing string using stack (static array) in c++ | i am new to this concept in c++
i am trying to reverse string using stack static array implementation in c++.
Input: qwerty
expected output: ytrewq
output which i am getting is: trewq
Can some one explain me why is this happening and any possible solution.
Here's my code
#include <iostream>
#include <string>
using name... | Remove the "-1" in :
for(int i=0;i<(str.length())-1;i++)
Else your array doesn't contains the last character.
I made the test without the -1, it works well.
The condition "< str.length()" is enough to loop on all string caracter.
In similar case, use the debugger to see what contains your variable. In these case th... |
62,278,057 | 62,282,287 | Is python faster than c++ for http requests? | I have program that is written in python3.6 and now I wanted to re-write it in c++ to make it faster. Before doing so, I decided to make a small test to get a inference on how much speed will I gain. The program makes a lot of http request so I decided to test for http request speed. But I was really surprised by the r... | The difference may be because Python has a very optimized way of page requesting, and the swish lib/code you are using hasn't.
The network time may be the same (in fact, it should be the same), but you really can't know (unless you developed swish lib) what that library is doing.
Asking for a web page in c++ can be don... |
62,278,067 | 62,280,265 | Build an Array Pyramid/Cone | I am working on a project that needs to fill the cells of a 2D Array with the proper values in order to build two shapes, a pyramid and a cone. I will immensely appreciate any help on implementing this algorithm. Basically, I need to pass the x and y coordinates of the 2D Array and the function should return the proper... | This is more about geometry than programming. First consider the cone and LENGTH=WIDTH. Due to symmetry, the height above a given point only depends on its distance from the center of the base. How? Draw a vertical cross section of the cone through the apex and try to find a relation between the two. Look for similar t... |
62,278,098 | 62,278,447 | Text Adventure Game - How to Tell One Item Type from Another and How to Structure the Item Classes/Subclasses? | I'm a beginner programmer (who has a bunch of design-related scripting experience for video games but very little programming experience - so just basic stuff like loops, flow control, etc. - although I do have a C++ fundamentals and C++ data structures and algorithm's course under my belt). I'm working on a text-adven... | One possible way to solve your problem is polymorphism. By using polymorphism you can (for example) have a single describe function which when invoked leads the item to describe itself to the player. You can do the same for use, and other common verbs.
Another way is to implement a more advanced input parser, which ca... |
62,278,147 | 62,285,659 | How to insert a character to a text control in wxwidgets from the code itself? | I have this textctrl
FTextCtrl = new wxTextCtrl(parent, wxID_ANY, _("Text"), wxPoint(20, 20), wxDefaultSize, wxTE_CENTRE | wxTE_PROCESS_ENTER, wxDefaultValidator, _T("ID_TC"));
For this control based on the programming logic, I want to insert a editable character into the text field. How can we do the same?
| To insert text at the given position, you should use SetSelection() to set the insertion point (by creating an empty selection at the desired position) and then WriteText(). Of course, if you just want to append the text, you could use AppendText() directly.
Finally, you may decide to just use ChangeValue() to replace ... |
62,278,259 | 62,278,551 | Accessing frame data with OpenCV C++ | I'm trying to write a Gaussian Blurr OpenCv program where I input a mp4 video , read it frame by frame, and to each frame I apply a 3x3 stencil that essentially blurrs the image. However, my problem is that I don't know how to access the data of every frame. I tried doing "frame.data" this way:
int main(int argc, const... |
In OpenCV, you can use Mat constructor to specify the size (height, width, channels) of the Mat, and the memory will be allocated. You are using the default constructor, which does not initialize the object.
There are different ways to access the pixel values. You could use the Mat .at() method, you can access the raw... |
62,278,774 | 62,279,018 | ERROR: expected unqualified-id before '[' and ERROR: 'users' was not declared in this scope | I trying to make a program, in which you write login and password, and, if user exists in class, it shows permissions (ex. Carl can read and execute files). Right now I have two bugs:
22:9: error: expected unqualified-id before '[' token
36:23: error: 'users' was not declared in this scope
I'm new to c++, so I'm not s... | string User[] users = new User[]
{
new User("Alice", "Cooper", false, true, true),
new User("Bob", "Dylan", false, true, false),
new User("Carl", "Perkins", true, false, true)
};
That’s not valid C++ (it looks like you’re somehow mixing C++ and Java syntax). First off, you slipped an accidental string int... |
62,278,885 | 62,282,565 | Is there a way to figure out the type of object (in array of bytes form) C++? | I have been using boost::asio for a client server application, I am sending packed structs to and fro as messages, the server need to identify the the type of request struct passed to it and accordingly determine the response for it. For now each struct has a unique TemplateId, which is stored in a second level struct:... | Your method will work if all responses have the same initial structure
typedef struct {
uint32_t BodyLen;
uint16_t TemplateID; //this is unique
If all of the requests have that as beginning, it will work. No matter of the real type. You can cast any char * pointer to a MessageHeaderInComp type and verify the Te... |
62,279,094 | 62,280,097 | Trying to use spaceship operator in derived classes | I am trying to use spaceship operator in base class so I would have defined all operator by compilator. (source: https://devblogs.microsoft.com/cppblog/simplify-your-code-with-rocket-science-c20s-spaceship-operator/)
But I encountered problem which I do not understand.
Source Code: https://godbolt.org/z/SZnNfK
#include... | I suppose this is a bug of GCC. As you can see in this assembly here:
mov eax, OFFSET FLAT:vtable for testClass+16
cmp rax, OFFSET FLAT:vtable for testClass2+16
Gcc compares member of the vtable: it compares the static type of AA and the static type of BB, not the timestamp.
|
62,279,391 | 62,280,225 | What is the advantage of a pointer to the base address of an array instead of pointer to the first element? | Following is a code snippet showing a pointer to the base of an array and a pointer to the element;
1st case:
/* Pointer to an array of 10 integers */
int arr[10]
int (*ptr)[10];
ptr = & arr; //points to the base address of an array of 10 integers
for (i = 0; i < 10; i++) //prints the values
printf("%d\n", *(*ptr +... | In your particular example
int arr[10]
int (*ptr)[10];
ptr = & arr; //points to the base address of an array of 10 integers
for (i = 0; i < 10; i++) //prints the values
printf("%d\n", *(*ptr + i)); //NOTE: same as `ptr[0][i]`
there's no advantage or at least no advantage being utilized.
*(*ptr+i) with int (*ptr)[... |
62,279,725 | 62,279,726 | How to convert char* to TCHAR in Unreal Engine 4? | For example,
const char* bytes = "somemultibytecharacter一些宽字符";
size_t n = strlen(bytes);
How to convert bytes to FString or TCHAR* in Unreal Engine C++ code?
I know I can convert with std::mbstowcs or MultiByteToWideChar, but I'm trying to find a UE4 alternative.
| Just use FString(int32 InCount, const CharType* InSrc).
Usage:
const char* bytes = "somemultibytecharacter一些宽字符";
size_t n = strlen(bytes);
const FString& Str = FString(n, bytes);
const TCHAR* Text = *Str;
Note, in my copy of Unreal Engine 4, TCHAR is wchar_t:
typedef wchar_t WIDECHAR;
typedef WIDECHAR TCHAR
|
62,279,785 | 62,282,781 | Operator += applied to std::valarray<int*> | Here is the example:
#include <iostream>
#include <string>
#include <valarray>
int main()
{
std::valarray<std::string> vs(2);
// vs[0] += "hello"; // works
// vs[1] += "hello"; // works
vs += "hello"; // works
std::cout << vs[0] << std::endl;
std::cout << vs[1] <... | std::valarray doesn't have overloads for heterogeneous binary operations, but it does have a catch-all for other functions, apply.
vi.apply([](int * p){ return p + 1; });
|
62,279,887 | 62,280,431 | Concatenating LPCSTR variable and literal? | I have a LPCSTR variable name and I want to use it in MessageBoxA(NULL,name,"pop up",MB_OK);
where I want name to hold value name+" is X". For example name has value John so I am expecting output on Message Box as "John is X".
Can anyone help me with this?
I tried using std::(string(name)+string(" is X")).c_str();
... | You can create a string from the LPCSTR and then add " is X" to it.
Here's an example putting the result as both caption and text in the MessageBoxA:
#include <string>
void makebox(LPCSTR name) {
std::string res(name);
res += " is X";
::MessageBoxA(nullptr, res.c_str(), res.c_str(), MB_OK);
}
|
62,280,046 | 62,280,144 | Pointer to member function in virtual function | Is it possible to call a member function from an overriden virtual function? Compiler tells me that the member function has no address (lvalue required as unary '&' operand). I would like to do something like:
class Virtual
{
public:
virtual void f() = 0;
};
class Real : public Virtual
{
public:
void f() overr... | The error message already gives a good hint on what is wrong here:
<source>:10:27: error: cannot take the address of an rvalue of type 'bool'
void f() override { g(&Real::h()); }
^~~~~~~~~~
Real::h() is bool. Correct syntax to get a pointer to the member function is
void f() override... |
62,280,277 | 62,487,366 | argmax() method in C++ Eigen Library | I am using Eigen library for matrix/tensor computation where I want to returns the indices of the maximum values along the depth axis. Similar to what numpy.argmax() does in Python.
Tensor dimension is as follows:
(rows = 200, columns = 200, depth=4)
#include <Eigen/Dense>
int main(){
Eigen::Tensor<double, 3> table(... | Honestly, this is a roundabout not an satisfying answer for the question itself. Nevertheless, the following approach did work for me.
I could not find what I wanted in Eigen library. Instead, I switched to armadillo library which is pretty similar to numpy having a user-friendly API. Moreover, Comparatively speaking, ... |
62,280,304 | 62,283,608 | yum : using boost 1.69 instead of default (1.53) version on centos | I want to compile (c++/cmake) code using boost 1.69. I am on centos 7.
After :
sudo yum install boost-devel.x86.64
the code compiles fine, but using the default version which is 1.53.
If I look at the libraries installed in /lib64, I see for example:
>> ls -al /lib64/ | grep boost_timer
lrwxrwxrwx. 1 root root ... | So there's obviously BOOST_INCLUDE_DIR which you can use to control where boost headers, so why not just
cmake -DBOOST_INCLUDEDIR=/usr/include/boost169 \
-DBOOST_LIBRARYDIR=/usr/lib64/boost169 \
...
|
62,280,716 | 62,312,027 | C++ - Sorting vector of structs with std::sort results in read access violation | I have a problem with the std::sort-method. In the following code I'm using the std::sort-method to sort a vector of structs (= Highscore). However, when I run this line a "read access violation" exception is thrown in the xmemory-file.
Here are the details:
Exception thrown: read access violation.
_Pnext was 0x217AE3... | Here is the current solution I'm using. This works for me and solves my problem, which is with reading/writing an std::string to a binary file and not with the sorting method (Thanks to the comments on the question!). To fix this problem I used parts of this.
reading from a file:
std::ifstream in(FileName, std::ios::in... |
62,280,995 | 62,281,045 | Problem with sorting a vector of struct in C++ | so I am basically trying to make a function that sorts a vector of a struct called tasks based on the task's priority. My program crashes whenever the given vector has two items or more dunno what's wrong with my code help! n thanks!
void sort_tasks(std::vector<tasks> &tasks_list)
{
if(!tasks_list.empty()){
... | Here auto j = i++; you don't check if i is tasks_list.end() after the increment.
You check it well in the for but you have to check it here too because you increment the iterator.
|
62,281,021 | 62,281,367 | CMake How to properly include my own headers? | I am working with ros and now I want to write my own unittest. But I am struggling with it. Maybe you have an suggestion for me? Or maybe a solution?
my structure:
-catkin_ws
--build
--install
--src
----project1
----CMakeLists.txt
----package.xml
------include
--------prime_tables.h
--------sample1.h
------src
--------... | In sample1.cpp is a library you want and to test and you want to create an executable which links to this library and runs a unit test?
Some basic cmake info:
The first argument of add_library, add_executable and target_link_libraries is the name of the library/executable. So if you specify your linked librarys to this... |
62,281,381 | 63,124,372 | ZMQ: are messages published in extended pub-sub when there are no subscribers? | According to the ZMQ guide, when using a standard pub-sub pattern, if there are no connected clients the publisher does not publish any messages.
If a publisher has no connected subscribers, then it will simply drop all messages.
However, what happens if you are using an extended pub-sub pattern i.e. the publishers a... | The Proxy routes published messages from upstream producer (PUB) to downstream consumer (SUB). It passes subscribe/unsubscribe messages from the consumer to the publisher. The publisher's PUB socket drops any messages for which there is no subscription.
So if there are no consumers downstream of the Proxy, and the Prod... |
62,281,522 | 62,282,066 | Save a Type to a file | Im trying to make a level loading system, where the level file is stored as some binary file that has the class of the object to be spawned and its position and scale. One thing I cant figure out is how to convert a class type into something that can be written to a binary file and also retrieved later.
I tried convert... | There are a few things going on here, so I took the liberty of writing a short snippet.
In order to read in a bunch of objects into a single container like the below when you don't know their type, they all need to derive from a base class. Alternatively you could pass the deserialize function different vectors (or o... |
62,281,558 | 62,285,422 | C++ - Password validation with do while (entering asterisks signs) | As you can see from the title I want to check password but with do while loop. What I want to do is, asking the user to enter the password and if the password is incorrectly entered 3 times, the program should exit.
Here is the code, I hope you understand what I want to do
#include <iostream>
#include <conio.h>
using ... | Following loop will never end:
do
{
cout << "Your password is incorrect" << endl;
cout << "Enter again: ";
for (i = 0; i < 5;i++) {
unos[i] = _getch();
_putch('*');
}
n++; // how many times user entered the password
}while(un... |
62,281,660 | 62,283,246 | Why this program does 35 percent accepted but rest is runtime errors? | Once, when Dino was solving a problem related to arrays, he saw that the size of all arrays is at most 106. Since Dino is a dinosaur, this number seemed very small to him. Therefore, he decided to create a big array.
Dino first creates an empty array and selects n pairs of numbers: (a1, b1), (a2, b2), ..., (an, bn). Th... | You don't need to recreate the array, and you don't need to sort anything (the description even tells you that you shouldn't: "Dino's computer cannot perform this arrangement").
Consider what happens if you turn the problem around slightly.
Instead of a[i] being the i:th number, let it say how many is there are in tot... |
62,281,792 | 62,282,065 | What could I summarize this c++ program??? It is a counting loop for vowels and digits | I'm an early beginner of c++. I developed a program but I would like to compare, trying to summarize the following code to practice my logic skills.
The program currently is working. The program counts the number the vowels and digits found in a user's input. The input normally has to be in one word but could be random... | You can use an array to store all your counts and then only print the values you're interested in:
#include <array>
#include <cctype>
#include <climits>
#include <cstdio>
#include <iostream>
#include <numeric>
#include <string>
#include <string_view>
int main() {
std::string str;
std::cin >> str;
std::array<int... |
62,281,974 | 62,391,126 | How can I watch multiple variables while debugging without stopping at breakpoints? | Suppose I have a complex C++ application that I need to debug with a lot of variables. I wanna avoid using std::cout and printf approaches (below there's an explaination why).
In order to explain my issue, I wrote a minimal example using chrono (This program calculates fps of its while cycle over time and increment i_t... | You can use nonblocking breakpoint. First add the breakpoint. Then click on breakpoint settings or right click and select action.
Now you add a message like any string that is suggestive for you. And in brackets include the values to show, for instance
value of y is {y} and value of x is {x}
In the image is shown the... |
62,282,119 | 62,282,609 | Disambiguating a function pointer | To choose between two comparison functions, I can write the following code:
const float& (*cmp)(const float&, const float&);
if (cmp_type >= 0)
cmp = &std::max;
else
cmp = &std::min;
I would like to combine it to a single line using the ?: expression:
const float& (*cmp)(const float&, const float&)(cmp_type >=... | You could make a typedef and use it to static_cast to get the correct overload.
using cmp_t = const float&(*)(const float&, const float&); // typedef
cmp_t cmp = cmp_type>=0 ? static_cast<cmp_t>(std::max) :
static_cast<cmp_t>(std::min);
|
62,282,599 | 62,282,713 | Create UObject with global lifetime | I have a plain C++ class where I need to have property of type UObject.
class A {
private:
UObject* SomeSpecialObject;
};
If I create such property with NewObject I will get dangling pointer when I load new level/map because of GC. I can use weak pointer and check if object is still alive but I need this object t... | I guess it's an Unreal Engine question.
Once your UObject is created, you can call its method "AddToRoot()". After that, it will never be deleted by the GC.
https://docs.unrealengine.com/en-US/API/Runtime/CoreUObject/UObject/UObjectBaseUtility/AddToRoot/index.html
Add an object to the root set. This prevents the object... |
62,282,687 | 62,283,388 | Pisano period generator behaves incorrectly for 3-digit periods | I have a C++ code which is supposed to return the Pisano period value for any value m. The code works correctly when the period is 2-digited, but generates incorrect values for 3-digited periods. Eg:- Period(24) = 24 which is correctly generated
Period(25) = 1243 (which is INCORRECT , it should be = 100)
#include <ios... | When you compute the next fibonacci number, you do :
long long tmp = prev2;
prev2 = cur2;
cur2 = tmp + prev2;
period = period + 1;
There's nothing in there to prevent overflow. Even long long eventually overflow. You should try keeping only the modulo part of prev2 and cur2 to avoid the overflow.
I don... |
62,283,036 | 62,283,170 | Curly braces in variable names | Lately I've been browsing through some code of facebooks folly library and saw a variable named like
HTTPServer* const server_{nullptr};
as a class member.
I've never seen something like this before and wondered if there is any special meaning. Googling only made me found other examples like this one in boost code to.... | It is used as an initializer list. In your case, HTTPServer pointer would be set to nullptr, but you can use curly braces even with plain types such as int, float, etc.
Its role is to initialize the variable with value(s) inside, which means that both attitudes below mean the same:
int x = 10;
int x{10};
You can also... |
62,283,173 | 62,319,199 | Setting QFont from QFontDatabase sets all labels to monospaced font? Qt C++ | I am trying to set one QLabel to a monospaced font. By default, I have all my other labels set to "Arame-Regular" in the designer. Normally, trying to set any of my labels to "Arame-Mono" (the monospaced font) in the designer does not work. They stay regular.
After this bit of code in my mainwindow.cpp, every label in ... | I've created a simple demo; it shows three labels where only the last one is set manually to monospace:
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
using QFD = QFontDatabase;
if (QFD::addApplicationFont(QStringLiteral(":/Roboto/Roboto-Regular.ttf")) == -1) {
qWarning() << "Failed... |
62,283,227 | 62,283,411 | C++20 concepts: int not swappable_with int | I'm trying out C++20's concepts, and either std::swappable_with is undefined (Visual Studio, using /std:c++latest) or its constraints are not matched by the MCVE below (g++10 using -std=c++2a) -- that is, int is not swappable with int (!). What's the fix for this? If int can't be swapped with int, I don't see anything ... | std::swappable_with<T, U> checks whether swap can be invoked (after using std::swap;) with arguments std::declval<T>() and std::declval<U>(). With T and U being int, both arguments are rvalues, which cannot be bound to std::swap parameters, since these are (non-const) lvalue references.
You wonder that int cannot be s... |
62,283,582 | 62,283,636 | Can't make C++20 concept requiring bool member function | This MCVE is giving trouble in both Visual Studio (2019, with the C++20 flag on) and g++10 (also, with C++20 option set). The complaint in each case is that bool is not a type constraint. (So what should I be typing to require that a given type have such a member function?)
#include <concepts>
template <typename T>
c... | The concept needs to be written as:
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> std::convertible_to<bool>;
};
Note that this is actually more explicit in the constraints for foo. It says, calling foo must return a type that is convertible to a bool.
This means you can also specify that... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.