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,663,284 | 62,663,361 | class prototypes not being read | im learing c++.I was goofing around trying new stuff and wanted to use an object class sub in class object.But i was getting error saying that the object of class sub not in not defined.I know how to solve this issue i just have to move class sub above class object so that the compiler knows that there is a class call... | When a type is used in c++, at a minimum that type needs to have been declared previously.
However, in some cases, the type needs to be defined (complete) as well.
class A;
class B {
A a; // error, because A needs to be defined
};
In other cases, the type only needs to be declared (i.e. it can be incomplete... |
62,663,291 | 62,664,585 | Initialization of a struct defined in a templated parent class | I have defined a struct within the protected section of a parent class, which I would like to use in an inherited class.
This works as expected if the parent/child classes aren't templated classes. But does not compile as-is below.
Specifically, the compiler (clang 8.0.1) reports:
inheritance_example.cpp:33:26: error: ... | In order to pack the comment into an answer!
Node is a depended name and hence you need to use keyword typename there. Meaning in the dummyAdd function, you need
void dummyAdd(T toAdd)
{
this->head = new typename Parent<T>::Node(toAdd);
// ^^^^^^^^^^^^^^^^^^^^
};
That is, however, a bit verbose/ ... |
62,663,405 | 62,663,584 | input to size variable error in stack (c++) | #include <iostream>
using namespace std;
struct stack{
int size;
int top;
int *s;
};
void create(struct stack *st){
cout<<"enter size :";
cin>>(&st->size); ///This line poses error when i run the program
st->top=-1;
st->s=new int[st->size*sizeof(int)];
}
void display(struct stack st)... | &st->size is an int*. You can't read from cin into an int*. Since you just need to read the size, removing the & should fix it:
cin >> st->size;
Your for loop in display is incorrect as well. You need to do something like:
for(int i = 0; i < size; ++i)
cout << st->s[i];
Also, this line:
st->s=new int[st->size*siz... |
62,664,165 | 62,664,276 | CUDA error identifier "__stcs" is undefined | I want to use store function with cache hint __stcs on GPU Pascal, CUDA 10.0.
In CUDA C++ Programming Guide there is no mention of any header for data type unsigned long long, but the compiler return an error identifier "__stcs" is undefined.
How to fix this compilation error?
| These intrinsics require CUDA 11.0, they are new for CUDA 11.0.
If you look at the CUDA 10.0 programming guide you will see they are not mentioned. You can also see that they are mentioned in the "changes from Version 10.2" section of the 11.0 programming guide.
You also need to compile for compute capability 3.5 or... |
62,664,285 | 62,665,286 | Convert a HEX string to long in C++ | I'm writing my first BLE system for Ardunio and I'm building it on top of an already working system for controlling RGB strip, and currently, I'm using the HEX numbers to know what I'm setting where.
OK reworking the question,
#define BLE_RX 5
#define BLE_TX 4
SoftwareSerial BLE(BLE_RX, BLE_TX);
// set the startup co... | Source of error in your posted code: you are using an array of 6 characters while it should be 7 to hold the whole recv string. Your code is currently showing an undefined behavior because strtol searches for null/whitespace character to finish parsing which is never present within bounds in char c[6].
I would recommen... |
62,664,997 | 69,449,755 | Debug-Compiled Server crashes on Database opening | quick background...
have been running AC for WoW 3.3.5 on my server for almost 3 years.(previously TrinityCore)
running older version on an older system.
went to update with latest commits last week and found dependency updates.
reverted back to previous version i was running, which runs fine on main server.
installe... | it has taken a while, but i finally figured out what was going on here.
the compilation and testing of libACE failed.
i did not see this, nor was it obvious when i "make install".
this lead to failure of ACE_Activation_Queue::dequeue(), which caused the hanging described above.
all is working now, using ACE 6.5.0.
|
62,665,302 | 62,665,487 | Showing garbage values when adding two matrix using operator overloading | Please help me as I am new to programming and I have made this program and it looks fine to me but I am getting garbage values instead of sum of two matrix.I have applied the concept of operator overloading to find the sum of two matrices but I am getting garbage values again and again?Please help me that where is the ... | Let's take a close look at you operator+, there are two major errors:
Matrix sum[2][2]; is an array of matrices, but you want to return only a single Matrix, not multiple. Also the name is bad, because you already have a parameter with a similiar name. And yes, C++ is case sensitive, but such similiar names are proble... |
62,665,503 | 62,666,839 | Boost Signals2 pass Slot to member Function for Disconnecting | I have the following class which uses a simple boost::Signals2::Signal:
class Button {
using OnClick = signal<void()>;
public:
using OnClickSlotType = OnClick::slot_type;
boost::signals2::connection add_handler(const OnClickSlotType& slot) {
return click.connect(slot);
}
void remove_han... | You could register the same function more than once, resulting in multiple connections.
Therefore, the function is not sufficient identity.
Instead, you can use the connection object to disconnect a particular connection:
Live On Coliru
auto d = btn.add_handler(&demo);
btn.add_handler(&second);
btn.click();
d.disconn... |
62,665,516 | 62,665,835 | Why OpenGL cut off polygons (even if this settings is disabled)? | I read similar suggested questions and their solutions, but could not find an answer.
I'm trying to draw a scene with an isometric view in OpenGL.
Draw func:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glRotatef(atan(0.5f) * 180.0f / PI, 1.0f, 0.0f, 0.0f);
glRotat... | The polygons are clipped by the near or far plane of the viewing volume.
When you do not set a projection matrix, then view space, clip space and normalized device space are the same. The normalized device space is a unique cube with the left, bottom, near of (-1, -1, -1) and right, top, far of (1, 1, 1). All the geome... |
62,665,564 | 62,665,674 | Why my program keep asking values continuously if I add this line | I am trying to increase the value of s by the call by reference but when I add *s=*s+5; my code is going to a loop of continuously getting values
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
};
node* push(node *head,int newdata,int *s)
{
node *newnode,*temp;
newnode... | You are getting an infinite loop because i < s is always true since you increase s by 5 on every push function call. Here's your loop:
for(int i=0; i<s; i++){
After every iteration it checks whether i < s. But you are increasing s by 5 in the function push():
*s=*s+5; //this line
Thus, i is always les... |
62,665,749 | 62,666,060 | How to Hide Next Button in QT Wizard | I am working with a QWizard that really should've been implemented as a QStackedWidget but it's too far gone to change now. I have a QPushButton I would like to call a SLOT from, and that SLOT then calls nextId() after doing other things.
I have tried removing the next button with:
QList<QWizard::WizardButton> wizardBu... | As a workaround, I was able to call
wizard()->next();
from the SLOT which forced a call to nextId().
This is probably not the best way to handle this but it is working. I will accept another answer if one is presented, or alterations/comments on the validity of my solution.
|
62,666,033 | 62,666,934 | How to solve NTE_BAD_DATA using CryptDecrypt at final step | I am working on a encryption algo with c++ using WINAPI. My encryption works flawless and my decryption too untill the last chunk to be decrypted with final = TRUE. I got the NTE_BAD_DATA error.
PS : I manualy check the buffer and the decryption works fine untill the last CryptDecrypt.
If someone have an idea, kindly h... | You are not storing off the encryption the final block correctly.
The amount of data you pass into the encryption is in out_len, and the amount of data that is encrypted is put back into out_len. For a block cypher that doesn't matter for whole blocks, but your last block which is less than a whole block being passed i... |
62,666,095 | 62,686,758 | using std::index_sequence to initialize POD struct container with fixed size array members | I am trying to use std::integer_sequence and its helper template std::index_sequence to initialize a fixed size POD struct that behaves like a container. Each element in turn contains a fixed size array field.
The container POD struct is essentially defined as:
#define ELEM_NAME_SIZE 7
#define CONTAINER_SIZE 20
us... | if you want the output following output given HELLO
Element:[H], Element:[E], Element:[L], Element:[L], Element:[O],
this code will work, although there will be an element for the null character if you pass a null terminated string.
#include <iostream>
#include <tuple>
#define MAX_NAME_CHARS 9
#define MAX_CONTAINER_... |
62,666,166 | 62,666,292 | Passing AActor reference into the nested object | I want to do some logic of AActor in nested object and i need to pass this actor by reference to make it work. Unfortunatelly, i don't see a way how to pass "this" when "&" is used. Can someone explain me what's going on?
ATestActor.h
class UHelper;
UCLASS()
class PROJECT_API ATestActor : public AActor
{
GENERATE... | &this creates a pointer to a pointer. your function Help accepts a reference to a pointer. calling Helper->Help(this); should work since this is already a pointer, then we pass the ptr by reference when calling Help.
edit:
actually i forgot this is a prvalue expression and prvalues cant bind to non const lvalue referen... |
62,666,731 | 62,667,006 | move semantics with local variables | I was wondering about the following code taken from this example:
Is it possible to std::move local stack variables?
struct MyStruct
{
int iInteger;
string strString;
};
void MyFunc(vector<MyStruct>& vecStructs)
{
MyStruct NewStruct = { 8, "Hello" };
vecStructs.push_back(std::move(NewStruct));
}
... | If NewStruct was entirely on the stack, the moving it would be no more efficient than copying it. To create a new object with the same contents as NewStruct would require copying everything from the stack to wherever the new object is.
Where move semantics are helpful are for objects that aren't entirely on the stack (... |
62,667,301 | 62,667,335 | Do includes in .cpp file get included when a .h file is included | So lets say I have a bunch of files named like this :
main.cpp : Containing the main() function
foo.h : declaration for some resource
foo.cpp : definition of the resource declared in foo.h
goo.h : declaration of some other resource
Now foo.cpp includes goo.h
// foo.cpp
#include "goo.h"
//...
//...
My question is th... |
if I include foo.h in main.cpp file, can I access definitions in goo.h in my main.cpp file?
Depends on what foo.h contains. If it includes goo.h, then you can technically access those definitions in main.cpp. Inclusion is a transitive "operation". If c includes b, and b includes a, then c includes a indirectly.
If fo... |
62,667,448 | 62,678,204 | C++ Qt application on Android and iOS | As an experiment, I have a pure Qt C++ application (without QML) compiling (with cmake & ninja) and running on:
Windows
macOS
Linux (ubuntu and centos/redhat)
FreeBSD
It uses basically QMainWindow, QGraphicsItem and QDialog, iostream and a few C++ containers and iterators.
I am wondering if the port to Android is:
p... | Yes, it is possible. I have worked in many Qt apps developed for iOS and Android. However, never used cmake, but qmake. it is good that you started experimenting using cmake which is the future as qmake is going to be deprecated sometime in the future. Qt's official documentation started adding cmake getting started t... |
62,667,846 | 62,667,894 | How do you call a non-member function with a template in c++, where the typename is only in the return? | My goal is to have a non member function use a template for a return value. This is so I can return a float array, a double array, etc. I get a "couldn't deduce template parameter 'T'" error.
Here is the method I am trying to use:
template<typename T>
T* make(double magnitude, double frequency, double radians, double s... | You can very much do this with non-member functions, as per the following example, which adds together two values of a templated type:
#include <iostream>
template<typename T> T add(const T &val1, const T &val2) {
return val1 + val2;
}
int main() {
auto eleven = add<int>(4, 7);
std::cout << "4 + 7 = "... |
62,667,937 | 62,668,149 | Reading Triangle Data Mesh With Object Files | I need to load in the vertices of a .obj file in c++. I just copied over the verts from the object I downloaded so I didn't have to worry about texture mapping or anything. I was able to separate it into a single line and get rid of the v but am not able to isolate the x,y,z coordinates so I can assign it to three sepa... | A simple way to read in the line
v 10.693913 60.403057 33.765018
and separate it into 3 different variables is to first read in a char, then read in three doubles:
ifstream fin("fox.txt");
vector <vector<double>> data; // holds sets of coordinates
double a, b, c;
char v;
while(fin >> v >> a >> b >> c){
data.push_... |
62,668,629 | 62,678,787 | QGamePadManager connectedDevices empty but Windows detects gamepad | I'm trying to get gamepad functionality to work in my C++ QT arcade game(yes PacMan) clone app. I'm writing and testing it in Windows for now (I don't have access to a Linux box but eventually I'll test there too hopefully). I have a protected method in my GamePanel class called "initInput" Here is the code for that ... | So it turns out that there is somewhat of a bug in the QGamepadManager as per this site:
https://bugreports.qt.io/browse/QTBUG-61553?focusedCommentId=371230&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel
Evidently you have to first get the Manager's instance, then create a dummy window, show it... |
62,668,815 | 62,668,827 | Problem compiling a template friend example from Stroustrup's C++ | Does anyone know why this will not compile and how to correct it? I'm trying to use friends and templates. I'm using this code from Stroustrup C++ 4th Ed Page 682-683.
Thanks
#include <iostream>
using namespace std;
template<typename T>
class Matrix;
template<typename T>
class Vector
{
T v[4];
public:
frien... | The friend declaration refers to the instantiation of template operator* (i.e. operator*<T>), but the template doesn't exist (has not been declared) and then cause the error.
You need to declare the operator template in advance.
E.g.
template<typename T>
class Matrix;
template<typename T>
class Vector;
// declaration... |
62,668,913 | 62,669,089 | Why in C++11 we move from one function in vector::resize to 2 version? | I'm asking this because im developing a class library.
(As i can see in cplusplus.com) in C++98 we had only one version from the std::vector::resize funcion:
void resize (size_type n, value_type val = value_type());
this way the function works if you want to specify the second argument or not. But in C++11 they change... | For std::vector::resize, before C++11, the default argument of val is always value-initialized, the appended elements are copied from it, as the effect they're value-initialized too. Since C++11 this could be avoided by providing a custom Allocator.
additional default-inserted elements are appended (since C++11)
(e... |
62,669,166 | 62,669,202 | Why can I assign one object to another without overloading the "=" operator? | I'm new to C++ and just learned about overloading operators. I'm confused because it seems like I can assign one object to another without having to overload the "=" operator.
Take this code as example:
class process
{
int size;
public:
process(int s)
{
size = s;
}
~process();
int getSize()
{
... |
Why can I assign one object to another without overloading the “=” operator?
Because classes have an implicitly generated copy (and move) assignment operator.
Is there any place where I can have some concrete info about what C++ did for this to happen?
Authorative source of info is the standard document.
Books have... |
62,669,351 | 62,669,487 | Why is iteration through a char vector is faster than the iteration through a string in C++ | I am practicing a coding challenge where I have to reverse the vowels in a string.
My first approach failed because of exeeding Time limit. Here is my first approach using string iteration to reverse the vowels in a string.
string reverseVowels(string s) {
string str = "";
//storing the vowels from the string i... | Replace str = str + x; with str.push_back(x); or str += x;, and you'll likely see the same performance as with vector.
str = str + x; makes a copy of str, appends the character to that copy, then makes another copy when assigning back to str. As a result, your algorithm is quadratic, for no good reason.
|
62,669,584 | 62,672,456 | how can I use CERN Root with C++17? | Apparently, CERN's "Root" software is compatible (as of version 6.12) with C++17. However, I have been completely unable to get this to work with the newest version (6.20) and all previous questions I found on this topic are from a few years ago.
Does anyone with Root experience know if there is a particular compiler o... | You can use root only with the c++ standard with which your root version has been compiled. This is a known inconvenience and I believe the developers would be happy if/when they get this sorted out. The build configuration root-config --cflags should set the appropriate c++ standard. This might very well be c++17 (it ... |
62,669,860 | 62,671,535 | incomplete type GLFWwindow when wrapping a C++ class | I am trying to derive from an Application C++ base class in Python with Boost::Python and am struggling with wrapping the GLFW callbacks, particularly due to the GLFWwindow* window argument.
Here's the MCVE:
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <boost/python.hpp>
class Application
{
public:
... | The error comes from template <class T> inline type_info type_id() via...
template <class T>
struct registered_pointee
: registered<
typename boost::python::detail::remove_pointer< // <-- fails for incomplete types
typename boost::python::detail::remove_cv<
typename boost::python::... |
62,670,516 | 62,670,744 | Is there any way to sort set of pair of int and pair by greater int and smaller pair in c++? | I have a set<int, pair<int, int> > ms that I want to sort it by greater int and smaller pair<int, int>. For example, if these are the data in my set:
<10, pair<100, 120> >
<20, pair<45, 60> >
<20, pair<50, 10> >
I want it to be this after sorting operation:
<20, pair<45, 60> >
<20, pair<50, 10>
<10, pair<100, 120> >
... | Pass a custom compare operator to std::sort.
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
int main() {
std::vector<std::pair<int, std::pair<int, int>>> v = {
std::make_pair(10, std::make_pair(100, 120)),
std::make_pair(20, std::make_pair(45, 60)),
std::make_pair(20, std:... |
62,670,544 | 62,670,762 | Is there a function to load a non-atomic value atomically? | In C++20 we can write:
double x;
double x_value = std::atomic_ref(x).load();
Is there a function with the same effect?
I have tried std::atomic_load but there seem to be no overloads for non-atomic objects.
| Non-portably of course, there is GNU C __atomic_load_n(&x, __ATOMIC_SEQ_CST) __atomic builtin.
I'm pretty sure you don't find a function in ISO C++ that takes a double * or double &.
Possibly one that takes a std::atomic_ref<double> * or reference, I didn't check, but I think the intent of atomic_ref is to be construct... |
62,670,987 | 62,671,367 | Why does an unnamed struct inline variable not have the same address in every translation unit? | thing.hpp:
struct
{
} inline thing;
other.cpp:
#include "thing.hpp"
#include <cstdio>
void test()
{
std::printf("test: %p\n", &thing);
}
main.cpp:
#include "thing.hpp"
#include <cstdio>
extern void test();
int main()
{
std::printf("main: %p\n", &thing);
test();
}
Compiling with Clang 11 or GCC 9.3.0 i... | Let's ignore the inline specifier for a second. Imagine it was absent. Your code would still produce the same results. The reason is the linkage of the class type itself.
[basic.link]
8 A type is said to have linkage if and only if:
it is a class or enumeration type that is named (or has a name for linkage purposes (... |
62,671,190 | 62,671,983 | Time complexity when have composite data type such as tuple or pair? | In Hash map data structure such as unordered_map in C++:
unodered_map<char, int> mp = { {'a', 10}, {'b', 20} };
if (mp.find('a') != mp.end())
cout << "found you";
we know find() method takes constant time. but if I have composite data as the key:
unodered_map<tuple<char, string, int>, int> mp = { {'a', "apple"... | In general, the more bytes of data in the key, the longer the hash function will take to generate a value (though some hash functions do not look at every byte, and can therefore have reduced big-O complexity). There might be more or less bytes because the tuple has more values, or some element in the tuple is variabl... |
62,671,358 | 62,671,397 | C++, is there a way to (object.method(0,0) = 10) use assignment operator instead of an extra parameter? | I'm new to C++, and it's my first year in computer science and...
I just want to ask if... is there a way to make what i put in the title work?...
To further explain what I mean, here is an example:
template <class dataType>
class squareMatrix{
private:
int size_side;
dataType *mainPtr;
... | Yes, you can make index returning the reference to element, (like how std::vector::operator[] and std::vector::at do,) e.g.
dataType& index(int row, int column) {
return mainPtr[row+(size_side*column)];
}
then you can assign to the return value like
obj.index(0,0) = 10;
|
62,671,522 | 62,671,618 | include botan 2 in compilation | i try include some botan header in compilation process
#include <botan/rng.h>
#include <botan/auto_rng.h>
#include <botan/cipher_mode.h>
#include <botan/hex.h>
#include <iostream>
int main(int argc, char** argv)
{
return 0;
}
I found that i need to compile with following command in order to build successfully... | The following command:
g++ app.cpp -lbotan-2
links botan-2 with app.cpp but you still need to specify where to find the headers:
g++ app.cpp -I/usr/local/include/botan-2 -lbotan-2
Under my system, the headers for botan-2 are in /usr/include/botan-2. So, make sure you are giving the right path.
|
62,671,686 | 62,672,005 | Does the operand of unary* operator expect a prvalue | int main(){
int a = 0;
auto ptr = &a;
auto&& rf = *ptr;
}
Consider the above code, when glvalue ptr is used to as the operand of unary* operator, Is it be required a lvalue-to-rvalue conversion that would applied for it? I.E, Does the operand of unary* operator expect a prvalue?
Question 1:
expr.unary.op#1
The ... | In general, it is CWG1642:
1642. Missing requirements for prvalue operands
Although the note in 6.10 [basic.lval] paragraph 1 states that
The discussion of each built-in operator in Clause 8 [expr] indicates the category of the value it yields and the value categories of the operands it expects
in fact, many of the ... |
62,671,866 | 62,673,138 | Concurrency/Multithreading: Is it possible to generate the same output this way? | One thread is supposed to count up, the other down. Output varies but it generally is able to print the countUp() portion fine, followed by some flaws in the countDown() portion. Initially, I determined that the problem was that both the threads were fighting for the cout resource. This I thought would be resolved with... | Use Condition variable to wait, The wait operations atomically release the mutex.
mutex mu;
atomic<int> counter = 0;
condition_variable m_cvO;
//Counts up from 0 to 20
void countUp()
{
unique_lock<mutex> lck(mu);
m_cvO.wait(lck, [&]() {
return counter < 20;
}... |
62,672,035 | 62,672,189 | How to use .h file which have (this) as variable name into CPP file | I have a header my.h which have following declaration of a function named as my_func.
#pragma once
void my_func (int *this);
this function is implemented in my.c
void my_func (int *this)
{
printf("%d", *this);
}
in foo.cpp i want to use my_func
extern "C"
{
#include <foo.h>
}
but i am getting following error ... | this is a keyword in c++. You cannot use it as a variable.
You can simply rename it to something else in the header.
In fact, you can even remove the variable name completely. The compiler won't care. Named arguments are there to tell developers what the argument is meant to represent. It does not inform the compiler o... |
62,672,472 | 62,672,573 | Why do these perfectly similiar codes not work? | I'm learning about functions in C++ and I saw this code on Tutorialspoint which tells us whether the
input is an int or a string.
Link to the Tutorialspoint article : https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string
This is the original code:
#include <iostream>
using namespa... | You are checking if the char is a digit and returning false if it is, you should change it to
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i])
return false;
return true;
}
a sidenote, if you want to check for false you can do (!bool) instead of (bool != true) it lo... |
62,672,942 | 62,673,159 | How can I check if a template specialization is a child class of a base template? | Using Check if class is a template specialization?, I can check if a class is a specialization of a template.
Using std::is_convertible<A*, B*>, I can check whether A is a child class of B.
How can I implement is_convertible_specialization, something that would do:
template<typename ... Args>
class Base {};
template<... | You were close.
First, the template parameters of the primary template (but not the specialization) must match the way you want to use your template:
template <typename ChildTemplate, template<class...> class Template>
Next, if the pointers are not convertible, the specialization of is_convertible_specialization shoul... |
62,673,102 | 62,675,061 | availability of __builtin_bswap16 for signed short? | I am trying to do swapping of 16 bit signed number .
So I wrote this logic which works fine :
// Byte swap signed short
inline int16_t swap_int16( int16_t val )
{
return (val << 8) | ((val >> 8) & 0xFF);
}
But I observed that in gcc compiler following swap function is available for unsigned short variable.
https:... |
Is it available in GCC or g++ ?
No. The list of documented builtins is exhaustive. There are no secret signed bswaps.
On the other hand, there is also hardly any need to use the builtins. Using the bitwise operators is equally fast as the builtins as long as optimiser is enabled, and unlike the GCC builtins, the bitw... |
62,673,524 | 62,674,021 | Is GoogleMock still intended to work with any testing framework? | Until v 1.8.1, Using Google Mock with Any Testing Framework was documented.
Since v 1.10.x, it looks like this section does not appear in the documentation. Has it been moved somewhere else or GoogleMock is no more made to work with any testing framework?
|
Has it been moved somewhere else or GoogleMock is no more made to work with any testing framework?
The section has been removed.
The commit
Preparation for including docs in round-trip with OSS
of the googletest project entirely removed the section Using Google Mock with Any Testing Framework. The commit is large ... |
62,673,816 | 62,673,939 | reverse function is out of scope in my cpp program | #include <iostream>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
int LCS(string x, string y, int n, int m)
{
int t[n + 1][m + 1];
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++)
{
if (i == 0 || j == 0)
t[i][j] = 0;
}
for (int... | You should ask for string before you reverse it, cin >> x; should be before you use std::reverse, because it's empty.
This line
cout>>LCS(x,y,x.length(),y.length());
has a typo, it should be cout << ....
std::reverse does not return the reversed string, it reverses it in place, you can't assign it to another std::stri... |
62,673,997 | 62,674,068 | How to find indices in an std::vector<bool> which are true? | I have say the following bool vector
v = [false ,true, false ,false ,true, false ,false ,true]
I want another vector which contains the indices of v for which the elements are true.
I have the following code:
std::vector<int> nds; //contains the indices
for (const auto &elem : v)
{
auto idx = &elem - &v[0];
if... |
is there a better way to find the indices?
Use a classical for loop
for (int i = 0; i != v.size(); ++i) {
if (v[i]) nds.push_back(i);
}
|
62,674,132 | 62,675,026 | How does one program to an interface/supertypes in C++? | I'm reading the book Head First Design Patterns and am also trying to learn C++.
In the book it says to program to an interface/supertype instead of programming to an implementation and the authros give this java example:
//programming to implementation
Dog d = new Dog();
d.bark();
//programming to an interface/superty... | Disclaimer: Translating Java code/patterns/best practices directly to C++ leads you to a world of pain.
Java has interfaces. What comes closest to that in C++ is an abstract base class:
struct Animal {
virtual void makeSound() const = 0; // <- pure virtual, ie no implementation in Animal
virtual ~Animal() = d... |
62,674,307 | 62,674,579 | What is the default behavior of a std::map if, rather than the value, the KEY is a std::list or std::vector? | For example, these cases:
using stringlist = std::list<string>;
std::map<stringlist, int> orderedMap;
std::unordered_map<stringlist, int> unorderedMap;
How will comparing keys in orderedMap work? Would it compare all items ('sub-keys') in the key one by one in lexical order?
How will computing hash in unorderedMa... | An ordered map, by default, uses std::less to compare keys, which by default just does lhs < rhs.
The behavior of vector's operator < is described here: https://en.cppreference.com/w/cpp/container/vector/operator_cmp
And that of list is here: https://en.cppreference.com/w/cpp/container/list/operator_cmp
Yes, they just ... |
62,674,659 | 62,674,807 | namespace extern variable already defined | I cannot compile my C++ program and I don't understand why.
Here's a simple representation of what is throwing errors:
hello/hello.cpp
#include "hello.h"
namespace MyHelloNS {
MyHelloClass::MyHelloClass() {
MyHelloVAR1 = "hi";
MyHelloVAR2 = "dog";
}
}
hello/hello.h
#pragma once... | Add this to main.cpp (or hello.cpp)
namespace MyHelloNS {
string MyHelloVAR1;
string MyHelloVAR2;
}
This question has nothing to do with namespaces, you just aren't following the correct procedure to define a global variable.
|
62,674,839 | 62,705,838 | Inherited class with member containing other inherited classes? | I am trying to represent an abstract syntax tree in C++.
I have multiple classes which inherit base class 'TreeNode'.
Some of them contain pointers to other inherited classes of TreeNode within them.
With the method i am trying to use to get it to work, I can't seem to access the members within the child TreeNodes. Am ... | Thanks for all your answers.
It turns out I was trying to solve this problem in the wrong way. I completely removed the TreeNodeType enum, and instead used a virtual function to traverse the tree.
class TreeNode {
public:
TreeNode();
virtual void print() = 0;
};
class UnaryOperation : public TreeNode {
public:... |
62,675,188 | 62,675,879 | can't show the encrypted text on Logcat | main func to try encrypt and show on logcat
aes = new ofxLibcrypto();
// start
unsigned char *key = (unsigned char *)"qwertyuiqwertyuiqwertyuiqwertyui";
unsigned char *iv = (unsigned char *)"qwertyuiqwertyui";
unsigned char *plaintext = (unsigned char *)"The quick brown fox jumps over the lazy dog";
unsigned char *ciph... |
can't show the encrypted text
Your encrypted text(ciphertext) is a binary blob. It may have some printable characters such as A or ? or something, but is also going to have characters that are not printable for e.g characters with ASCII value 1, 2, 3 or even 0.
Consider this sequence of characters in a binary blob:
u... |
62,675,256 | 62,675,758 | Template instantiation of templated class constructor | This fails to compile with clang++, can anybody explain why ? (this compiles fine with g++)
struct X
{
template <typename T> X() {}
};
template X::X<int>();
int main() { return 1; }
instantiate.cc:7:13: error: qualified reference to 'X' is a constructor name rather than a type in this context
template X::X<int>(... | Constructors don't have names. As much is said in [class.ctor]/1. They are special members that get defined by using the name of the class. But they themselves are nameless. While C++ allows us to reference c'tors in certain contexts by using the class name, those are limited. In general, we cannot name a c'tor.
And th... |
62,675,477 | 62,675,943 | Do I have a risk to put a thread in deadlock with std::condition_variable in C++? | This is more theoretical question. I've seen couple examples with std::condition_variable and it seems that it gets threads to sleep until a condition will be satisfied. It is some kind of a flag on races and makes sense.
But it seems that if a variable is always changed then a thread may be woken up for checking cond... | You appear to be talking about some kind of 'livelock'. A deadlock is a situation where one or more threads is making no progress waiting on the release of a lock.
Livelock is similar but the state of the process is constantly changing but still none is progressing. We can also talk about 'practically livelocked' where... |
62,675,548 | 62,690,100 | How can I apply memoization to this recursive function? | I was solving the Subset Sum problem: "Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not." For this problem I created a recursive function which works correctly but I am not able to correctly memoize it.
The code is:
bool func(int a... | Tabulation is much easier.
bool ss(int a[],int n,int s){
bool r[n+1][s+1];
for(int i=0;i<=n;++i)
r[i][0]=true;
for(int i=1;i<=s;++i)
r[0][s]=false;
for(int i=1;i<=n;++i)
for(int j=1;j<=s;++j)
if(j>=a[i])
r[i][j]=r[i-1][j] || r[i-1][j-a[i]];
else r[i][j]=r[i-1][j];
return r[n][... |
62,675,858 | 62,675,920 | using getline gives error: no matching function for call to ‘getline(std::istream&, const string&)’ | I'm working on this code and it works with cin>>partname; instead of using getline(cin, partname); in the showpart function but for only names without blank space. But with using getline(cin, partname); it produces an error
error: no matching function for call to ‘getline(std::istream&, const string&)’
#include<iostrea... | #include <string> instead of <cstring>.
Also:
void showpart() const can't be const since you update partname (which is an odd activity for a function called show-something).
I suspect that you want to show the partname, not to update it:
void showpart() const
{
cout<<"Inventory details"<<endl;
cout<<"Part Number: "... |
62,676,422 | 62,692,589 | Is reinterpret_cast<char*>(myTypePtr) assumed to point to an array? | We know that char* can alias anything: According to cppreference
Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true:
[...]
AliasedType is std::byte, char, or unsigned char: ... | auto ptr = reinterpret_cast<char*>(myTypePtr);
The standard permit this conversion, due to:
An object pointer can be explicitly converted to an object pointer of a different type.73 When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_cast<cv T*>(sta... |
62,676,425 | 62,676,715 | How to pass the zero-filled multidimensional array to a function in C++? | I want to pass my zero-filled nullMat multidimensional pointer array to a function called setGraphics in the constructor. In whatever way I try to do so I get "argument incompatible" or something in the lines of that.
The cpp file Test.cpp
#include "Test.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#includ... | Seems clear you don't understand when to return values from functions. lifeMatrix is creating the matrix so it need to return the matrix. nullMat is just modifying the matrix, so it doesn't need to return the matrix.
Rewrite your code like this
class Test : public QMainWindow
{
...
void nullMat(bool **lifeMat) ... |
62,676,665 | 62,676,710 | When does a non-dynamic variable goes out of scope if being referenced by a pointer? | I'm new to C++ programming and I am having some hard time understanding some concepts.
Take this code as a example:
// Example program
#include <iostream>
class nber
{
int* value;
public:
nber(int n)
{
value = &n;
}
int getNber()
{
return *value;
}
};
int main()
{
nber var(111);... | The scope did end. What you're seeing is Undefined Behavior - anything can happen. The number could be "purple", as far as the rules say. Or your hard disk could be erased. The latter is a bit rare, though.
|
62,676,808 | 62,676,864 | Why the output of this program is not as expected | I separated pointer template from general template but the output does not as it should be.
template <class T>
class Test
{
private:
T pvalue;
public:
Test(T invalue)
{
pvalue = invalue;
}
void display()
{
std::cout << pvalue << "\n" ;
}
};
temp... | Just add full specialization for char * as follow:
template <>
Test<char*>::Test(char * invalue)
{
int len = 0;
while(invalue[len] != '\0')
{
len++;
}
pvalue = new char[++len];
for(int cnt = 0; cnt < len; cnt++)
{
pvalue[cnt] = i... |
62,677,010 | 62,677,117 | Pure virtual function implementation through lambda | Can I implement a pure virtual function using lambda, similar to Java interface implementations?
| Not directly. You can via some indirection though.
struct interface {
virtual auto execute() -> int = 0;
};
template<typename T>
struct lambda_impl : interface, private T {
lambda_impl(T l) noexcept : T{l} {}
auto execute() -> int override {
return T::operator()();
}
};
You can now construct ... |
62,677,023 | 62,677,226 | Using variables to define variable names | I am sure that there is a very simple answer and I am perhaps just being forgetful, but I cannot remember how to use a variable to define the name of another variable. I cannot even think of a name of this process to search for existing answers.
I have a variable: VarA, which will be an integer 1, 2, 3, 4, etc.
I have ... | The term to search for is "nasty convoluted macro voodoo". But seriously, don't go there. Names of variables do not exist at runtime. What you want to do cannot be done in C++.
However, whenever you name variables X1,X2,...XN then that variables actually want to be members of an array. If you use a 2D array then that s... |
62,677,387 | 62,692,308 | gSoap unfriedly error during creation of .h from .wsdl | I am trying to produce .h file from .wsdl using gsoap:
wsdl2h.exe -v -s -c++11 -o a.h a.wsdl
With a.wsdl it is working like a charm, but with b.wsdl I am getting the unfriendly error:
SOAP 1.1 fault SOAP-ENV:Client [no subcode]
"End of file or no input: message transfer interrupted"
Detail: [no detail]
Any idea how t... | It was some whitespace which was preventing wsdl2h in parsing the wsdl / xsd file.
|
62,677,446 | 62,677,737 | I just want to use a C++11 lib in Android 4.4 | I want to embed Antlr4.8 C++ runtime lib in our App which supports Android 4.4.
I have checked the official Google Doc about NDK, but still don't know the relationship between NDK version and Android System version and C++ version.
So can anyone give me some tip or "more detail" Doc about embed C++11 lib in Android App... | According to release notes of the current Android NDK v21, the toolchain uses Clang release r365631 (the master branch as of 10 July 2019), which corresponds to Clang 9.0.6.
That means that C++ is supported all the way up to C++17, and even some parts of C++20.
So C++11 is no problem at all.
Note: to use the latest C+... |
62,677,672 | 62,678,214 | Error using boost::from_block_range on member dynamic_bitset, but not on local dynamic_bitset | I am attempting to convert a std::vector<uint8_t> into a boost::dynamic_bitset. I can achieve the inverse of this using the following code, where values is a class member function defined as
boost::dynamic_bitset<uint8_t> values.
std::vector<uint8_t> payload;
boost::to_block_range(values, std::back_inserter(payload));
... | Your decode method is marked const, but you are attempting to modify class member variable values.
Either remove the const or mark values mutable
For example:
#include <cstdint>
#include <vector>
#include "boost/dynamic_bitset.hpp"
struct foo
{
void do_the_thing()
{
std::vector<uint8_t> payload{1, 2, 3... |
62,677,747 | 62,677,847 | warning C4552: '>>': result of expression not used | #include <iostream>
int main() {
int manic;
std::cout << "Enter Size of Array" << "/n";
std::cin >> size; // << "/n";
size = manic;
static const int arr[size];
for(int i = 0; i < size; i++) {
std::cout << "Enter" << i << "Element" << "/n";
std::cin >> (arr[i]); // Error Is Show... | The compiler gives you the hint that you may uninentionally override a value
std::cin >> size;// << "/n";
size = manic;
You let the user input a value and then override it with another, by the way uninitialized, value.
|
62,678,221 | 62,711,335 | QT image display is not working without declaring openCV namedWindow in windows 10 | I am using windows 10 with QT 5.14 opencv 4.20 with contrib version.
I am displaying the image captured by webcam to QT label. It was working perfect in Ubuntu but after migrating to windows it is not working. It work only if I create openCV namedWindow("frame",0). It creates extra window of openCV. I installed openCV ... | I am sharing so that other can benefit if they face same issue.
The problem is solved by adding
qApp->processEvents(); after the
ui->label->setPixmap(QPixmap::fromImage(QImage(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888).rgbSwapped()));
Actually what this qApp->processEvents(); does is it pro... |
62,678,497 | 62,765,379 | How to use superpowered time stretching class on audio process | I'm having a problem changing the rate of my audio with superpowered time stretching.
I know that I need to process the time stretching rate times the number of frames due to output the number of frames.
Ex: If I set the time-stretching rate to 1.5 (increase 50% of original speed) and the number of frames is 144, my nu... | I changed my approach of time stretching to the advanced audio player playback rate attribute.
|
62,678,564 | 62,753,560 | cppcheck generates wrong xml structure | I am trying to parse the XML data from the output of cppcheck. But the XML structure seems wrong.
cppcheck src --enable=warning,style,unusedFunction --xml --inconclusive --std=posix --std=c++11 2> error_s.xml
cppcheck XML output:
<?xml version="1.0" encoding="UTF-8"?>
<results version="2">
<cppcheck version="1.82"... | unfortunately it cannot be accessed with out writting too many if-statements ..
if(isset($location)){
}
Conversation with CppChecker Developer.. Hopefully it would get fixed when they release v3
for now, the only way to access is using too many if-Statements.
if not, there is also library htmlreport which will gener... |
62,678,686 | 62,678,716 | Does modifying a std::vector invalidate an iterator? | Consider this piece of code:
#include <vector>
#include <iostream>
int main(int argc, char** args)
{
std::vector<int> vec;
vec.push_back(0);
for (auto iter = vec.begin(); iter != vec.end(); iter++)
{
vec.push_back((*iter) + 1);
std::cout << *iter << std::endl;
}
}
I expected this ... | std::vector::push_back invalidates all iterators on that vector if the new vector size is greater than the previous capacity. (The reason is due to the reallocation of the vector).
The behaviour of using an invalidated iterator is undefined.
std::list::push_back does not invalidate any iterators.
|
62,678,875 | 62,746,881 | Multiply packed 8 bit integers by vectors of floats using intel intrinsics | I am writing a software rasterizer with heavy use of intel intrinsics (NOT including AVX512). The colors are represented by a 32 bit unsigned, which is really just 4 packed 8 bit colors (RGBA). So, a vector of 8 colors may be held in a single __mm256 color variable. However, I need to manipulate the individual colors w... |
a vector of 8 colors may be held in a single __mm256 color variable.
That's not the best way. Will be very hard to add 10+ bit color depth, or gamma correction, or color grading. For optimal performance, consider using 16 bit integers instead, or floats.
I cannot find any sane way to do this.
Convert your floats t... |
62,678,879 | 62,700,230 | C++ Nested Iterators for Sets | I am trying use nested iterators for sets as shown below but gives an err:
error: no match for ‘operator+’ (operand types are ‘std::_Rb_tree_const_iterator’ and ‘int’)
for(auto itj = iti+1; itj != st.end(); itj++){
int alternate(string s) {
set<char> st;
for(char x : s){
st.insert(x);
}
for(aut... | std::set's iterator does not satisfy the named requirement LegacyRandomAccessIterator. It only satisfies LegacyBidirectionalIterator.
So iti + 1 is not a valid expression, there's no matching operator+ for the iterator.
To fix your problem, you can use std::next.
for (auto iti = st.begin(); iti != st.end(); ++iti){
... |
62,679,099 | 62,716,368 | Extension plans for formatting of trivial structs in C++ {fmt}? | In my current project I need a custom very simple "serialized" representation of a couple of trivial data transfer object (DTO) structures. After first coming up with a custom made solution, that was a big PITA, I had the idea to use {fmt} for that.
So the last days I was playing around with formatting of custom types ... |
Would formatting user defined types via a simple reflection API provided by {fmt} be something that you'd consider a possible future extension to {fmt}?
Possibly but it will have to be an explicit opt-in, i.e. such types won't be formattable automatically in this way because normally you'd want a more high-level repr... |
62,679,201 | 62,681,112 | How to sort and change date format in QTableView | I've already implemented a QTableView + QStandardItemModel in Qt5. At the beginning, I set the date data just as a string with the date format based on the application setting. For instance, it can be the US format like MM/dd/yyyy or the european format dd.MM.yyyy. The data comes from a json file with the european date... | The solution is to pass the QDate as data to the model, and use a delegate to set as shown in the view:
_model->setData(index, date);
class DateDelegate: public QStyledItemDelegate{
public:
using QStyledItemDelegate::QStyledItemDelegate;
QString displayText(const QVariant &value, const QLocale &locale) const{
... |
62,679,389 | 62,691,243 | Crypto++ Signing with PKCS1v15 padding with different algorithms | I am wondering if Crypto++ only signs files using SHA (RSASSA_PKCS1v15_SHA_Signer)?
I have been using pyCryptodome to do the signing and verifying, but I want to make a C++ application that does the same. In Python, I can sign the files with any of the supported hashing (SHA3/BLAKE2B etc..) algorithms. At the very leas... | So I found an answer to it. So partially following the tutorial found here
and from RSASS<PSS, SHA256>::Signer signer(privateKey); you could add the PKCS1v15 padding as such RSASS<PKCS1v15, SHA256>::Signer signer(privateKey);
So the final code would look something like this:
std::string Hasher::sign(const std::string& ... |
62,679,495 | 62,679,643 | Sorting a vector of pairs that correspond to row and column of matrix | I have a matrix of int's. The <row,col> pair is stored in an std::vector. I would like to sort this vector so that after sort, when traversed it gives the elements of the matrix in order. Follows a sample code:
#include <vector>
#include <algorithm>
int main()
{
int matrix[2][2];
matrix[0][0] = 4;
matrix[0... | The comparator is supposed to take two elements. You are passing a comparator that takes ints but the elements of the vector are std::pair<int,int>.
#include <vector>
#include <algorithm>
#include <utility>
#include <iostream>
int main()
{
int matrix[2][2];
matrix[0][0] = 4;
matrix[0][1] = 3;
matrix[1]... |
62,680,568 | 62,680,604 | Do arrays that get allocated on the stack within the scope of a function always get deallocated when leaving the function? | Let's say I have the following code:
#include <iostream>
void f() {
int arr[10];
}
int main() {
f();
f();
}
Does the array arr get deallocated once we leave the scope of f(), even though we will call it again? Also, if we only call f() once, I'm assuming it gets deallocated when leaving the scope of f(), but so... | Conceptually it does indeed since arr has automatic storage duration. (For example, if you were to return a pointer to an element of that array, then the behavior on dereferencing that pointer in the caller would be undefined.)
Whether or not the compiler chooses an appropriate optimisation based on the as-if rule is a... |
62,681,059 | 62,681,387 | How to run thread in class method? | class TestMgr{
public:
std::condition_variable mSubCond;
static TestMgr & GetMgr() {
static TestMgr *Mgr = nullptr;
if (Mgr == nullptr) {
Mgr = new TestMgr();
}
return *Mgr;
... | TestMgr::GetMgr() is not safe for multithreading, but is called concurrently (In CAL::add()from all 4 worker-threads).
Change it to the simpler
static TestMgr & GetMgr() {
static TestMgr Mgr = TestMgr();
return Mgr;
}
And it will be.
|
62,681,412 | 62,721,466 | Lower framerate while using dedicated graphics card for OpenGL rendering | I'm using glDrawArraysInstanced to draw 10000 instances of a simple shape composed of 8 triangles.
On changing the dedicated graphics card that is to be used to my NVIDIA GTX 1060, it seems i'm getting lower framerate and also some visible stuttering.
This is the code i'm using to see time taken for each frame :
std::c... | I solved the issues by Disabling NVIDIA Physx GPU acceleration. For some reason it slows down graphic rendering. Now I'm getting about ~280 FPS on my GPU even when rendering ~100k instances.
|
62,682,216 | 62,682,741 | How to fix this deprecated use of std::allocator? | Here are the key points:
1: This project uses the open-source repository NanoRT as a raytracer in a project.
2: This project is compiled under Visual Studio 2019 (C++17)
3: This project is compiled with warnings treated as errors (and this cannot be changed). Adding the define to suppress these warnings did not help.
H... | There's a couple of ways to address this, and one size doesn't fit all.
The simplest path:
For std::allocator<T>, the type std::size_t is always the same as size_type, and the type T* is always the same as pointer. So the easiest thing is to just sub in those types.
The std::allocator_traits path:
These types also exi... |
62,682,217 | 62,683,046 | Memory handling in C++ classes | #include<iostream>
using namespace std;
class abc{
private:
int a;
string s;
public:
abc(int x,string y) {
a=x;
s=y;
}
~abc() {
cout<<"destructor for abc called\n";
}
};
class def{
private:
int *a;
string *... | C++ doesn't actually have a concept of "the stack" or "the heap". C++ only cares about object lifetimes, not where the implementation chooses to store those objects.
In this case, there are two lifetimes at play:
new abc() and new def() create objects with dynamic lifetime
These objects will live until a pointer to ... |
62,683,557 | 62,683,681 | Declare a subclass method as a friend of the base class | I am new to C++ and OOP and was given a problem that I struggled with. I was asked to design classes to represent employees and managers. My implementation is below.
class Manager;
class Employee {
private:
int salary;
public:
std::string name;
Manager* manager;
Employee(int salary, std::string nam... | write a getter method for that field in the employee class that checks if the caller is the manager. If so, return the value.
|
62,683,653 | 62,684,455 | Variable or field '...' declared void Error on Ardunio Compiler | I am trying to code a flight computer.
The odd think about this error is:
This code block works flawlessly:
class PlaneStatus {
public:
PlaneStatus(double y, double p, double r, double t) {
yaw = y;
pitch = p;
roll = r;
throttle = t;
}// Access specifier
double yaw, pitch, roll, thr... | For future reference
I got an answer from another forum. The problem is with The Arduino IDE's auto-prototype generation.
This solves the problem.
void manuer(PlaneStatus ms);
void manuer(PlaneStatus ms) {
ms.pitch;
}
|
62,683,816 | 62,683,925 | why c++ is rounding of big numbers to ceil and small numbers to floor | "x","y" are two long long type variables in c++ to which i have assigned two different numbers.
Variable type is long long but i have assigned decimals to the integer.
so i expected that it will trim the decimal part and display only integer part.
it trimmed off the numbers after the decimal and retured an integer.
Ou... | Each initialization involves two conversions, first from the decimal numeral in the source text to double, and then from double to long long.
Let’s discuss the second declaration first. Because 2.001 is a double constant, the decimal source text 2.001 must be converted to double. Assuming your C implementation uses IEE... |
62,684,332 | 62,685,448 | Force-stop MP3 file playback when program complete | I added the following to my program:
system("afplay intro_music.mp3 &>/dev/null &");
Audio is playing in background as expected, but when the program exits (whether I use CMD+C or use my "quit game" function that just return 0;, it still continues to play. Even when I close out Visual Studio Code, it still continues l... | You need to call your System to Stop the music in your Code.
The music does not stop, because it is a programm Independent from VScode and your program.
|
62,684,413 | 62,684,587 | constructors not used for initialization with a temporary variable | In a struct, I defined the default, move and copy constructors. However, when I tried to instantiate the object form another temporary object of the same type, none of those constructors are called. I tried removing the move constructor but still no constructors are called. Could anybody help me with this. Thank you so... | Before c++17, your code does in fact call the move-constructor. In practice, unless otherwise specified, compilers will optimize the move out of the code. demo
From c++17, the wording changed, and now there is mandatory copy-elision. There is no longer any temporary created, so there's nothing to move from. demo
|
62,684,590 | 62,685,179 | How to get Edge window handle (HWND)? | I created edge browser window using CreateCoreWebView2Host() method. This method is takes parent window handle and creates child window in which we can navigate the web page. After I am done with navigation I need to return my window handle, which I believe I am failed to return.
On Spy++ I see "Chrome_WidgetWin_0", "C... | The WebView2 SDK doesn't provide this HWND because exactly how the WebView2 connects up to the provided parent HWND is intended to be an implementation detail that could change as the underlying Edge browser or WebView2 Runtime is updated even when you stay on the same version of the WebView2 SDK. We're relying in larg... |
62,685,583 | 62,686,584 | How to display all the lines of a file in MFC | So as the title says, I want to display all the content of the file in the edit box but I dont know how to do that
this is the handler of the button, when pressed it will make the user choose a file and its content is supposed to appear in the edit box.
The problem is that its only showing the first line somehow
Update... | Don't use MFC for you application needs, only us it as UI. All of your code should be written in a portable fashion. IMHO.
Write global, non MFC functions for your needs. So, to get the string from a file.
std::string read_file(const std::wstring& filepathname)
{
std::ifstream is(filepathname, std::ios::binary | st... |
62,686,572 | 62,688,429 | Different solution for Activity Selection problem with greedy approach | There is a classic solution for famous Activity Selection problem with greedy approach that you can see here.
But now, I think about another solution. Let's see this sudo code:
while(!empty(S))
{
Select interval I $ \in $ S that overlap least number of other intervals;
Add I to Result;
Remove all Interval from... | Your solution doesn't always work. Here is a counter example
|
62,686,665 | 62,686,717 | Clone vector of unique pointers with RTTI | I want to clone a vector of unique pointers using RTTI.
Currently, there is an abstract base class, Node, and derived classes, Element and TextNode. Element contains a vector of unique Node pointers.
I'm able to create an object of type Element and move it into the vector. I want to be able to clone an Element and push... | What you are asking for can't be done directly with RTTI, but it can be done indirectly by checking the class types manually. Since you have only a small number of classes to check, you can do that like this:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Node {
virtual ~Node() =... |
62,686,761 | 62,823,706 | SSL Certificate Format | I'm starting some C++ programming to read certificates with libcrypto (OpenSSL) and I'm curious about the format of a certificate ("crt" or "cert") file.
In the file, when I look at it with a text editor, there are multiple certificate sections like so:
-----BEGIN CERTIFICATE-----
XXXXXXXXXXXX
-----END CERTIFICATE-----... | In normal cases, a .crt file contains just one certificate. However, in some contexts, some applications may allow that a file contains multiple certificates.
For example, some applications may expect that a file contains all or some certificates of a certificate chain. However, in typical cases, such file has .p12 (PK... |
62,686,780 | 62,742,982 | Is my solution to fixed timestep with delta time and interpolation wrong? | I am trying to write simple loop with fixed delta time used for physics and interpolation before rendering the state. I am using Gaffer on games tutorial on fixed timesteps and I tried to understand it and make it work.
float timeStep = 0.01;
float alpha = 1.0;
while (isOpen()) {
processInput();
deltaTime = clo... | You should remove the if statement and always calculate alpha; the if statement will never be executed as the condition is always false after the while loop is exited!
After the loop the accumulator will be between 0 and timeStep so you just end up drawing the latest position instead of interpolating.
|
62,687,052 | 62,688,104 | Pointers to undefined functions and parameters in C ++ | I have the following code:
#include<iostream>
using namespace std;
void saludo();
void despedida();
int main(){
void (*Ptr_Funciones[2])() = {saludo, despedida};
(Ptr_Funciones[0])();
(Ptr_Funciones[1])();
return 0;
}
void saludo(){
cout<<"\nHola mundo";
}
void despedida(){
cout<<"\nAdios m... |
How do I make an array of functions, if they are of a different type?
You can, but you don't want to. It doesn't make semantic sense. An array is a collection of the same kind of thing. If you find that you need to make a collection of different kinds of things, there are several data structures at your disposal.
I ... |
62,687,108 | 62,687,120 | How does the C++ sort function work when using a custom comparator? | Disclaimer: it's been about 5 years since I wrote any C/C++. I usually code in python.
I have a vector of strings that I wanted to sort in a certain way (by length), so I wrote my own comparator function:
bool sortSubstrs(string a, string b)
{
if (a.length() > b.length()) { return true; }
else { return false; }... | This has nothing to do with sort whatsoever. This line is wrong:
cout << a.length() + " " + b.length() << endl;
It should be:
cout << a.length() << " " << b.length() << endl;
As a relic and compatibility with C in C++ string literals have C array type, i.e. " " is of type char[2]. Again as a C relic C array types de... |
62,687,219 | 62,687,450 | Qt: How to make Incompatible sender/receiver arguments compatible? | Here is the code where I use connect,
connect(myTimer, SIGNAL(timeout()), ui.widget_2, SLOT(paintEvent(QPaintEvent *)));//draw lines
I use it to go to the slot paintEvent(QPaintEvent *) where I can draw some lines. But I have a message while debugging or running the program which is
QObject::connect: Incompatible send... | Don’t try to connect to paintEvent(QPaintEvent *); that method isn’t a slot-method, so calling it via a signal wouldn't work even if you were somehow able to get the right arguments passed to it. Instead connect to the update() slot, which will see to it that the paintEvent(QPaintEvent *) method is called from the pro... |
62,687,318 | 62,688,123 | undefined reference to copy ctor and ctor | I have A base class in this file:
#ifndef MTM_CHARACTER_H_
#define MTM_CHARACTER_H_
#include "Exceptions.h"
#include "Auxiliaries.h"
#include <memory>
namespace mtm
{
class Character
{
protected:
int health
public:
Character(int health): he... | It looks like you might be instantiating an abstract class (because the virtual method is pure virtual (=0)).
Make sure you're dynamically instantiating virtual types, and not using new Character() - because that names the abstract type.
So don't:
Character x(.....);
Also don't:
Character x = Sniper(....); // slicin... |
62,687,496 | 62,687,525 | why is my last else condition not executing correctly | why is it when I input anything other than int I get 0 is an even number, the plan was if the user enters something that's not an integer it should output invalid input
cout << "Enter an integer: ";
cin >> input;
if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else if(input % 2 != 0) {... | cin >> input is an operation that can fail, and if it fails the input variable does not contain a useful value. You can check whether it succeeded by converting cin to bool:
cin >> input;
if (!cin) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Or, since cin >> input returns the c... |
62,687,568 | 62,687,614 | How to correctly implement a different version from a Base class? | I'm trying to implement a class that inherit from (lets say) Base. But there is a problem, Basedoes have an class which declaration is like this:
template<typename It> void getInfo(It begin, It end);
But in the second class Inh i concluded that this version of the class that take 2 iterators is not the best, so i deci... | In fact you don't need to mark the getInfo as delete. If you declare another getInfo in the derived class, it will hide the one from the base class. Then
Ihn<int> obj;
obj.getInfo(5, 1000); // would always try to call getInfo in the derived class
And you can still call the base version explicitly like
obj.Base::getInf... |
62,687,952 | 62,688,718 | How to pass 2-D char array to a function? | I just create a simple function which takes the 2-D char array as an argument and then just print the values of that 2-D char array.
The function is given below
void final_output(char arr[][200]){
int i, j;
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
cout << arr[i][j];
}
}
}
... | I you want a method to be valid for any matrix since you need to use char**. I is more cumbersome because if you are using pointers, but it is more flexible.
void final_output(char** arr, int nrow, int ncol) {
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
cout << arr[i][j];
... |
62,688,105 | 62,688,179 | std::is_trivially_copyable_v on virtual function | I try following code, it just prints false.
class A
{
virtual void func() {}
};
std::cout << std::is_trivially_copyable_v<A>;
Why does virtual function influence copy? virtual table pointer can just trivially copy.
| From class.prop
A trivially copyable class is a class:
where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial ...
And from class.copy.assign
A copy/move assignment operator for class X is trivial if ...
class X has no virtual functions ...
So yo... |
62,688,225 | 62,749,097 | Compile error in third party API - Visual Studio | I tried using a few hash APIs but it gives compile error. I tried 2 different hash APIs and 2 different IDEs and compiler but it gives the same errors. It looks like a linker error. Often there is a "unresolved external externals" or "undefined to" compile error. How can I fix compile error?
test.cpp:
#include <iostrea... | A likely reason is that your project is missing xxhash.c in its list of source files to compile. Each *.c file becomes an object file, which is linked during the last stage. So without it, no symbol defined in xxhash.c is ever created.
Another way to solve this issue is to #define XXH_INLINE_ALL just before #include "x... |
62,688,268 | 62,688,323 | In C++11, how to find and return all the item(s) in a vector of strings that start with a given string? | (Note: When I refer to vectors, I'm referring to the vector class provided by <vector>.)
The problem
Given a string x and a vector of strings, how can I retrieve the string(s) in the vector that start with x? Preferably in a way that is time-efficient?
That is, if x is "apple" and the vector is vector<string> foods = {... | A good way to solve your problem would be to use binary search. Note that this requires sorting the vector of strings first, which gives the algorithm a time complexity of NlogN.
vector <string> v = {"a", "apple b", "apple c", "d"}; // stuff
string find = "apple";
// create a second vector that contains the substring... |
62,688,364 | 62,688,874 | Qt:Where to find the .pro file when developing with visual studio | I want to add sound to my program so I need to add header file “QSound”.
To add the header file, I need to modify the .pro file.
The problem is, I use visual studio to develop projects, so I can't find the .pro file.
I am so confused.
Thanks for your help!
| If you're using Qt VS Tools, use Create Basic .pro File from extensions menu. Note that .pro and .vcxproj files might not be in sync so if possible use Qt Creator to configure your project in the .pro file and then open the project in visual studio via Open Qt Project File
|
62,688,820 | 62,694,394 | <badref> when using CallInst::CreateMalloc for a struct type | I am trying to generate LLVM IR for code (in a toy language) similar to the following C++ code:
struct test {
int a;
int b;
int c;
};
int main() {
tempVar *a;
a = new test();
}
Unfortunately, when I run verifyModule, I receive the following error messages:
Instruction referencing instruction not embedded in ... | The documentation for the function you call says "Note: This function does not add the bitcast to the basic block, that is the responsibility of the caller."
I have no idea why not, but the caller is you.
|
62,688,978 | 62,689,060 | C++: Why Protected Constructor Cannot be Accessed in the Derived Class? | Protected member is supposed to be accessible from derived class.
Then, why I got the compiling error in the code below?
class A {
protected:
A() {};
};
class B : public A {
public:
void g() {
A a; // <--- compiling error: "Protected function A::A() is not accessible ...". Why?
}
};
int main() {... | protected members could be accessed from derived class, but only when through the derived class.
A protected member of a class is only accessible
...
to the members and friends (until C++17) of any derived class of that class, but only when the class of the object through which the protected member is accessed is tha... |
62,689,426 | 62,705,530 | Loop condition works well with raw iterator but not with iterator dereferencing | In the snippet below,
while(litr < = ritr) works well, but while(*litr < *ritr) can not be met and goes out of range and crashes when try to search element which is not present in vector. I understand, loop will work with raw iterators but Why loop condition can not be met with iterator dereference?
bool binarySearch(... | I don't understand what you mean by "iterator deduction". I think you mean "dereferencing"?
Anyway, you're asking about while(litr <= ritr) (which works) compared to while(*litr < *ritr) (which fails). There are several differences.
LessThanOrEqual vs. Equal
The working code uses <= rather than just <, and the equals p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.