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 |
|---|---|---|---|---|
64,517,100 | 64,517,200 | In a non-void function I want to return nothing | I have a function which returns a pointer. In this function I want to check a condition. If this condition is satisfied, I want to return the pointer. However, if the condition is not satisfied I want to print an error log and do not return anything. What should I do in this case? I am not returning anything if the con... |
However, if the condition is not satisfied I want to print an error log and do not return anything.
Well, unless you want to exit the program or throw an exception or something like that, this is not really possible. And the most common way to solve it when you have a function that returns a pointer is to return a nu... |
64,517,119 | 64,517,239 | cin does not accept input properly | I use the following code to get the input
int main() {
int x=0,value=0;
cin>>x;
string str;
for(int i=0;i<x;++i){
cin>>str;
value = findpalindrome(str);
cout<<value<<endl;}
return 0;
}
And these are my test cases:
3
xabcbayabbaz
abcbaabc
abcba
The code accepts the first string and ... | Note that the i++ line in the while loop of your findpalindrome function will never be executed - either the loop will exit (on break) or start again from the beginning (on continue).
Removing the continue; line from the first else if block in that loop prevents the program from going into an infinite loop - but I can'... |
64,517,444 | 64,518,256 | Hexadecimal representation on little and big endian systems | Consider the following code :
unsigned char byte = 0x01;
In C/C++ the hexadecimal will be considered as an int, and therefore will be expanded to more then one byte. Because there is more then one byte, if the system uses little or big endian has effect. My question is to what this will be expanded?
If the system has ... | It is completely architecture specific. The compiler produces the output according to your computer's endianness. Assuming that your microprocessor is big-endian, the compiler will produce;
char x = 0x01; --> 01,
int x = 0x01; --> 00 00 00 01
On the other hand, if you use a cross compiler that targets little-endian o... |
64,517,669 | 64,517,911 | C++ / QT Inheritance Program Architecture | I have several classes, inherited from a base one. I want to add some functionality, a timer to be exact, and functions to handle it, to all child classes, except one. Cause of that I can't just add this code to parent class. What is the best way to handle this task, avoiding code copying? Thanks!
| You can use a mixin, create a class with a timer and other classes that want to use it inherit from it. This class should not inherit form anything if possible.
Edit to add an example:
you create a class without inherit from QObject:
class TimerMixIn {}
Make any class that needs to use TimerMixIn inherit from it:
clas... |
64,518,005 | 64,518,436 | Share data across classess | I'm currently writing a program to read and parse ext2 filesystem C++. I split my program to a few classes, e.g. Ext2 as the main class, Superblock, etc. I have some data that I'll retreive once and I want it to be avilable to all the classes, e.g. block size, etc. What is the best way to achieve data sharing among sev... | You could make a seperate struct containing this data, and make all data sharing classes point to the same instance of this struct (Do watch out for memory leaks though, and maybe consider shared pointers).
struct SharedData
{
int someValue;
};
class Thing
{
public:
SharedData *shared;
void printData()
... |
64,518,019 | 64,518,117 | Why does the C++20 range library have its own namespace? | Why is std::range::sort (and other range-based algorithms) implemented in the range namespace? Why isn't it defined as an overload of std::sort taking a range?
| It's to avoid disrupting existing code bases. Eric Niebler, Sean Parent and Andrew Sutton discussed different approaches in their design paper D4128.
3.3.6 Algorithm Return Types are Changed to Accommodate Sentinels
... In similar fashion, most algorithm get new return types when they
are generalized to support sentin... |
64,518,244 | 64,518,383 | When constructor raises, should/could I call destructor ? Possibly on attributes? | I have a class DLXMatrix with constructor delegation. it as a simple constructor:
DLXMatrix::DLXMatrix(int nb_col);
And another more advanced one which is currently:
DLXMatrix::DLXMatrix(int nb_col, const std::vector<std::vector<int>> &rows)
: DLXMatrix(nb_col) {
for (const auto &r : rows) // TODO : cleanup ... |
When constructor raises, should/could I call destructor ?
No.
If exception is thrown out from a constructor, then the object never existed. It should not and cannot be destroyed.
Whether you catch in constructor or not, destructor should never be called in the constructor body.
Note that some classes may indeed need ... |
64,518,361 | 64,518,392 | Replace a char in array of string when IF statement is satisfied | I'm trying to create a method where an array of char "s" is entered along with 2 other chars char1 and char2, this method called substitute will then search through the array and if it spots an instance of char1 FOLLOWED by "!", it will replace that char1 with char2.
However, when testing my method it doesn't seem to ... | Your code increments i twice - once as part of for statement, and again in the body of the loop. The effect is that you only check even-numbered characters, skipping every other character.
|
64,518,404 | 64,518,470 | C++ getting undefined symbols for architecture x86_64 when using a pointer | I know that "oh no I got this error: Undefined symbols for architecture x86_64" questions have already been asked numerous times here, but none of them were able to help in this specific situation. I have a static pointer variable called "pointer" in my class's header file, and in a "GetSingleton" method, it will alloc... | In your counter.hpp header file:
static Counter* pointer;
is a declaration rather than a definition - it simply declares that pointer exists, without creating it.
To create it, you need:
Counter * Counter::pointer;
somewhere, probably in counter.cpp.
|
64,518,590 | 64,518,760 | MSVC Bug? Overloaded member not found for constrained function | This code fails to compile using MSVC 19.27.29112.0, but works with GCC 10.2.0. C++20 is enabled in both cases:
template <typename T>
struct Blah {
void blah() requires (sizeof(T) == 4);
};
template <typename T>
void Blah<T>::blah() requires (sizeof(T) == 4) {}
int main() {
Blah<int> b;
b.blah();
ret... | (Too long for a comment.) This looks like a bug, indeed, and I suggest you formally report it.
Curiously enough, the following works, instead.
template <typename T>
struct Blah {
enum { sizeofT = sizeof(T) }; // or: static const size_t sizeofT = sizeof(T);
// or: static conste... |
64,518,607 | 64,519,040 | Program to track the passing of a ball in a circle of 10 people using boolean | I am stuck on this problem. Any help would be appreciated.
You have ten people sitting in a ring as shown below. A ball is continuously passed around the ring in
sequence. Initially person 0 has the ball. A user inputs a number between 0 and 9 inclusive. The ball is
then passed down that number of people. For example, ... | I wrote this before the edit, so refer to your original code to see the differences. I added comments to explain what I did.
One of the problems is the lack of {} around the code after the if statements. Without them only the first statement after the if is conditional.
if(newLocation == 0)
cout << "\nPerson zero... |
64,518,622 | 64,519,765 | Erasing container that holds a shared pointer also deletes the object that's being pointed to? | For example, using raw pointer:
Object *obPointer = new Object(); //dynamically allocating memory, meaning we have to delete it, ourselves, later
std::unordered_map<std::string, Objects*> objContainer; //container that holds a string key and a pointer to an object type.
objContainer.emplace("A", obPointer); // placin... | So, like Dave mentioned, I should've used an unique pointer. In my example, by erasing the container, it would not free up the memory allocated with shared_ptr. It would only delete the memory if it ran out of scope or references.
Therefore, as Dave suggested, I used an unique_pointer to created the memory, then I "pas... |
64,518,984 | 64,560,339 | How can I queue a function to be executed in a Qt application's main thread with as high priority as possible? | I would like to be able to have a separate thread queue a std::function to be executed in a Qt application's main thread with as high a priority as possible, meaning that executing this function takes precedence over anything else that is happening in the main thread, save for any task the main thread is currently exec... | Here is the solution I settled on:
#define kFunctionEventType ((QEvent::Type)(QEvent::User + 1))
class FunctionEvent : public QEvent {
public:
FunctionEvent(const std::function<void()> &inFunc) : QEvent(kFunctionEventType), func(inFunc){};
std::function<void()> func;
};
class FunctionEventReceiver : public QO... |
64,519,008 | 64,519,308 | Is a diagnostic required for incorrect uses of non-dependent names in a template that is never instantiated? | Here's what the standard says about non-dependent names in a template definition:
Non-dependent names used in a template definition are found using the usual name lookup and bound at the point they are used.
[Example 1:
void g(double);
void h();
template<class T> class Z {
public:
void f() {
g(1); ... | Ill-formed NDR is a specific case of ill-formed. In the example, the definition of class template Z clearly is ill-formed; whether or not a diagnostic is required depends on whether or not an instantiation of Z occurs anywhere in the translation unit, which the example appears agnostic about (since it admits that there... |
64,519,236 | 64,519,397 | Concept Regular vs. Concept Semiregular | Are there programming models that clearly differentiate the use of the regular concept and semiregular concept?
According to the elements of programming, the regular concept has a clear mathematical definition. I gather that the semiregular concept (from the draft) is a regular concept without the == comparator overloa... | To constrain a template against a concept is to, essentially, make the claim that the template will freely use any of the expressions that the concept requires. If you are writing a template that, by the nature of the algorithm being implemented, has no need to do equality tests, then there is no point in excluding a t... |
64,519,453 | 64,519,502 | C++ multiple access specifiers and order of initialization | We know that in the following code
class Foo1 {
private:
int i;
bool b;
public:
Foo1() : i(7), b(false) {}
};
"i" is going to be init before "b". If I try to init "b" before "i", I'll get a warning.
what about this case:
class Foo2 {
private:
int i;
private:
bool b;
public:
// what happens if ... | The order of initialization is guaranteed; i is always initialized before b. Non-static data members are initialized in the order of their declaration in the class definition, regardless of their access specifiers.
[class.base.init]/13.3
Then, non-static data members are initialized in the order they were declared in ... |
64,519,537 | 64,519,551 | Why Could Not Deduce Template Argument When Function Returns a Struct Template | I'm trying to overload a CreateBST function which accepsts an iterable container of elements and its size. The code is as follows:
#include <iostream>
#include <vector>
template <typename ElementType>
struct BTreeNode
{
ElementType value;
BTreeNode<ElementType>* left;
BTreeNode<ElementType>* right;
};
tem... |
Can someone explain me why I am getting this error?
Template parameters can only be deduced from the arguments at the call site. While that information, i.e. ElementType is actually present in the type of the first argument, your template doesn't know how to extract that type.
how am I supposed to declare a functio... |
64,519,623 | 64,519,630 | How to obtain the return type of a function passed into a templated function or class? | How does one obtain the return type of a function (passed into a higher-order function/class) in this fashion:
template <typename F>
auto DoSomething(F&& func) -> /* whatever type func returns */
{
// whatever...
return /* something that is func's type */
}
Edit: especially if func required parameters of type... | Indeed, you can use decltype like this:
template <typename F, typename T>
auto DoSomething(F&& func, T number) -> decltype(func(number))
{
// ...
return {};
}
Here's a demo.
|
64,519,677 | 64,519,700 | C++ function not updating variables | I have a program designed to simulate a ball bouncing in C++ and save the position, and velocity of it. I have a ball class to simulate many of them at a time and for some reason when I run the update function to update the ball, none of the variables update.
Ball class:
class Ball
{
public:
float x... | Ball ball = balls.at(k);
This retrieves one of the Ball objects from the vector, and creates a new object called ball that's a copy of it.
ball.update();
This calls update() on this ball object. Since it's a copy of the original object from the vector this, of course, does nothing whatsoever to the object in the vect... |
64,519,721 | 64,609,243 | How to update $@ into a Makefile variable dependent target rule? | I have a Makefile defining a variable dependent target like so:
SRCFILES=./src/main.c ./src/file.c
# Get the filenames of all the sources
SRCNAMES=$(notdir $(SRCFILES))
OBJDIR=./obj/
# Replace .c to .o in all source names
OBJNAMES=$(SRCNAMES:.c=.o)
# Add the obj/ repository as prefix
OBJFILES=$(addprefix $(OBJDIR), $(... | When make parses a Makefile it will expand all the variables upon building a dependency tree for targets that are not implicit targets. So when you call make debug it tries to build myprog, which in turn tries to build obj/main.o, not obj/debug/main.o, since the $(OBJFILES) has already been expanded when the rule for m... |
64,520,624 | 64,520,654 | How to print the butterfly pattern using C++? | So I am taking a C++ course during which I was asked to write a program to print the following butterfly pattern:
* *
** **
*** ***
********
********
*** ***
** **
* *
So, this is what I wrote:
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
for(int row=1; row<... | The condition j>=(2*n)-row is wrong.
You will want to make row characters from left and row characters from right to be * and the other characters to be space.
For example, let's consider row=1 case.
Considering "from left" part, the condition j<=row is correct and it will be true in one situration j=1.
On the other ha... |
64,520,726 | 64,520,747 | Empty vector characterstics in C++ | The following function in the program searches for a target value in matrix and returns true if it is present else false and it gave error when a vector - ([]) or ([[]]) is passed i.e. whenever we passed an empty vector.
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int i = 0;
int... | In this expression:
if (matrix.size() == 0 || matrix[0].size() == 0)
if matrix is empty, then the first condition before the || will evaluate to true, and the right hand side won't be evaluated, due to short circuiting.
In your code, you are indexing into matrix[0] unconditionally. If matrix is empty, this invokes und... |
64,520,737 | 64,520,789 | Trying to return a Bool Value from a class in C++ | I'm very new to the world of coding and C++. I'm tasked with taking numbers from a .txt doc with different lines of values. I need to do error checks on each line to make sure the file is in the correct format. I was hoping to make a class that I can reuse in order to do these checks. i,e:
get data from first line
che... | The bool value is returned from the function errorCheck, not the class itself.
You can store the return value to a variable like this:
bool checkRes = checkOne.errorCheck();
if (checkRes == true) {
//Do code here
}
else if (checkRes == false) {
//Do code here
}
or simply do:
if ... |
64,521,289 | 64,521,346 | how to implement named parameter like property in c++ | I have a sorting function inside class Array and wanted to achieve something like in python sort(reverse=True). I want to show user that they can pass this parameter because right now arr.bubble_sort(true); (check the code) dose not make much sense. I don't want lambda functions any idea how to achieve this.
Any other... | Just provide this overloads:
void bubble_sort(std::function<bool<int, int>> cmp) {
...
if(cmp(arr[j], arr[j+1])){
std::swap(arr[j], arr[j+1]);
}
...
}
void bubble_sort(bool rev = false)
{
bubble_sort(rev ? std::greater<int>{} : std::less<int>{... |
64,521,296 | 64,533,614 | How to translate a virtual-key code to char (depending on locale)? | I am playing around with translating user's keystrokes between the different installed languages on their Windows machine.
I found this article about virtual-key codes, and how they map to characters, and also this function to perform the mapping. But it doesn't seem to work like I expected it to.
This is my attempt at... | You can use ToUnicodeEx API.
And if you want to output characters correctly, you can refer to: How to print Latin characters to the C++ console properly on Windows?
I created a sample and used the following code:
int main()
{
SetConsoleOutputCP(1256);
_setmode(_fileno(stdout), _O_U16TEXT);
HKL lpList[2];
... |
64,521,652 | 64,758,878 | Create xlib window with a frame buffer i can draw directly and use XPutImage | I'm trying to create a xlib window, create a frame buffer that has a depth of 32 and draw that buffer to the window, However. Everything works until XPutImage gets called, the window never shows and the console outputs:
Process returned -1 (0xFFFFFFFF) execution time : ?.??? s
Press ENTER to continue;
If i comment out... | To get it to work, I had to change two lines in the code. You probably won't be happy because to get it to work I had to change it from RGBA to BGRX. Whenever I work with xlib I always had to use a 24 bit depth even though the data is stored in 32 bits. It is also stored BGRX not RGBX...
Here is the changed code.
#in... |
64,521,907 | 64,521,967 | C++ TitleCase char* function returning "CCCCC" at the end of every Google C++ Test | I'm trying to create a char* toTitleCase(char* text) function that makes every word in a text start with a capital letter.
Here is my current code:
char* toTitleCase(char* text)
{
char* arr = new char[strlen(text) + 1];
for (int i = 0; *(text + i) != '\0'; i++)
arr[i] = *(text + i);
... |
I specifically allocated the length of the text + 1
There's your hint - what is the length of the text?
Change this:
for (int i = 0; *(text + i) != '\0'; i++)
arr[i] = *(text + i);
To this:
for (int i = 0; *(text + i) != '\0'; i++)
printf("%c", *(text + i));
And it will answe... |
64,523,140 | 64,523,425 | How use the custom key in openssl in AES_set_encrypt_key | I try implement the encode and decode using openssl, using a code how example, but when i try use a custom key, the code broken, what is the currect form to set a custom key and a custom input to use in openssl (I believe that the error is in my logic in C and not at use of openssl)
const char *in = "test";
si... | Using a text string as AES key is not a good idea because:
An AES key must be exactly AES_KEY_LENGTH bytes in size.
"my_custom_key", being 13 bytes, is too short.
ASCII text has low entropy, and will severely reduce the security of the encryption.
The standard solution to this is to use a key derivation function, e... |
64,523,154 | 64,531,024 | What's the difference between push_back({ "George", 1 }) and push_back(Student("Jack", 10)); | I was just wondering if there's a difference between the following two lines:
objStudents.push_back({ "George", 1 });
objStudents.push_back(Student("Jack", 10));
Is one way more efficient than the other? Or is it just a different syntax that completes the same task?
| Assumming Student has a constructor with the right arguments, the difference is that while objStudents.push_back(Student("Jack", 10)); always compiles,
objStudents.push_back({ "George", 1 }); only compiles if the constructor is not declared explicit. On the other hand, if Student is an aggregate (e.g. struct Student { ... |
64,523,243 | 64,523,652 | C++ Program Gets Crash on recalling Function from Main? | I have a class Movie with data members genre Actors and size.
class Movie
{
private:
string* Actors;
string* genre;
int size = 0;
I have used setters and getters method to initialize the data members. First I have set the size to 2 from main by calling the
setsize()
member function for genre and then cal... | Least fix will be preparing separate variables for
size of current Actors
size of current genre
size for next reading
It will be like this:
class Movie
{
private:
string* Actors;
string* genre;
int Actors_size = 0, genre_size = 0;
int size = 0;
public:
Movie()
{
Actors = new string[siz... |
64,523,302 | 64,561,686 | CUDA: "missing return statement at end of non-void function" in constexpr if function | when I compile the following test code, I get this warning:
test.cu(49): warning: missing return statement at end of non-void function "AllocateSize<T,D>(size_t) noexcept [with T=int, D=Device::GPU]"
detected during instantiation of "Pointer<T, D> AllocateSize<T,D>(size_t) noexcept [with T=int, D=Device::GPU]... | Our compiler team looked at the issue. The warning is a spurious warning. We hope to address it in a future CUDA release. I won't be able to respond to questions about when that may be. The code is being generated correctly.
If you wish to silence the warning, a possible method is to add an additional return statem... |
64,523,432 | 64,523,508 | How to put a string inside a std::vector<char>? | I have a vector of char that its all elements are initialized by '-' like this:
vector <char> vec (10, '-'); //vec = "----------"
consider we have two inputs: a string and an integer representing the starting index. for example:
string word = "HELLO";
int start = 3;
I Want to put word inside the vector vec startin... | std::copy(word.begin(), word.end(), vec.begin() + start);
|
64,523,550 | 64,768,902 | No rule to make target 'VLCQtWidgets/WidgetVideo.h', needed by 'ui_mediaplayer.h' | I am developing a media player using vlc-qt. So what I have done till now is I have clone the git repository of vlc-qt and have build that using BUILDING.md and in my '''pro''' file of Qt I have added the path of my vlc-qt installation like below
INCLUDEPATH+= /home/vinay/vlc-qt/build/include
LIBS+= -L/home/vinay/vlc-q... | You need to include this line in your pro file
INCLUDEPATH+= /usr/local/include
The reason for this error is become the ui file is not able to access the header file because the actual system path is not included in your pro file and most of the time in Linux the vlc-qt files are installed on this location
/usr/local/... |
64,523,630 | 64,523,673 | How do i write a program that calculates the product of a number's digits that are different from another number i input? | I have to input 2 numbers, n and k, and find the product of n's digits which are different from k.
Example: n = 1234, k=2, and the product should be 1 * 3 * 4;
#include <iostream>
using namespace std;
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while(true){
digit= n % 10;
i... | The problem is the while(true). In this way the program stay in the loop for eternal.
A possible solution can be this:
int main()
{
int n, k, p=1, digit;
cin >> n >> k;
while( n > 0 ){
digit= n % 10;
if(digit != k){
p = p * digit;
}
n = n/10;
}
cout ... |
64,523,642 | 64,523,643 | Intel c++ compiler: how to compiler and link openmp pragma in macro definition/define? | I have a simple code which uses pragma in macro definitions. The code compiles and runs fine using QtMinGW just fine.
#include <omp.h>
#include <stdio.h>
#define NUMEL 1024
#define OMP_PARALLEL _Pragma("omp parallel")
#define OMP_FOR _Pragma("omp for")
#define main_func(par) \
in... | After tones of try and error some Q/A on icc forum it turns out
_Pragma should be replaced with __pragma
no need for quotes
so the intel/icc syntax for using omp pragmas in a macro definition should be corrected as below:
#define OMP_PARALLEL __pragma(omp parallel)
#define OMP_FOR __pragma(omp for)
I hope it help ot... |
64,523,816 | 64,523,992 | QTreeWidget MouseMove event is not called | Here is the code
#include <QTreeWidget>
#include <QEvent>
class CustomTreeWidget: public QTreeWidget
{
Q_OBJECT
public:
CustomTreeWidget(QWidget *parent = nullptr);
protected:
bool eventFilter(QObject *target, QEvent *event) override;
private:
Q_SLOT void OnItemEntered(QTreeWidgetItem *item, int colu... | QTreeWidget inherits QAbstractScrollArea so you need to intercept the mouse move events in the associated viewport rather then the QTreeWidget itself...
CustomTreeWidget::CustomTreeWidget (QWidget *parent)
: QTreeWidget(parent)
{
viewport()->setMouseTracking(true);
viewport()->installEventFilter(this);
co... |
64,524,123 | 64,524,161 | Printing functions in cpp | Why is it that any time i print a function in cpp, it prints 1. i.e
#include <iostream>
using namespace std;
void f1(){
cout<<"called function f";
}
int f2(){
cout<<"called f2";
return 1;
}
int main(){
cout << f2 <<endl; // prints 1
cout << f1 <<endl; // still prints 1
}
Im just wondering why it prints ... | It seems it is judging if the functions (converted to pointers to functions) are not null, returning true, and printing true as 1. This can be confirmed by adding cout << std::boolalpha; and seeing the the output is changed to true.
#include <iostream>
using namespace std;
void f1(){
cout<<"called function f";
}
int... |
64,524,360 | 64,524,373 | Adding one value at the end of c++ array | I want to add one more value into C++ array, and I have this piece of code:
void print_array(int *array, int size)
{
for (int i = 0; i < size; ++i)
{
std::cout << array[i] << ' ';
}
std::cout << '\n';
}
void add_to_array(int *array, int size, int value)
{
int *newArr = new int[size + 1];
... | Function arguments of C++ are copies of what are passed and changing them won't affect what are passed. You should use references to have functions change what are passed.
Also note that now the new array has size + 1 elements and the index of the last element is size, not size + 1.
Fixed code:
void add_to_array(int *&... |
64,524,992 | 64,525,284 | Temporary captured-variables in lambda functions - C++11 | I was trying out something like this to pre-populate a map using a vector-list of strings.
The code is self-explanatory:
Constructor(const vector<string>& names) {
for_each(names.begin(), names.end(),
[this, counter = 1](const String& choice) mutable {
nameMapping.empl... | When you set counter = 1 you're declaring a new temporary counter equal to 1. The compiler does the work of determining the type. This temporary object is deduced to type int by default, and lives while the lambda is alive.
By setting mutable you can both modify counter and this
Aside: since it appears that you're inse... |
64,525,096 | 64,525,136 | Cannot edit data stored in a linked list's node using setter | My Node class:
class Node {
private:
int orderId; //unique for each node
Cake cake;
Customer customerInfo;
Node* next;
public:
Node() {
orderId = 0;
next = NULL;
}
Node(int id, Cake ck, Customer c) {
orderId = id;
cake = ck;
customerInfo = c;
... | It's because your getCake method returns a copy of the cake in your Node object. Your setter then changes the copy, but this leaves the original unchanged.
Simple fix is to make your getter return a reference
Cake& getCake() {
return cake;
}
Now getCake returns a reference to the cake in the node, not a copy of it... |
64,526,087 | 64,526,185 | C++ Deleting array of structures with delete[] | I'm having trouble with adding structures to array in cpp. I've came up with this method which works great on ints but when i want to do the same thing on structures im getting error after adding 3 or more. I debugged it a little bit and it seems that delete[] is causing error message "Segmentation fault (core dumped)"... | The problem is probably trying to copy an std::string with memcpy.
std::string is not a POD (Plain Old Data) object, and some compilers and
certainly static code analyzers e.g. SonarQube or Klocwork will alert you that
what you are doing is wrong.
To accomplish a copy correctly you should define an assignment operator ... |
64,526,291 | 64,526,403 | Type of a class that has variadict template in another class body | I am not an expert in template metaprogramming, and I am kind of stuck now. Any help would be appreciated.
As an introduction.
I have a class (a bit simplified here):
template < int dim, int spacedim, int... structdims >
class TopologyInfo
{
}
I can create an instance of TopologyInfo with functions:
template < int dim... | auto is just a placehold for the actual type. When you write
auto t = get_topology_info< 3, 3, 3 >( );
then t is of some specific type. The fact that you used auto doesn't change that.
If the actual type is too unwieldy to be spelled out or not readily known, you can also use autos cousin decltype. For example this is... |
64,526,361 | 64,526,463 | C++ Mixin using derived types | How can I pass along typedefs from a class to its mixin? At first I thought it may have been naming conflicts, but renaming value_t in the mixin doesn't help either.
template <typename Derived>
class Mixin
{
public:
using value_t = typename Derived::value_t;
Derived * self()
{
return static_cas... | At the point where Mixin<DerivedInt> is instantiated, DerivedInt is an incomplete class - the compiler hasn't seen any of it beyond class DerivedInt. That's why DerivedInt::value_t is not recognized.
Perhaps something along these lines:
template <typename Derived, typename ValueType>
class Mixin
{
public:
using val... |
64,526,453 | 64,527,643 | Pointer to member variable as static member | These days I was fiddling with a project study for a data model with a kind of reflection suitable to my needs.
While I got my first study running with the recent stable version of g++, I failed in Visual Studio 19. Too bad, because the latter is my primary platform…
Effectively, I try to store a pointer to member vari... | @doug gave me the hint that he got my code running in VS 2019 without any complaints.
After a long chat, he gave me the hint to test my above samples in a new created VS solution. All I had to do, was to enable C++17 (/std:c++17) and then MSCV compiled all the samples without complaints.
I must admit that I usually use... |
64,526,724 | 64,526,780 | Wrapping method with default argument that is a null pointer to another wrapped type | Consider the following C++ code:
struct A { };
struct B {
void f(A *a = nullptr) const;
};
How can I wrap this properly using boost::python? In particular the default argument. The following fails miserably1:
bpy::class_<B>
// Explicitly converting the nullptr to A* does not solve this:
.def("f", &B::f, b... | So this was quite... simple, in the end. Just need to wrap the null pointer in a bpy::ptr:
bpy::class_<B>
// The cast to A* is mandatory otherwise bpy::ptr cannot deduce the type:
.def("f", &B::f, bpy::arg("a") = bpy::ptr((A*)nullptr));
|
64,526,835 | 64,527,399 | copying 2d matrix file into a 2d vector with unknown size | I have a file which is made up of unknown rows but 2 columns and I would like to read this to a 2d vector, but I cannot achieve it, as my code skips the first columns all the time, i dont know why
I have written the code as follows:
#include <iostream>
#include <fstream>
#include <vector>
// this is for file handleing
... | The problem is in the line
inner_vector.push_back(stoi(token));
What you thought you were doing was passing in things like "0" then "3", then "0" etc. But the thing is you were passing in things like "0", " 3\n0", " 7\n0". The getline ignores the endline and when passing in something like " 3\n0" into stoi it returns ... |
64,526,900 | 64,527,299 | character variable storing issue with scanf | I am trying a simple program which will create a linked lists and display the elements afterwards.
In this program, i am using a char variable ch to store yes/no for entering more nodes in the linked lists.
Consider the following program:
#include<stdio.h>
#include<malloc.h>
struct node
{
int num;
struc... | I am not sure of the reason but just put a space in your scanf("%c",&ch) and it will start working.
Just change it to scanf(" %c",&ch)
You can check if there is a reason somewhere for this and comment it out but for now this will help you. Just a guess it might be that the new character read by ch is new line which ter... |
64,526,950 | 64,559,700 | Custom iterator for value checking | I am new to iterators and trying gain more knowledge about them.
That's why I'm trying to create a custom iterator to traverse given string array to check if any values of that string is a decimal value or not. I come up with the implementation given below:
Collection is the user of my iterator
// Collection type
templ... | So basically, my post and pre increment implementation were not correct. When I changed them as below, it works.
bool operator==(const CollectionIterator &other)
{
return data == other.data;
}
CollectionIterator<T>& operator++()
{
data++;
return *this;
}
CollectionIterator<T> operator++(int)
{
Collec... |
64,527,027 | 64,527,335 | Can I determine the type of an rvalue reference? | I have a serialize function that performs differently based on the type. I'd like to be able to call it with both f(x) and f(5), but f(5) fails with error No matching function for call to 'f', Candidate function [with T = int] not viable: expects an l-value for 1st argument. If I change f(T& t) to f(T&& t) then f(x) is... | You can use a forwarding reference, T&&, to take the argument by either lvalue- or rvalue reference depending on what's passed in.
In case of lvalue, T = int&, so we need to use std::decay_t to remove the reference from the type.
When we pass an rvalue, T = int and decay does nothing.
#include <type_traits>
#include <s... |
64,527,224 | 64,527,599 | Is it possible to put multiple names in one string? | I just started learning C++ and I'm currently following a tutorial on YouTube.
I thought it was fun to make a very simple 'access' program. If I type in my name it says, "Welcome!" If I type in another name it says, "access denied". It worked perfectly fine, but then I wanted the program to say "Welcome!" to two differ... | The problem is in the string variable "name". You need an array of strings, not a single string.
This is an example implementation:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string names[] = {"Joe", "Sean"};
string input;
cout << "What is your name?\nMy name... |
64,527,229 | 64,527,623 | Calling a "__device__ __host__" function from an external file by a CUDA kernel function | I'm trying to play with mixing CUDA and C++. I encountered the following error:
main.cpp: define "main()". Call "gpu_main()" and "add_test()"
| |--> add_func.cu: define "gpu_main()" and "__global__ void
add()" as kernel. The "add()" will call "add_test()" |
|--> basic_add.cu: define "__host__ __device__ int
add_test(i... | One of the things you are trying to do here isn't workable. If you want to have a function decorated with __host__ __device__, first of all you should decorate it the same way everywhere (i.e. also in your header file where you declare it) and such a function won't be directly callable from a .cpp file unless you comp... |
64,527,737 | 64,529,537 | C++ 17 Metaprogramming recursive struct: enum or constexpr | For illustrative purposes, I'm showing two small, slightly different templated recursive definitions. One uses an enum and the other uses static constexpr to define a value.
I have inspected the output assembly from both programs, and they are exactly the same, and semantically they also appear the same.
I think conste... | The most significant difference (since C++17 avoids the need for an out-of-class definition for the static data member) is that enumerators are instantiated along with the containing class, whereas static data members are instantiated only when needed. (Note, however, that MSVC, at least, doesn’t always properly defer... |
64,527,951 | 64,528,199 | Why is std::pair from anonymous object copying that object instead of moving? | I tried to make std::pair with this style:
#include <iostream>
struct A {
A() noexcept {
std::cout << "Created\n";
}
A(const A&) noexcept {
std::cout << "Copy\n";
}
A(A&&) noexcept {
std::cout << "Move\n";
}
};
int main() {
std::pair<A, A> a{ {},{} };
return 0;
... | There's a problem with how std::pair is defined. I'd even say it's a minor defect in the standard.
It has two constructors that could be used here:
pair(const T1 &x, const T2 &y);, where T1, T2 are template parameters of the pair.
template <class U1, class U2> pair(U1 &&x, U2 &&y);
If you do std::pair<A, A> a{A{}, ... |
64,527,994 | 64,528,936 | C++ program to count redundant words in a string using recursion and structures | I am writing a c++ program to display the count of characters, words and redundant(duplicate) words in a string(taken by the user) using recursion and structures.it will terminate when '#' is found in the string. I have done the part for characters and words but couldn't do the redundant count part. Can anyone help?
| Use std::unordered_map, storing the words as keys, and storing the count of each word, as the value.
Once you're walked the length of the input sentence, storing/incrementing the values of present words, then you can iterate from beginning to end of the hash-table, summing up all the values greater than count of 1.
|
64,528,190 | 64,528,719 | Find the number of ways to generate N unique pairs of courses without clashes | I came across this problem and could not think of a good solution. The problem is as follows
There are N CS courses and N EEE courses, both numbered 1, 2, ... , N.
For each i, j (1 ≤ i, j ≤ N), the compatibility of CS course i and EEE course j is given as an integer Aij. If Aij = 1, CS course i and EEE course j do not ... | This is just an expansion of @amit's comment that this looks like Inclusion-Exclusion.
First we take the number of ways to make N pairs. Which is simply N!. In your example, this is 6.
all sets of pairs
(1, 1), (2, 2), (3, 3)
(1, 1), (2, 3), (3, 2)
(1, 2), (2, 1), (3, 3)
(1, 2), (2, 3), (3, 1)
(1, 3), (2, 1), (3, 2)
... |
64,528,273 | 64,528,753 | local constexpr variable introduces compiler error | The following code compiles and works as expected unless you swap the line marked ok for the line marked fails. The only difference is that I'm making a local temporary constexpr variable. I don't understand why it fails in one case only.
#include <array>
using TArray = std::array<int, 2>;
using TSize = TArray::size_... | This behaviour occurs because
The expression myArray.size() that appears inside the function is not a constant expression per se, because it accesses a reference variable whose initialization is not visible within the context of this expression.
The expression Fn(ar) is a constant expression despite the fact that its ... |
64,528,343 | 64,528,403 | How can std::less be safer than < when applied to unrelated pointers? | I've found out that I should use std::less to compare my objects to be able to compare Unrelated pointer (from a different sequences) because just using the relational operator < yields UB if used on those unrelated pointers.
So for practice I've implemented my compare function:
#include <iostream>
using namespace... |
How can be std::less safer than <?
Because the standard says so.
I mean the internals.
On all x64 and most modern architectures std::less::operator() is just a simple wrapper over built-in operator < or the pointers are casted to uinptr_t then compared.
C++ is meant to work on all sorts of hardware architectures so... |
64,528,351 | 64,528,467 | What is wrong to initialize an int vector like this: vector<int> v1 = {1, 2, 3, 4}? | When I initialize a vector in C++ like this:
#include <string>
#include <vector>
using std::vector;
using std::string;
int main() {
vector<int> v1 = {1, 2, 3, 4};
return 0;
}
I got this error:
prog1.cpp:8:15: error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list
vector<int> v1 =... | Initializer lists were introduced from C++ 11 onwards, so you'll need to specify that (or a higher) version while compiling (-std=version) if your using an older standard for default compilation.
|
64,528,865 | 64,529,070 | Why in a template we can use a dependent name without being already declared if not instantiated? | I have written this code to understand template name lookup:
//void bar(int);
template <typename T>
void foo(T x)
{
bar(x);
}
void bar(int x)
{
std::cout << "bar(int)\n";
}
template <int>
void foo(int i)
{
bar(i);
}
int main()
{
foo<int>(4);
std::cout << "\ndone!\n";
}
I've commented out t... | In your program, this definition:
template <int> // not a specialization, just a different
void foo(int i) // template with a non-type template parameter
{
bar(i);
}
does not actually define a specialization of the foo primary template. So when you make this call:
Foo<int>(4);
you end up calling the primar... |
64,529,149 | 64,529,215 | Pointer to Member Function Class Type | class Object
{
public:
void mem_func();
}
I want to be able to extract the type Object at compile time from a pointer to member function &Object::mem_func, but did not notice anything in <type_traits> that could be used to get the type.
This is desired for a Pimpl class that has an abstract data member that would ... | template<auto x>
struct memfunc_object;
template<auto x>
using memfunc_object_t=typename memfunc_object<x>::type;
template<class T, class R, class...Args, R(T::*mf)(Args...)>
struct memfunc_object< mf > {
using type=T;
};
live example.
Requires c++17.
Without it, you can do decltype(&bob::hello) and write a similar ... |
64,529,733 | 64,530,240 | Is clang's global-constructors warning too strict? | In our project we often use a construct like this (simplified for clarity, we actually use a more safe to use version):
struct Info
{
Info(int x, int y) : m_x(x), m_y(y)
{}
int m_x;
int m_y;
};
struct Data
{
static const Info M_INFO_COLLECTION[3];
};
const Info Data::M_INFO_COLLECTION[] = // glo... | The problem is that it is not constant initialized. This means that M_INFO_COLLECTION may be zero-initialized and then dynamically initialized at run time.
Your code generates assembley to set M_INFO_COLLECTION dynamically because of the "global constructor" (non-constant initialization): https://godbolt.org/z/45x6q6
A... |
64,530,128 | 64,530,184 | Revisited: difference between static array and dynamic array in C++? | I'm a beginner for C++ and I saw the post here. However, it is very unclear for me what is the benefit of dynamic array.
One advantage is that one can change the length of a dynamic array, here is the code
int *p = new int[10];
// when run out of the memory, we can resize
int *temp = new int[20];
copy(p, temp); // copy... | int array1[10];
int *p = array1;
// when run out of the memory, we can resize
int array2[20];
copy(array1, array2); // copy every elements from array1 to array2;
p = array2;
In whichever function, or inner scope, array1 and array2 get declared these arrays get automatically destroyed when the function or inner scope r... |
64,530,199 | 64,530,230 | istream operator overloading without function body? what does it mean? | __istream_type&
operator>>(bool& __n)
{ return _M_extract(__n); }
__istream_type&
operator>>(short& __n);
__istream_type&
operator>>(unsigned short& __n)
{ return _M_extract(__n); }
__istream_type&
operator>>(int& __n);
The above code snip comes from libstdc++, which is basically a bunch of operator overloading for... | This is a just an ordinary class method declaration. Nothing out of the ordinary.
When you write your own classes, you must've done the same thing yourself, many times:
class my_class {
// ...
void some_method();
};
and then later defined
void my_class::some_method()
{
// stuff
}
And this is exact... |
64,530,809 | 64,530,867 | Saving a txt file into a folder in the same folder as the cpp file in C++ | I want to make a program that can save a text file into a folder that is in the same folder as the cpp file without having to write down the full path, as the location of the cpp file may be changed.
Example:
I have my cpp in a file called CppFileLocation on my desktop: C:\Users\user\Desktop\CppFileLocation\file.cpp
I ... | Try this:
saveloc.open(".\\CppFileHistory\\" + fileName);
with the dot .
But I can't guarantee to work. Because a C++ program is supposed to be compiled into an executable, then run the executable. When the executable is run, you basically free to pick its "current working directory". What the above code does is, fro... |
64,530,967 | 64,531,134 | Execution order in GCC statement expressions | I found that there is a different execution order between two similar statements(the only difference is the below one has an additional ;). The destructor order is different. Does C++ have a corresponding specification about that or it's only an unspecified behavior?
Environment: GCC10
#include <iostream>
template <in... | This is not standard C++. This is a GCC extension known as statement expression. A compound statement enclosed in parentheses can appear where an expression is allowed. If the last statement in the brace-enclosed block is an expression statement, then the value of this expression is also the value of the overall statem... |
64,531,120 | 64,531,651 | C++ unnamed typed struct member | First, I'll start with what does work:
struct A
{
int a, b;
};
struct S
{
A A_;// Member can be defined elsewhere.
struct B
{
int c, d;
};// Member can be defined locally.
B B_;
struct C
{
int e, f;
} C_;// Member can be instanced on the same line...
C C2_;// ...... | Now that I thought about it, I can see that what I want is impossible.
If something like this is allowed then it creates ambiguities in the case of
struct X
{
int k, l;
};
struct Y
{
X;// unnamed (X1)
X;// unnamed (X2)
};
The near miss solutions are:
Inheritance
struct Y : X {...};
First of all, along... |
64,531,383 | 64,531,968 | C++ runtime error (using -fsanitize=undefined): object has a possibly invalid vptr: abs(offset to top) too big | My code:
const int N = 1048569;
struct A { };
struct B : virtual public A {
char space[N];
};
struct C : virtual public A {
void foo() {};
};
struct D : public B, public C { };
D T;
int main() {
T.foo();
return 0;
}
When I compile my code with -fsanitize=undefined, I got the runtime error below:
a.cpp... | It's an arbitrary size limit set by Clang's UndefinedBehaviour Sanitizer:
https://github.com/llvm/llvm-project/blob/5745eccef54ddd3caca278d1d292a88b2281528b/compiler-rt/lib/ubsan/ubsan_type_hash.h#L55-L57
/// A sanity check for Vtable. Offsets to top must be reasonably small
/// numbers (by absolute value). It's a wea... |
64,531,685 | 66,647,777 | VSCode <error reading variable> when viewing array elements during debugging | I am debugging the following code in VSCode:
int main() {
char arr1[] = {'t', 'e', 's', 't', '\0'};
char arr2[] = "test";
int arr3[] = {1, 2, 3};
double arr4[] = {1.1, 2.2, 3.3};
}
The elements of the first two arrays show as:
116 '<error reading variable>
101 '<error reading variable>
115 '<error read... | The following solution resolved the issue:
I found a workaround in this chinese blog
https://blog.csdn.net/m0_46304383/article/details/113487503
(translated with google transator). It seems a Windows 10 UTF-8
problem. I hope it can also help you @georgetian3.
The workaround is: "Windows Settings" -> "Time and Language... |
64,532,708 | 64,533,166 | Binary number with alternating bits, wrong answer | The question is of checking whether the given number has alternating bits or not.
Link to question - https://leetcode.com/problems/binary-number-with-alternating-bits/
Even though dry run of the code shows that logic is correct but answer is wrong and I don't know what am I missing out in the code or what I have done w... | You got the solution spot on.
It was all about operator precedence creating the bug.
class Solution {
public:
bool hasAlternatingBits(int n) {
int cur = n&1;
n = n >> 1;
while(n > 0){
if(cur == (n&1)){
return false;
}
cur = n&1;
... |
64,534,394 | 64,534,958 | Insert node at specific position | i need to insert a node at a given position in a linked list.
Is there any better way to do it?
Here is my code:
struct node
{
int data;
node* next;
};
void InsertNodeAtPosition(node *& first , int x , int position)
{
//0 based indexing
int i = 0;
node *q = new node;
q = first;
while (i != posi... | The written by you function is wrong has a memory leak and undefined behavior.
For example at first the pointer q is assigned with the address of the dynamically allocated memory and then it is reassigned with the value of the pointer first. So the address of the allocated memory is lost and the memory can not be freed... |
64,534,535 | 64,536,198 | Difference between Run Code and Run without Debugging in VS Code | I am a newbie in cpp programming and use visual studio code, I don't understand what is the difference between Ctrl + Alt + N(To run code) and Ctrl + F5(Run without Debugging).
| Ctrl + Alt + N (Run Code) is a shortcut provided by the "Code Runner" extension you installed while Ctrl + F5 (Run Without Debugging) is a shortcut provided by VS Code by default. Both shortcuts run the code without debugging and they have the same function.
|
64,534,707 | 64,534,907 | Not obtaining desired output C++ | I am working on a triplet code actually. The problem statement goes as follow:
The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2].
If a[i] > b[i], then Alice is awarded 1 point.
If a[i] < b[i], then Bob is awarded 1 point.
If a[i] = b[i], then neither person rece... | The solution of this question is easy. First You need to take array value using loop. Then compare them.
http://cpp.sh/3kk5f
// Example program
#include <iostream>
using namespace std;
int main()
{
int a[3],b[3],r[2]={};
for(int i=0;i<3;i++) cin>>a[i];
for(int i=0;i<3;i++) cin>>b[i];
for(int i=0;... |
64,535,229 | 64,535,526 | weird behaviour of memcpy | I want to copy an unsigned long integer to char buffer byte by byte.
If I use the line under comment, it is not copied to buffer.
char buf[128];
//unsigned long int_val = 268435456;
unsigned long int_val = 293456376;
cout << "Value of int_val: " << int_val << endl;
memset(buf, 0, sizeof(buf));
... | In hexadecimal, 268435456 is 1000000016. Your C++ stores the bytes of an unsigned long in memory with the low-value byte earlier in memory, so this is stored in memory as bytes with values 0016, 0016, 0016, 1016.
memcpy correctly copies these bytes into buf.
Then, when strlen(buf) examines buf, it finds a null byte (00... |
64,535,307 | 64,536,131 | Turn widget's focus on and off based on mouse enter/leave event | I want to turn on Gtk::SpinButton entry focus when mouse pointer enters this widget and then turn it off again when the pointer leaves.
The signal event doesn't seem to respond while the window is still running. But the std::cout outputs are printed after I close the window.
How do I implement my expected widget behavi... | Huge THANKS to underscore_d's comments above.
The answer to this is to direct our focus to another widget when mouse pointer leaves Gtk::SpinButton widget and for enter event, grab the focus back.
Just turning on and off with set_can_focus() won't work.
Below is the corrected solution:
#include <gtkmm.h>
#include <iost... |
64,535,437 | 64,535,796 | Unit test for ensuring conditionally compiled code in c++ | This is a standard C++ ASSERT macro defined in my code -
#ifndef DEBUG
#define ASSERT(n)
#else
#define ASSERT(n) \
if (!(n)){ \
printf("%s - Failed ", #n); \
printf("On %s ", __DATE__); \
printf("At %s ", __TIME__); \
printf("In File %s ", __FILE__); \
printf("At Line %d\n", __LINE__); \
exit(1... | First the obvious the following raises only an error when DEBUG is defined.
ASSERT(index == num);
ASSERT(index != num);
For unit tests for both cases: production and development, you need to compile both ways.
You might effect that by your own #define/#undef DEBUG.
Good practice? I do not know; I was not aware that th... |
64,535,485 | 64,551,272 | Send json document with ESP8266 | I created a function to send a sensor value with a name to a node.js server with a http post request.
I use ArduinoJson V6 library and ESP8266HTTPClient.h
so i wrote this :
void stk(String name, float value)
{
if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
{
digitalWrite(2, HIGH);
Dynamic... | You showing the message in the comments leads me to the following analysis:
Read the ArduinoJson V6 documentation on the serializeJson() function
This function treats String and std::string as streams: it doesn’t replace the content, it appends to the end.
I.e. because you reuse postmessage, which is probably a globa... |
64,535,527 | 64,538,162 | How to launch the same linux process with different arguments in multiple threads with Poco process | When trying to launch the same C++ Linux program, with different arguments and with Poco::process, I get exit 72 code from my second DummyProcess.
This code snippet below is executed in a thread function, which launches every other time, with different task and duration arguments.
When task-1 is running and task-2 want... | I finally found an answer. I ignorantly didn't mention that i was running Linux in virtual box on windows host and was using a shared folder..
I noticed that when launching an executable it's permissions change to -rw-rw-rw from -rwx-rwx-rwx, and i couldn't change them with chmod. So i noticed something fishy here and ... |
64,536,053 | 64,536,462 | Flutter Desktop: How to handle Native Code editing in an IDE (Intellisense, Autocompletion, etc.)? | I am an absolute beginner to C++. I am working with a Flutter Desktop Plugin. Everything is fine just I am unable to configure native code editing properly (Intellisense, Autocompletion, etc.) as it's just acting as a plain text. I have a linux named directory in my flutter project, it seems to be a C++ project. How do... | You said you're working on an application, but you've shown the CMakeLists.txt for a plugin. As on mobile, desktop Flutter plugins aren't stand-alone buildable projects; they are meant to be built in the context of an application. That's why opening it directly gives you a missing command.
When editing a plugin, you sh... |
64,536,266 | 64,536,625 | Pushing an array of pointers into a std::vector avoiding copying the objects with push_back | In this code, an array of pointers newData is created in a for loop then it is pushed into a vector testData. The pointers are stored in the vector std::vector<testData*>.
My concern is that I need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them. Do I los... |
Do I lose this reference by calling the line newData = new unsigned char[frameSize]; in a for loop?
No, if done correctly it's perfectly feasible.
The are some problems in your code though, in the line memset(&newData, 0, frameSize); // ?? you're setting the memory occupied by a pointer, which is usually no more than... |
64,536,272 | 64,579,922 | The issue about the deferred dynamic initialization | Consider the example in the section basic.start.dynamic, that is:
// - File 1 -
#include "a.h"
#include "b.h"
B b;
A::A(){
b.Use(); //#1
}
// - File 2 -
#include "a.h"
A a;
// - File 3 -
#include "a.h"
#include "b.h"
extern A a;
extern B b;
int main() {
a.Use(); //#2
b.Use();
}
The comments follow the examp... | Evolution of the clause
The (non-normative) example in question dates back as far as the C++98 edition of the Standard, but the (normative) language in the hosting clause was changed in C++17.
C++98:
3.6.2 Initialization of non-local objects [basic.start.init]
3 - It is implementation-defined whether or not the dynami... |
64,536,279 | 64,550,202 | QStorageInfo is not working with read only rootfs | I am using qt revision 5.7.1 on my debian strech system. I have mounted my rootfs as read only using overlayfs ,I have used QStorageInfo to check my SD card size.
After mounting rootfs as read only i am getting only root directory in QStorageInfo mountedvolumes.
Below is the source code to get storage list:
foreach (c... | QStorageInfo is trying to read /etc/mtab to get the mountedvolumes.
/etc/mtab can not generate because of readonly rootfs.
/etc/mtab is symbolic link of "../proc/self/mounts".
so it is required to generate smbolink link from "../proc/self/mounts" to /etc/mtab before creating read only system.
|
64,536,429 | 64,785,640 | Implementing an efficient and convenient constructor for a C++ vector class template | I'm trying to implement a constructor for a C++ vector class template that is both efficient and convenient to use. The latter is, of course, somewhat subjective — I'm aiming at something like Vec2D myVec = Vec2D({1.0, 2.0}).
To start with, I'm thinking about a class template for fixed-length vectors, so no immediate u... | You could also make use of parameter packs, which (combined with some nice polymorphism) can enable you to do stuff like this:
Vector<int, 3> v1{std::vector<int>{1, 2, 3}};
Vector<double, 3> v2 = {5., 6., 7.};
Vector<float, 3> v3 = v1 + v2;
Where Vector is defined as follows:
#include <vector>
#include <array>
#includ... |
64,536,446 | 64,539,159 | Where are variables stored in Inherited Classes in C++/ | There have been several questions similar to this but none have answered something I don't understand about inheritance in C++.
I have a simple Parent and Child class the child inherits from the parent. The example here just has a child which is the exact same as the parent but it's value for the integer a is always 0.... | Whats wrong is
Child(int b){Parent(0, b);};
That constructor creates a parent that is local to the constructor and goes out of scope when the constructor ends. It isn't the new childs Parent (which has been default constructed) its a different, temporary parent.
The Child object does indeed have the parent data, you ju... |
64,536,716 | 64,537,078 | Thread is not seeing refreshed value with lock | How do you force a thread to see the updated value of a shared variable? I thought mutexes were supposed to help, but in the code below, I don't see the correct behavior:
#include <thread>
#include <vector>
#include <chrono>
#include <iostream>
#include <mutex>
using namespace std;
mutex coutm;
class Timer {
publ... | thread timerThread {&Timer::start, std::ref(t)};
thread t1{&dummyPrint, std::ref(t)};
Just because you constructed the timerThread first, and t1 after it, you have no guarantees whatsoever that Timer::start will run first, in its execution thread, and dummyPrint will run second, in its own execution thread. And not on... |
64,537,302 | 64,540,812 | How to know when the user has finished resizing the window? | I am programming myself a PDF Reader for the fun and giggles however I am having trouble when the window is being resized. The problem is the following: When the window is being resized while a PDF is loaded, the PDF is being rendered again to match the new window sizes, however the resizeEvent is being called several ... | Disclaimer
The below solution is an answer to the question How to know when the user has finished resizing the window?, which is clear enough to be answered.
However, I believe you have a XY problem. The slow rendering you are experiencing might be due to using the wrong technology, but there is no way to tell without ... |
64,537,524 | 64,537,590 | Quasi "If" in switch/case | I faced with new for me C/C++ switch/if/else/case syntax.
I can't find it's mention in C standart.
Value inside "if" doesn't matter, "if(1)" or "if(0)" works same.
Seems this "if" doesn't act like condition, but as scope.
Is it compiler extension or compiler sugar ?
#include <stdio.h>
int main()
{
int a = 0, b = ... | A switch jumps to the selected case label. The if conditions are never evaluated because program control never flows to them. This is specified by the C standard and C++ standards.
|
64,537,609 | 64,537,658 | Can the dimension of std::array be read from command line arguments? | I have a C++ code where I decided to use std::array instead of std::vector and I want the size of the array to be read from command line.
In practice, this can be summarized with the following snippet
#include <iostream>
#include <array>
#include <sstream>
int main(int argc, char* argv[]){
std::size_t my_size;
{
... | Types and arrays sizes in particular must be known at compile time, hence the answer is: No.
You can implement some mapping from a runtime value to a compile-time constant. Something along the line of
size_t size;
std::cin >> size;
if (size == 10) {
std::array<int,10> x;
// use x
} else if (size == 20) [
... |
64,537,645 | 64,537,759 | Use c++ classes from console application class in other project visual studio | I am trying to make a gtest project in Visual Studio for my console application in the same solution. When i create this project from the "new project" wizard i can choose the project i want to test. So i select my console application. After visual studio has created the gtest project i can see under references that my... | You should design you application for testing.
Split the application into two projects. The core logic should be implemented in a (static) library. The actual command line application is just a small shell around the logic that has been implemented in the library.
Now you can create the test that links with the library... |
64,537,691 | 64,538,748 | Floating point arrays storing garbage value despite input correctly given | I'm trying to solve a problem for which I'll have to store float's in 3 different array's, surprisingly the values being stored are all zeros, could you point out what's going wrong here.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
vector<floa... | Here you go,
vector<float>prb(n+1,0),prft(n+1,0),loss(n+1,0);
Can be replaced with,
vector<float>prb(n),prft(n),loss(n);
In your original program to fix it :)
Also, while accessing the values (precisely cout), access the i-1 th element instead of i th. Since, the default indexing done is 0-based, and you are accessin... |
64,537,702 | 64,538,692 | C++ : Unable to print the text formatted as expected | I'm trying to print this LIST but it's driving me insane.
So this is the output that I wanted to get :
Veranstaltungen:
1: Freitag 08:00 - 09:30 SU Informatik III Kevin Kaufmann H3
2: Freitag 10:00 - 11:30 Ueb Informatik III Kevin Kaufmann D 114
3: Freitag 12:15 - 13:45 Ueb Informatik III ... | To fix your problems you need to left justify the text for some fields:
printf("%-30s %-20s %-10s\n",Events[i]->Name.c_str(),Events[i]->Teacher->Name.c_str(),Events[i]->Room->Name.c_str();
Note the minus in the number before s. Additionally I think you will have to make some of the fields wider than this constants
|
64,537,800 | 64,537,864 | C++: How to call a function (lets say funA()) from a header file inside my own function whose name is also funA()? | I want to call a function reverse(BidirectionalIterator first, BidirectionalIterator last) from <algorithm> header file inside my function, whose name is also reverse(int).
code:
#include<iostream>
#include<algorithm>
using namespace std;
class Solution{
public:
int reverse(int x){
string num = to_string(... | Ahh, now you're experiencing the reason people on StackOverflow are always yelling about not using using namespace std;. The issue is that you're bringing the whole namespace into the global namespace, which'll lead to clashes like this.
If you delete that line, however, now all of your imported functions stay in the s... |
64,538,319 | 64,539,400 | std::random_device is not a member of std | The random_device class is not recognized as part of the std:: namespace until I include <bits/stdc++.h>.
I want to ask you if there is another solution for this, because I don't really want to include all standard libraries for this purpose.
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution... | It is a good sign, indeed, that you don't want to include all the Standard Library header files (via the appalling and non-standard #include <bits/stdc++.h> concoction)! However, you do need to (explicitly) include the headers relevant to the aspects/components of the Standard Library that you actually use.
In the case... |
64,538,696 | 64,539,693 | C++ list with fast find | Im working with a std::list.
Elements appear in "order of insertion" into the list, not according to the value of an element.
When std::find()-ing an element, the whole list must be searched.
In order to speed up "finding" from O(n) to O(log(n)) I could myself implement a hash-map to store the std::list elements positi... | Since iterators for a std::list remain valid across inserts and deletes (except for the element you deleted, of course), you could maintain a secondaray data structure of type std::map <my_key, my_list_iterator> (or a std::unordered_map if that is more suitable).
Then, whenever you add or delete a list entry, do the sa... |
64,539,045 | 64,539,214 | Using Comparison Operators in preprocessor directives C++ | I want to define some functions based on a constant value:
#define mode 5
#if mode & 2 != 0
// function 1
#endif
#if mode & 4 != 0
// function 2
#endif
This may sound and look weird but I want to use one constant to define and activate some program modules.
defining mode = 2 includes function 1, mode = 4 include... | & has lower precendence then !=. So:
MODE & 2 != 0
is the same as
MODE & (2 != 0)
The 2 != 0 is logically true, so the result of != operator is a 1. Thus this is the same as
MODE & 1
It's just checking the first bit. While you want:
(MODE & 2) != 0
To check if the second bit is set. But really just remove the != pa... |
64,539,485 | 64,539,575 | set_intersection of vector<pair> elements | I was trying to see how the set_intersection function in C++ works, for a vector<pair>s and wrote this piece of code:
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, int> &a, pair<int, int> &b )
{
return a.first < b.first;
}
int main()
{
vector<pair<in... | Your output is perfectly fine. The issue is your comparator comp only considers the .first member of each pair when deciding the ordering.
So as far as set_intersection is concerned, neither {2,1}, nor {2,3} is less than the other, and so they are considered to be equivalent.
set_intersection will add the element from ... |
64,539,646 | 64,545,420 | Is it legal to convert a pointer/reference to a fixed array size to a smaller size | Is it legal as per the C++ standard to convert a pointer or reference to a fixed array (e.g. T(*)[N] or T(&)[N]) to a pointer or reference to a smaller fixed array of the same type and CV qualification (e.g. T(*)[M] or T(&)[M])?
Basically, would this always be well-formed for all instantiations of T (regardless of layo... | There’s not much to say here except no, in any language version: the types are simply unrelated. C++20 does allow conversion from T (*)[N] to T (*)[] (and similarly for references), but that doesn’t mean you can treat two different Ns equivalently. The closest you’re going to get to a “reference” for this rule is [co... |
64,539,770 | 64,539,909 | C++ Linked List: Node Creation Function | So, I'm learning C++ and data structures. The first one I wanted to do was singly-linked lists. I created/copied the following code:
class Node {
public:
int data;
Node* next;
};
Node* head = NULL;
void createnode(int* value) {
Node* new_node = new Node(); //allocate memory size of node
new_node->data... | Suppose you have a sequence:
a -> b -> c -> NULL; // where head points to a
what those lines are doing is (suppose you want to add 'd' to the previous list):
d -> a; // where a still points to wherever it used to point
and after that you update to where HEAD should point, which is no longer the node that had a, bu... |
64,540,176 | 64,540,498 | C++ : create a tuple with vector of strings | I have the following API to be implemented:
tuple<vector<string>, ItemStatus> SomeFcn() const
{
vector<string> result_item;
return tuple(result_item, ItemStatus::ACTUAL );
}
But it does not compile and compile output is not clear at all
/usr/include/c++/9/bits/stl_pair.h:436:9: note: candidate: ‘template<clas... | Write like this instead, assuming ItemStatus is an enum
std::tuple<std::vector<std::string>, ItemStatus> SomeFcn() const
{
std::vector<std::string> result_item;
return std::make_tuple(result_item, ItemStatus::ACTUAL );
}
(* i don't like leaving namespace out *)
|
64,540,179 | 64,540,270 | I can't print a vector inside a switch case | This is my first question here. I am just beginning to learn C++ and I am stuck at this exercise:
Your program should display a menu options to the user as follows:
P--Print the vector
A--Add a number
M--Display mean of the number
S--Display the smallest number
L--Display the largest number
Q--Quit
Enter your choice:
... | You created the variable vector inside your loop, so at the end of the loop the variable get destroyed and a new empty one is created on the next iteration. So, if you want your variable to retain values between loop iterations, you should declare it outside of the loop scope, the same way you did with the variable con... |
64,540,182 | 64,544,611 | Including an external library to my own library project c++ visual studio | Currently i have 3 visual studio projects:
ConsoleApplication
Logic
Test
These projects are all in the same solution. In the Logic project i use an external library named curl. My logic project is a static library made with the "new project" wizard in visual studio. This project includes a pch.h file. I added followi... | So after hours of research i found this post and i think this also applies to my case: Linking static libraries to other static libraries
TL;DR static libraries do not link with other static libraries
So i think the best solution in my case is to convert the static logic library to a dynamic lib (DLL)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.