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,619,427 | 62,619,481 | What does “\p” in comments means? | During reading LLVM source code, I find something different in comments, e.g.
/// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
What does \p means here?
| LLVM uses Doxygen for generating documentation, the /// marker is one of the many ways of creating a special comment block that Doxygen will parse to form documentation.
Within a special comment block, \p is simply one of the mark-up commands, this particular one renders the following word in typewriter font (fixed rat... |
62,619,491 | 62,904,923 | Nice syntax to get sized reference to vector's/array's data? | I'm wondering if there's any std:: function to get a sized pointer/reference to a vector/array's underlying data? Something better than:
const size_t(&asArray1)[N] = *(size_t(*)[N]) vec.data();
const size_t(&asArray2)[arr.size()] = *(size_t(*)[arr.size()]) arr.data();
Clarification - something I could pass to the bel... | SOLUTION: Use helper functions defined once, that do the appropriate casting and leave the call-site cleaner... I'm surprised that helpers like these aren't available at least for std::array...
For vectors, I will admit that it's a rare use case where you have a compile-time known size for the vector. but I do have a ... |
62,619,699 | 62,834,259 | How to use a pollevent through out multiple class "Union variable" (sfml) | From my understanding how sf::Event works there could only be one a loop since they all share the same memory space so my question I would I able to use sf::Event throughout my other class with:
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::Circl... | sf::Event is implemented as a union of different events' data which means that only one of the data structures is active at the time and it depends on the value of the type field, but it's something that works per-instance not per-type.
Hence you can safely pass events around and, if I understood you correctly, your co... |
62,619,917 | 62,619,973 | Output a Vector Element of Enum Class Type in C++ | I have created card and deck classes for use in a C++ poker game, however, I'm trying to check that my assignment of vector elements are correct and having issues displaying them on the console. I have an enumerated class for the suits and integer values for the ranks. I see that my deck vector is generating with 52 ca... | To display vector element, you should call display() of the vector element to display.
std::cout << m_deck[card.display()];
should be
m_deck.back().display();
to have it display the last pushed card.
Also int main(){ Deck deck();} is a main function with only function declaration and Deck::Deck() won't be called.
To ... |
62,620,002 | 62,620,156 | Program to check any number exist in 2D array | I know how to check if number exist in the array, but not in a 2D array.
Please help me in 2D.
#include<iostream>
using namespace std;
int main()
{
int a[3] = { 4,5,6 };
int b, c;
int x = 1, fact = 1;
cout << "enter no ";
cin >> b;
for (int i = 0; i < 3; i++)
{
if (b == a[i]) {
c... |
I know how to check if number exist in the array, but not in 2D array!
It is like you did for the one-dimensional array, instead of one, you need to now iterate through the rows and column. In another word, you need one more iteration.
#include<iostream>
int main()
{
int a[2][3]{ { 1,2,3 }, { 4,5,6 } };
int us... |
62,620,004 | 62,620,131 | Syntax for C++ operator overloading in a class | Background
I am self-learning C++ from this course. I am trying to overload an operator in a class using a friend function (Assignment 4.2).
EDIT
The linked question does not answer my question. The accepted solution to that question gives a way for templates to be implemented in header + cpp file (not all in the same ... | You need to add <> (or <T>) to make the friend declaration referring to the declared operator template. Without that the friend declaration would declare a non-template operator+ which is not defined, that's why you got the linker error.
BTW: You can also specify the template argument explicitly like
// refers to the i... |
62,620,039 | 62,620,263 | Collect all specific comments inside code in a table | Suppose I have a logger function, and I called it all over my code. My logs usually show the probability of the existence of a problem or a bug. More actions and investigations needed to confirm the problem or bug. For example, maintainer or tester should grab the input, open it in an editor, and if a specific string i... | Doxygen contains a.o. the commands \todo, \bug
From the documentation:
https://www.doxygen.nl/manual/commands.html#cmdtodo
\todo { paragraph describing what is to be done }
Starts a paragraph where a TODO item is described. The description will also add an item to a separate TODO list. The two instances of the descr... |
62,620,147 | 62,620,672 | c++ coroutines temporaries in co_await expressions | I'm wondering whether co_awaiting a coroutine with a temporary captured by reference is valid or not. So is the following code valid, I guess should the compiler put the temporary in the coroutine frame as for local variables:
task g(const S&);
task f() {
co_await g(S{});
}
On clang and msvc (https://godbolt.org/... | MSVC and Clang are right, temporaries are destroyed at the end of the full-expression.
For GCC, this is bug 95599. Apparently this bug is in the process of being fixed.
|
62,620,149 | 62,620,167 | Choose file dialog errors | I took this code off the internet. however, i keep getting the same errors over and over again whenever i find open file dialog codes. all of them are the same error and it's really annoying.
int choosefile() {
char filename[MAX_PATH];
OPENFILENAME ofn;
ZeroMemory(&filename, sizeof(filename));
ZeroMemory(&ofn, sizeof(... | It seems you decided to use char array to receive the path and GetOpenFileNameA() function, so OPENFILENAMEA structure should be used.
OPENFILENAME ofn;
ZeroMemory(&filename, sizeof(filename));
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = L"Text Files\0*.txt\0A... |
62,621,106 | 62,621,162 | How to access class elements from static vector? | I have a static vector of class Town inside the same class, and I am trying to access it's elements.
Code:
// town.h
class Town
{
public:
static int nrOfTowns;
static std::vector<Town> *towns;
std::string name;
};
int Town::nrOfTowns = 0;
std::vector<Town> *Town::towns = NULL;
// main.cpp
... | In your code towns is a pointer to a vector but probably it should be a vector:
// town.h
class Town
{
public:
static int nrOfTowns;
static std::vector<Town> towns;
std::string name;
};
int Town::nrOfTowns = 0;
std::vector<Town> Town::towns;
// main.cpp
/* code */
Town::towns.resize(Town::... |
62,621,230 | 62,621,368 | Qt debug show line numbers | I am a newbie programmer. Is there any way that I can print the File name and line number of my qDebug() output in Qt C++ code?
Currently, I have to manually write the filename every time I output a debug message.
Please help
| Please try the following
qDebug() << __FILE__ << __LINE__ << "Your message";
|
62,621,262 | 62,622,005 | LeetCode 1011. Binary Search, C++ and Python same idea but different outputs | Can anybody take a look at my CPP code?
It's from this problem: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
I feel very frustrated cuz though my python code works, my cpp code doesn't work as always. :pensive: Same idea, different results. It drives me crazy.
The correct output should be 15.
... | remove the else
else total += w;
should be
total += w;
|
62,621,389 | 62,621,451 | access violation with dynamic 2-dimension array in C++ | thanks you for being here to help
i want to have dynamic 2d dimension as char
int n;
char** stars;
int main() {
cin >> n;
for (int i = 0;i < n;i++) {
stars = new char* [n];
stars[i] = new char[n];
for (int j = 0;j < n;j++) {
stars[i][j] = '*';
}
}
for (int i... | stars = new char* [n];
is wrongly positioned in the loop, so you reallocate it per each string, and in the freshly allocated matrix only one string is allocated.
|
62,621,486 | 62,621,617 | Undefined reference - Why are some of the Methods in the header file not found when linking? | The Project that should be linked is made from 2 .cpp files. The includes and all of the references in the headers themselfes seem to be correct (noone from our team could find the error). Therefore I think that our Makefile has to be wrong or missing something.
Everytime I build the project I get a linking error on so... | Undefined reference in the linking process doesn't mean, that it can't find the declaration in the header file, it means that it cant find the definition/implementation in any of the provided object files.
Utilities.cpp doesn't seem to include an implementation of simpleMatMultiplication, or at least not with this exac... |
62,621,630 | 62,621,676 | cout << function(); undefined reference. issues with a function | #include <iostream>
using namespace std;
//defining function
double distance(double,double);
int main() {
//where im having issues i think
cout << distance();
return 0;
}
//attempting to start the function with rate*time=distance and returning the value
double distance(double rate, double time)
{
... | You should pass arguments to the function because you've defined as: double distance(double, double);
So, the solution would be:
#include <iostream>
using namespace std;
double distance(double, double);
int main()
{
cout << distance(10, 10);
return 0;
}
double distance(double rate, double time)
{
retur... |
62,621,857 | 62,623,817 | Changing the world origin in C++ SFML | I've recently gotten into SFML and as an exercise to get more comfortable (and have fun), I started translating some Coding Challenges done by Daniel Shiffman on his Youtube channel, The Coding Train. Upon attempting to translate a star field effect in SFML, I started searching for the right function in SFML that would... | You need to use sf::View
https://www.sfml-dev.org/tutorials/2.5/graphics-view.php
Here is a small implementation example:
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(300, 300), "");
sf::Vector2u size = window.getSize();
sf::View view(sf::Vector2f(0, 0), sf::Vector2f(size... |
62,622,047 | 62,622,149 | Can i override non virtual function in c++ | i wanna know can i override non virtual function in c++ because i found this problem when playing with c++
override keyword i have the code as follows
class A
{
public:
void say()
{
cout << "From A\n";
}
};
class B : public A {
public:
void say()
override
{
cout << "From B\n"... | You do not override say in B
from C++ override specifier :
In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.
Look at that example :
#in... |
62,622,456 | 62,622,596 | cout<<endl; not working for printing a 2d array | I am trying to print a 2d array like this.
1,2
3,4
5,6
7,8
until 20
and this is the code
#include <iostream>
using namespace std;
int main()
{
int A[10][2]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
for(int i=0;i<10;i++)
for(int j=0;j<2;j++)
{
cout<<A[i][j]<<" ";
... | Hey there you forgot to add {} after first for loop.
Here's solution
#include <iostream>
using namespace std;
int main()
{
int A[10][2]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
for(int i=0;i<10;i++)
{
for(int j=0;j<2;j++)
{
cout<<A[i][j]<<" ";
}
cout... |
62,622,459 | 62,622,678 | How to call the lambda stored in pointer to the `std::function`? | I have a pointer to std::function that stores lambda inside.
How can I call that lambda?
example:
std::function <void()>* fx = new std::function <void()>([] {std::cout << "Hello world;\n"; });
//here i need to call my fx, just fx(); does not works in this case
fx may be stored inside std::pair
| You can call it either of the following ways:
Dereferencing the pointer and call
(*fx)();
or explicitly calling the
std::function<R(Args...)>::operator()
fx->operator()(); // explicitly calling the `operator()`
or using
std::invoke
std::invoke(*fx); // needed C++17 or later
However, you should be re-think abou... |
62,622,535 | 62,622,557 | Defining a parameter of a struct variable in a class constructor | I am using a struct variable inside a class and I would like to assign the value of a parameter of that variable in the class constructor.
But I can not find a way to compile. could you show me how to do it? This is an example of my code
struct mystruct
{
int myvar;
}
class myclass
{
mystruct s_;
public:
myc... | Your mystruct would need a suitable constructor which takes an intger as an argument, for that.
struct mystruct
{
int myvar;
mystruct(int val) // provide this constructor and good to go!
: myvar{ val }
{}
};
Or Aggregate Initialization
Since mystruct is an aggregate type you could do the aggregate init... |
62,622,936 | 62,623,072 | More efficient way to call vector.size() | Given a vector of ints I saw my professor writing:
for (int i=0;i<vect.size();++i)
{
}
I argue that his code isn't efficient and could be replaced by the following, am I right?
int vect_size=vect.size();
for (int i=0;i<vect_size;++i)
{
}
| You can do this:
for (std::size_t i = 0, vect_size = vect.size(); i < vect_size; ++i)
{
}
This way, you can limit the scope of vect_size.
|
62,623,511 | 62,623,622 | variadic templates vs using tuples for adding different data pairs in an argument | following main code works fine
string hello = "Hello ";
string world = "templates!";
cout << "var template add: ";
cout << setprecision(2) <<
var_template_add(5, 4, 5.5, 4.0);
for following template generator code and variadic func
template <typename T>
auto add(T a, T b) {
return a + b... | The only way for the current call to work is for var_template_add to return a single type, so it would need to be a string.
Instead, you could write the cout inside the function, so then you only need:
template <typename T, typename... Rest>
auto var_template_add(T first, T second, Rest... others) {
cout << setpre... |
62,623,603 | 62,624,349 | Why don't IDEs highlight string data type in C/C++? | I am using Sublime Text 3 and Atom to code C and C++. But they don't highlight string data type as shown below.
This issue is frustrating me when I use Atom and Sublime. This doesn't happen in Visual Studio Code.
Are there any ways to fix this issue except using Visual Studio Code instead?
| For Atom:
Press Ctrl + ,(comma) to open Settings.
Go to Settings > Core.
Check Use Tree-sitter Parsers for supported languages.
Additional Steps:
Install Atom language support for C/C++ (Official) or C++14 language support (3rd Party).
For Sublime Text 3:
Install C++ Starting Kit or C Improved or C++11.
Note: The... |
62,623,730 | 62,624,194 | List initialization - What changed in C++14? | These two lines from cppreference
What is the difference between these two statements ? I don't see any difference
until c++14
If the braced-init-list is empty and T is a class type with a default
constructor, value-initialization is performed. Otherwise, if T is an
aggregate type, aggregate initialization is performe... | The difference is which one happens when both conditions apply: if T is an aggregate class (as opposed to an array), which certainly has a default constructor, and the braced-init-list is empty. Of course, to understand why that matters, we then have to distinguish value initialization from aggregate initialization fr... |
62,623,777 | 62,624,530 | How to make bool variable only true if its being set to true? | I have
namespace global {
bool global::Aimbot; // this must be set to false until something else doesnt set this to true
}
in my function im doing
inline void set_view_angles()
{
global::Aimbot = true;
// so everytime this func is called it set global::Aimbot to true
}
I debugged global::Aimbot bool, and ... | Since the question is open to multiple interpretation, first let me summarize the problem as I understood from the description and the comments: OP wants to set variable global::Aimbot to true when some key is pressed, and set it to false when said key is released.
Answering: When function set_view_angles() is called, ... |
62,623,903 | 62,624,172 | c++ - offsetof function, why is it possible to pass just the member name | when I define a struct like this:
struct abc{
int member1;
int arr_member1;
std::vector<int> mVector;
}
and want to make an arr_member variable, I'd have to do this:
abc x;
x.member1=3;
x.arr_member1= ...
//some more code
but I can't do something like this:
arr_member1 a = //some code
where a is supposed to ... | Because offsetof is a macro, inside the macro definition, the field name will be used together with the type you passed in. It looks like this:
#define offsetof(st, m) \
((size_t)&(((st *)0)->m))
source: https://en.wikipedia.org/wiki/Offsetof
|
62,624,017 | 62,624,125 | Qt with WinAPI MouseProc | I need to track the cursor position on the screen, for this I use a function from WinAPI
// code from Qt(!) project
#include <windows.h>
#pragma comment(lib, "user32.lib")
MyClass *myclass;
static HHOOK hHook;
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
switch( wParam )
{
cas... | You an use GetCursorPos() funtion for this:
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
switch(wParam)
{
case WM_MOUSEMOVE:
POINT p;
GetCursorPos(&p);
sprintf(msgbuf, "My coordinates is (%d,%d)\n", p.x,p.y);
OutputDebugString(msgbuf);
break;
... |
62,624,475 | 62,624,582 | Size of string vs size of char array in c++ | I have to write a piece of code and deploy it in a system with limited memory space and was thinking about char arrays vs string . I wrote the following piece of code to get a better idea.
string str="abcde";
char carray[6]={'a','b','c','d','e','\0'};
cout <<"size of char array:"<< sizeof(carray) << endl ;
... | std::string is a class object in C++. The size of it is implementation-defined, but will generally require space for at least both a pointer to a heap-allocated string, and a size. The sizeof(std::string) you are seeing may be specific to your implementation -- but it could be partially due to a small-buffer optimizati... |
62,624,695 | 62,625,308 | The difference between a destructor and 'delete' | What is the difference between the destruction of an object and deletion in C++? In OOP, when an object goes out of the scope, the destructor is called, and when dynamically allocating memory we have to use the delete keyword inside the destructor. So what does it mean for an object to be destroyed or deleted?
| A destructor is a special method for a class. It is called whenever an object goes out of scope, or someone calls it explicitly.
An example where an objects destructor is called, but no delete:
struct MyObject
{
MyObject() { std::cout << "default constructor"; }
~MyObject() { std::cout << "destructor"; }
vo... |
62,624,816 | 62,624,838 | "Ill-defined for-loop - loop executes infinitely" (MSVC C6295) | I'm not quite sure why visual studio is giving me the error message "Ill-defined for-loop: 'unsigned int' values are always of range '0' to '4294967295'. Loop executes infinitely" for the following code:
for (unsigned int i = list->GetCount() - 1; i >= 0; i--)
{
// do stuff to each item (specifically in reverse ord... | When you subtract 0 from an unsigned type, you don't get a negative number, but a very large positive number.
That means this condition:
i >= 0
will always be true, resulting in an infinite loop.
You can fix this by doing:
for (int i = static_cast<int>(list->GetCount()) - 1; i >= 0; i--)
Note that the cast needs to b... |
62,624,977 | 62,624,978 | Generic find_if to check an element in the 2D array | Using std::find_if we could find if an element exists in a normal one-dimensional arrays.
Inspired from this question, I was wondering, whether we can provide an algorithm function to check the exists in a 2d array(i.e. std::vector of std::vectors or std::array of std::array) of any types and any number of elements.
Is... | With the help of the same std::find_if, we could achieve this.
Following is a template function which takes the iterators (like in most of the standard algorithm functions)
of the 2d array (either std::vector<std::vector<Type>>, or
std::array<std::array<Type, RowSize>, ColSize>) and returns the iterator pointing to the... |
62,625,150 | 62,625,176 | How to called special functions in the cmath library in C++? | I am trying to define a function that requires me to make use of something called an "Associated Laguerre Polynomial". It's listed here under the library. In visual studio code, intellisense predicts "assoc_laguerre()" as a function so it clearly exists!
Yet, when building the code, it highlights the assoc_laguerre() ... | You're not compiling with the C++ 2017 version of the language standard enabled. Enable it, and this should be available. Your code compiles with GCC 10.1 and -std=c++17; but not if we use -std=c++14 instead.
GodBolt
|
62,625,246 | 62,625,268 | C++11: template function call of a template method doesn't compile? | The following program, if compiled as shown, outputs size: 1 align: 1.
However, trying to make the same method-template call from a templatized function doesn't work.
If I change #if 0 to #if 1 g++ 9.2.1 gives me error expected primary-expression before 'char'. clang++ gives a more helpful-sounding error: use 'templa... | You need to specify that log is a function template, like this:
template<class T> void Test( T& t ) {
t.template log<char>();
}
Otherwise the compiler doesn't know if log is a member of T, and < is actually operator<.
Here's a demo.
|
62,625,450 | 62,626,839 | What is the recommended way to convert from long long int to uint64_t? | Consider a function that returns a long long int value. Even though it returns a long long int, the logic guarantees that it is always positive. I want to use the return value assigned to an uint64_t. Given the logic is correct what is the recommended way to do this cast? Should I just assign to it or do a static cast... | This is an implicit conversion, integral convertion, no cast is required:
If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n
where n is the number of bits used to represent the destination type.
That is, depending on whether the destination type ... |
62,625,642 | 62,625,772 | Vector Values (String and Int) Summation C++ | I have moved to C++ from Python, and just wanted to know the way to sum the values that a vector (list) object holds. For example, in python, I could use the code below:
totalSum = 0
myList = [1,2,3,4,5]
for i in myList:
totalSum += i
print(totalSum)
// Output:
15
However, I want to learn the way to do this in C... | The program has an error. In the for loop, you're trying to compare an integer to an unsigned long long int which is returned by v.size() (use -Wall mode in the compiler arguments to get it).
Using for each syntax, an approach is defined as follows:
#include <iostream>
#include <vector>
int main(void) {
std::vecto... |
62,626,082 | 62,626,881 | Rewrite C++ class in C | So, I am having some trouble rewriting a C++ class I made in C.
The C++ class has some private attributes:
int grid_width;
int grid_height;
const int group_width = 2;
const int group_height = 4;
std::vector<int> buffer;
It is initialized like so:
grid::grid(int width, int height) {
this->grid_width = width... | Your grid_new is allocating an array of grid structs and not a single grid with the correct number of elements.
You need to set buffer
Also, the number of elements in the grid is based on width/height and not sizeof(g->buffer) which is the size of the pointer and not the area to which it points
Here's the refactored co... |
62,626,149 | 62,626,315 | Explicit comparison in c++ | In the given code i don't understand line 5 & 6 clearly, i know it is used to compare the elements and returns true and false.
class Person{
public:
float age;
string name;
bool operator < (const Person& rhs) const { return age<rhs.age}
bool operator > (const Person& rhs) const { return age>... | Those are comparison operators, and correctly assumed return true or false.
So the Person class defines comparison directly on the object. These operators can be used to simply compare objects:
int main()
{
Person p1;
Person p2;
//set some ages
p1.age = 30;
p2.age = 20;
bool p1_older_than_p2 =... |
62,626,198 | 62,626,243 | C++ EXC_BAD_INSTRUCTION? | What's wrong with the class written down, It returns the following error:
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
when the operator= is called.
class test
{
int x;
public:
test()
{
this->x=10;
}
test(const test& other)
{
this->x=other.x;
}
test& operator... | You are not returning from your operator=. That invokes undefined behavior.
test& operator=(const test& other)
{
this->x=other.x;
}
You need to do:
test& operator=(const test& other)
{
this->x=other.x;
return *this;
}
|
62,626,347 | 62,626,753 | checking if an array is contained in another, in reverse order, at least twice |
I wrote a C++ function hasMirrorTwice that takes as parameters two arrays of integers, arr1 and arr2, and their lengths and checks if arr1 contains all elements of arr2 in reverse order at least twice. Below is the function. I was wondering if there was a way to simplify it?
bool hasMirrorTwice(int a1[], int a2[], in... | You could use the standard library std::search algorithm and reverse iterators. For example:
bool hasMirrorTwice(const int *a1, const int *a2, int size1, int size2)
{
using ritr = std::reverse_iterator<const int *>;
// first match
auto itr = std::search(a1, a1 + size1, ritr(a2 + size2), ritr(a2));
if (... |
62,626,456 | 62,626,473 | Why does my BaseClass:Method code compile (with single colon)? | I ran into the following code that spits a segmentation fault. Then I realized I typed Base:hello() instead of Base::hello, but it surprises me that the single colon code would compile. How is Base:hello() a valid expression?
class Base {
public:
virtual void hello() {
cout << "Hello" << endl;
}
};
c... | Base: is parsed as a label, which can be used as the target of a goto statement. So this is equivalent to just calling hello() and that, of course, will give you infinite recursion and a stack overflow.
|
62,626,999 | 62,627,923 | Dual variables Gurobi with C++ | I am solving a linear program using Gurobi811 with C++ interface and I want to recover the dual variables. It is written in the documentation that the corresponding attribute is Pi, but the syntax is not clear. This is an example of a simple linear program with two variables and three constraints, and the problem is to... | the dual variables are associated with the linear constraints, so you should useGRBgetdblattrelement to get the dual value. the index can be got from the function GRBgetconstrbyname. for example
int pIndex0 = 0, pIndex1 = 0, pIndex2 = 0;
GRBgetconstrbyname(model, "c0", &pIndex0);
GRBgetconstrbyname(model, "... |
62,627,219 | 62,627,619 | How can I determine what header calls another header in c++? | I am reading from here : Can std::string be used without #include <string>?, <iostream> is calling <string>. But I do not see any includes of <string> in Standard library header <iostream> from c++ standard: https://en.cppreference.com/w/cpp/header/iostream. In <iostream> is only included <ios>, <streambuf>, <istream> ... | You should always check the documentation for any symbol you use and include any headers it is specified to require.
The C++ standard only specifies which symbols must be made available when a standard header is included. It does not place any limits on what other symbols are made available. In your example, the stan... |
62,627,343 | 62,627,430 | Find index of element in vector of pairs | As stated in the title, I'm trying to find the index of an element in a vector of pairs. I have the following vector: std::vector<std::pair<std::string, double>> dict.
The content of my dict is:
Name1 11
Name2 9
Name3 10
Name4 12
Name5 13
All I have in order to find the index is the first attribute of the pair. For ex... | I would simply go with a normal for_each loop.
So:
int index = 0;
for(const auto& pair : dict) {
if(pair.first == <whatever>) {
break;
}
index++;
}
//if index == dict.size() then print element not found
Other way would be using std::find_if() ( Thanks @Tony Delroy :) )
auto index = std::distance(... |
62,627,464 | 62,627,646 | How to handle non default_constructible tyname variables | My question to you is how can someone handle a non default_constructible variable. I came upon this question on a test I had and got me thinking. Please find the below example to fully understand:
template<typename W>
class Foo {
array<W> arr;
public:
void fooFunc(W const& value){
// I wanted to do the below a... | std::array<W> will not compile, because it needs two template parameters.
std::array<W, 2> (for example) will create a variable containing two default-constructed values of type W. If W is not default-constructible, this will fail to compile.
The following psuedo-code will make a vector containing two elements of type ... |
62,627,666 | 62,627,779 | Should I declare method "const" if it is "shallow const" only, not "deep const"? | I have class Foo and its member bar_ is a pointer to some data. Method modify modifies the data, but not the pointer itself. Therefore I can declare the method as const:
class Foo {
public:
Foo() : bar_(new double) {};
void modify() const {*bar_ += 1;};
private:
double *bar_;
};
If I declare the method as ... | const after a method declaration is a statement of intent - const methods are meant to be idempotent; they do not modify the state of the object and can be called on const instances.
If the value pointed-to by bar_ is part of the object's state, then a const method should not modify it.
In addition, even the name modif... |
62,627,770 | 62,628,454 | Which data structure would be best for an expandable user database | I am attempting to create a data structure that will hold an unknown number of users and will be expanding as the program goes on. I'm using a struct that will have multiple instances of it places into the structure and now I'm wondering which structure should I use for an expanding user base that would need random che... | When I see a structure that walks like a database and swims like a database and quacks like a database, I call that structure a database.
In essence your trying to make a relational database.
struct Account {
string userName;
string password;
string legalName;
int accountNum;
string accountType;
};
And the f... |
62,627,838 | 62,628,399 | What am I supposed to include to make a boost.python extension? | Edit: accidentally copy pasted a line twice.
I'm making a C++ Python extension using a combination of boost and the normal C API, but I can't compile it. I've read the following documentations:
documentation from boost.org
documentation from python wiki
Python bindings for C++ medium
here's the code from the cpp file:
... | Like (almost?) everything (that isn't a macro) in Boost, class_ is in a namespace, in this case boost::python. Either:
Add using namespace boost::python; at the top of your file (just after the includes).
Refer to boost::python::class_ instead.
The same applies to the other symbols to.
This is shown in the quickstart... |
62,627,868 | 62,627,887 | Why size of c++ dynamic array is not changed? | Hi guys I tested c++ dynamic array and I changed 2 inputs every time.
but array size is not changed. Why?
#include <iostream>
using namespace std;
int main()
{
int r = 0;
int c = 0;
int cnt = 1;
cin >> r;
cin >> c;
int** arr1 = new int* [r];
for (int i = 0; i < r; i++)
{
arr1[i] = new int[c];
}
cout << size... | You are testing the size of a pointer which is always 4 on 32 bit.
That's because sizeof is a compile time thing; it cannot determine an array size.
Generally arrays do not carry size information, that is why functions like strlen need a null terminator.
Suggestion: use std::vector.
|
62,627,899 | 62,628,187 | how to return or a list of items of care is based on several classes | In my function 'func' i want to create an object Menu who returns a breakfast with lemon and coffee. 'func' return a list of menu
When I try to display the menu for a breakfast that contains only lemon or only coffee it is displayed correctly. For example:
c.push_back(make_unique<Breakfast>("eggs", 10));
but when i t... | You can't take a pointer to automatic memory, store it in a smart pointer and leave the function. After you leave the function the automatic memory is freed and the smart pointer contains a dangling pointer. The simplest way to avoid this problem and other problems with memory leaks is to use smart pointers for all var... |
62,628,317 | 62,629,681 | Parsing variant of struct with a single member using Boost Spirit X3 and Fusion | I am trying to parse a std::Variant with a fusion-adapted Struct type that contains a single member. After several hours of trying to figure out the problem, I was able to reproduce the issue with this code:
struct TestStruct {
float value;
};
BOOST_FUSION_ADAPT_STRUCT(TestStruct, value)
typedef std::variant<Test... | I hate to say, but this is a well-known limitation and it keeps cropping up. I've kind of given up on trying to get it fixed. It's an edge case that is usually easy to work-around or avoid.
See e.g.
boost::spirit::x3 attribute compatibility rules, intuition or code?
How to move results parsed results into a struct usi... |
62,628,374 | 62,628,460 | Having a problem with getting the right value with private variable | This is a program that takes an array and print the sum of the odd (named m_sumOdd) and even (named m_sumEven) numbers of that array using class. However when i run it and enter some values like (4, 6, 9, 3, 1) the m_sumEven returns 10 and m_sumOdd returns 2037769787. What's the problem with m_sumOdd ?
#include <iostre... | When you do not initialize your variable in C++, the default value of that variable is whatever garbage value happens to already be in that memory location. So if you initialize your privates variables as zeros (as in your non-parameterized constructor), your problem will be solved.
|
62,628,400 | 62,628,468 | Why result from std::getline() is not as expected | I'm extracting some data from a text file and put them in 2 vectors but the output of std::getline() is not as I expected. Here's the code:
std::vector<std::string> v1;
std::vector<std::string> v2;
const char* filename = "words.txt";
std::ifstream fin(filename);
if (!fin) {
throw "Bad file name!";
}
else {
... | In v2, the values end with a carriage return (\r). When this is printed to the terminal, it makes the cursor go back to the beginning of the line, so the ))) is printed over top of the (((. The same thing happens when the temp values are displayed, because it displays the entire line.
Please also see Getting std :: ifs... |
62,628,434 | 62,628,703 | Ncurses wrefresh not showing window borders | I am experimenting with some C++ using ncurses and am having trouble showing the window borders, but am having trouble with the following programs.
#include <cstdio>
#include <cstdlib>
#include <ncurses.h>
int main(int argc, char **argv)
{
if(argc != 5)
{
printf("not enough arguments\n");
exit... | For my tests, that initial refresh() is certainly what is missing. I checked some old code I wrote, and it indeed calls refresh() as part of the ncurses initialisation. Adding this to your code made it work for me. A lot of the curses documentation is still constrained to books, it never really made it onto the web.... |
62,628,884 | 64,791,936 | segmentation fault using static libraries with std::jthread (g++-10) | I'm developing a library that works with std::jthread (new in C++20) using g++ 10.0.1. The library works fine if I compile it using share libraries, but If I compile it with static libraries I got a segmentation fault at the end of the program (thread destructor). I have narrowed down my test case to a simple thread cr... | The problem was reported to libstdc++ (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95989) and a patch has been generated to solve the problem.
|
62,628,942 | 73,569,132 | consteval wrapper vs. source_location | I tried the following first variant using GCC10 in C++20 mode:
consteval std::experimental::source_location there()
{
return std::experimental::source_location::current(); // Line 3
}
void f(const std::experimental::source_location& a = there()) // Line 6
{
std::cout << a.line() << std::endl;
}
int main(int pAr... | I turned out second variant is correct. On current GCC 12 it works fine.
|
62,629,237 | 62,629,730 | My objects' members change when I call their methods | I have an object in C++ with several properties initially set to nullptr, the idea being that I can tell when I reach the edge of what I have thus far defined. For example, I can chain Nodes together into a linked list, and detect the end of the list by comparing to nullptr:
class Node{
public:
Node* next;
bool val... | The solution here is to dynamically allocate that object. You're using a temporary which falls out of scope on the very next line, and any references to that are invalidated, meaning your next pointer is now garbage.
The easy fix is:
void append(bool v) {
if (next == nullptr) {
next = new Node(v);
} else {
... |
62,629,262 | 62,629,338 | Need assistance with this if statement | first, let let me show you the code:
// calculate grand total
if(unitsPurchased >= 10,19)
{
discount = .20;
totalCost = totalCost - (totalCost * discount);
cout << fixed << setprecision(2);
cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total i... | The statement you're looking for is one of:
if (unitsPurchased > 10 && unitsPurchased < 19) { // exclude 10, 19
if (unitsPurchased >= 10 && unitsPurchased < 19) { // include 10, exclude 19
if (unitsPurchased >= 10 && unitsPurchased <= 19) { // include 10, 19
An expression like valA, valB is actually a use of the co... |
62,629,407 | 62,629,559 | File appending problem with users input with strings... C++ | I am using user input to store strings in a txt file! However I have a problem. While inputting the users string for file writing is fine, I want to add new lines, but when a user inputs a phrase for the file, it writes the input to the file, but not in one complete line, for each word it takes one line...
Code :
... | You should try putting getline(std::cin, Input) below std::cin >> Input to capture all spaces so that it won't be a one line in every word. Hope this works
|
62,629,512 | 62,629,699 | C++ cout aligning a double to a precision of 2 with right alignment | How do I align the code to 3 places to the right instead of the default left?
10.23
100.23
10.23 ----------Like this
100.23
double test = 10.2345;
double test2 =100.2345;
std::cout << std::setprecision(2) << std::fixed << test << '\n' << test2 << std::endl;
| Set the width of the output first using std::cout.width(num); and setting the output to the right using std::right, something like this:
#include <iostream>
#include <iomanip>
int main()
{
std::cout.width(6);
std::cout << std::right << 10.23 << std::endl;
std::cout << std::right << 10.453;
return 0;
}... |
62,629,779 | 62,707,035 | C++ Store class objects which contain polymorphic properties in a stack | I am attempting to make a chess game from scratch and made significant progress over the past couple of months. However, I recently got stuck on a problem that I just cannot figure out how to solve.
CODE (UPDATED)
Since the source code is too large to post here, I think it is best to leave a link to my GitHub account... | I managed to solve the problem by serializing/de-serializing the Chess object's private members to a file.
The way I did this was by making a separate folder which stores these files and added a move counting private member to Chess. Then I added the serializing functionality using the overloaded extraction and inserti... |
62,629,990 | 62,630,643 | How can I use Intel PIN to catch all loads to an array? | I'm profiling an application I have written using PIN. The source code of the application uses an array - I want PIN to catch every load instruction made to the array.
Currently, I have annotated the source code of the application I am trying to profile. Every time I read from the array, I first call a function startRe... | In your startRegionOfInterest method, you can use some kind of indicator sequence to pass the array address to your PIN tool. E.g., store a magic constant, then store the array address, something like:
volatile void *sink;
void startRegionOfInterest(void *array) {
sink = (void *)0x48829d2f384be;
sink = array;
... |
62,630,324 | 62,630,502 | Showing different Class from main.cpp | I am new to qt.
i have an application which have several forms.
i am trying to select the specific form from main.cpp, but it just flickered the form. But i am getting the debug values of the form and the form is invisible.
My main.cpp code
#include "dialog.h"
#include "design1.h"
#include <QApplication>
#include <QtCo... | The problem is that w in both cases have a limited scope inside the "if" so they are destroyed instantly. One solution is to use pointers managing dynamic memory, for example using QScopedPointer:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QScopedPointer<QWidget> w;
int theme = 2;
... |
62,630,486 | 62,633,162 | The wording about instantiation of a pack expansion in [temp.variadic] | I wonder Is it a mis-wording in the following quote, that is
temp.variadic#7
The instantiation of a pack expansion that is neither a sizeof... expression nor a fold-expression produces a list E1,E2,...En
, where N is the number of elements in the pack expansion parameters. Each Ei is generated by instantiating the pat... | I try to answer this question, To understand these sentences, These sentences are necessary to split to several portions.
A function parameter pack is a function parameter that accepts zero or more function arguments.
What is a function parameter pack?
In c++17 standard, it says:
dcl.fct#16
A declarator-id or abst... |
62,630,615 | 62,630,846 | How to store input for an unknown number of iterations? | I am writing a problem for school project on loops.
The program is a do-while loop where the user will feed the program sales figures, then expense figures for three separate districts. Then the user will be prompted to enter Y to enter the figures for another month, or anything else to terminate the loop.
After termin... | Seems like you would benefit from a dynamic data structure like a vector or list. If you're unfamiliar with std::vectors, they work like arrays but they grow and shrink as you add data to them. This will allow you to loop for as long as you like adding reports for an unknown amount of months.
Here you can see an exampl... |
62,630,665 | 62,631,493 | Compiling CUDA with clang on math functions | Compiling the following CUDA code helloWorld.cu with clang-11,
int main() {
return max(1.0f, 2.0f);
}
, using command clang++-11 -o helloWorld helloWorld.cu --cuda-gpu-arch=sm_75 -ldl -lrt -lcudart_static -pthread -L/usr/local/cuda/lib64, encountered the error:
helloWorld.cu:2:12: error: no matching function for ... | The code you have written is host code and it is not syntactically valid C++. That code should not compile, and the compiler behaviour is correct. The code should look like this in order to compile:
#include <algorithm>
int main() {
return std::max(1.0f, 2.0f);
}
i.e. you have to actually include the standard lib... |
62,630,717 | 62,829,820 | How to load and display a blender .obj source file scene using Qt 3D libraries | I'm trying to load a .obj source file from blender, and display it, LibertStatue.obj is the .obj file which is located in the same folder as the main.cpp file below. When I run this code, I get blank window which I think is supposed to show a statue of liberty, and a command prompt that says QObject::connect(opneglcont... | The problem is the setMeshName call. The documentation for the QMesh C++ class is misleading: setMeshName is not for setting a name to the QMesh object, but for selecting which geometry from the OBJ file you want to load. Its actual behavior is explained in the documentation of the corresponding QML type.
So you have t... |
62,630,827 | 62,638,134 | In C++, how do I use constant variable defined in one file elsewhere? | I'm c++ beginner.
// a.cpp
int g_x{ 1 }; // that linkage is extern-linkage by default
extern const int g_y{ 2 }; // change the linkage of variable g_y from intern-linkage to extern-linkage
//main.cpp
#include <iostream>
extern int g_x; // forward declaration
extern const int g_y; // forward declaratio... | I just tried the same thing (g++ 7.5.0 on Ubuntu 18.04) and got the correct values of g_x and g_y. I tried both -O3 and -O0 Is it possible that you just compiled different source files (or versions of the source files) than you thought, or ran the wrong compiled executable? Try recompiling and checking the timestamp be... |
62,630,949 | 62,631,134 | 9147 Segmentation Fault : 11 Construct Binary tree from inorder and preorder traversals | Given inorder and preorder traversal of a Binary Tree, construct the Binary Tree.
While constructing a tree from inorder and preorder traversal, i think i have written it properly but why is it giving a segmentatation fault. Please help.
below is my code for the same :
#include<bits/stdc++.h>
using namespace std;
cla... | It seems to me that at least one of your problems is that in the loop to find the root index in the in-order list of data, you don't actually check the last element (i.e. it should be i <= InE.)
Also, I can't say that your lPree calc is correct, because the names you have chosen are so unhelpful that I don't even want ... |
62,631,242 | 62,637,155 | Is there a formula to find the numbers of bits for either exponent or significand in a floating point number? | Recently, I have been interested with using bit shiftings on floating point numbers to do some fast calculations.
To make them work in more generic ways, I would like to make my functions work with different floating point types, probably through templates, that is not limited to float and double, but also "halfwidth" ... | Characteristics Provided Via Built-In Functions
C++ provides this information via the std::numeric_limits template:
#include <iostream>
#include <limits>
#include <cmath>
template<typename T> void ShowCharacteristics()
{
int radix = std::numeric_limits<T>::radix;
std::cout << "The floating-point radix is " <... |
62,631,698 | 62,632,628 | How to define a const class-member function that is inheriting without duplicated-code? | Im trying to define a class which (its minimal version) would look like this:
class Base{
int i;
public:
Base(int i_): i(i_){}
int& at(size_t index) {return i;}
const int& at(size_t index) const {return i;}
};
(Yes. It has an index because the class that i really want to create always need it, so lest ... | Thi is one of the few cases where const_cast is useful. You can use it as follow:
int& at(size_t index)
{
return const_cast<int&>(std::as_const(*this).at());
}
Pre c++17 you can replace std::as_const with static_cast<const my_class&>
|
62,631,702 | 62,631,989 | My code passes the test cases but when I submit it shows wrong answer | There are two Rectangular photo frames. Find if the given two frames overlap or not. A frame is denoted by providing the
x
and
y
coordinates of two points: the left top corner and the right bottom corner of the frames. Two frames sharing a side are considered overlaid.
Input Format
The first integer
T
denotes the numbe... | Two frames sharing a side are considered overlaid.
While your code consider sharing a side is NOT overlaid by using >= and <=.
Following is the example without equal signs.
bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
if (l1.x > r2.x || l2.x > r1.x)
return false;
if (l1.y < r2.y || l2... |
62,632,447 | 62,633,061 | Problems with directory deletion MFC | I am doing a mfc program in which i have created a directory to store dicom images using
CreateDirectory(Directory_name,NULL);
and succesfully created the folder,
After that i have used this folder of dicom images to perform volume rendering and it goes well too.
After that when i try to delete the directory includi... | Under Windows, you can't delete a file while it's open.
If you're using Windows functions directly, and specifically, opening the files with CreateFile, you can pass FILE_FLAG_DELETE_ON_CLOSE to (obviously enough) have each file deleted as soon as it's closed.
If (far more likely) you're using almost any other way to o... |
62,632,710 | 62,632,816 | Unordered_map or hashMap existing hash function modify? | I used unordered_map<long long int, long long int> the key may take values of upto 1e9, this lead to my answer being Time Limit Exceeded.
when I used map<long long int, long long int> it was succesful.
I came to know from other answers that unordered_map is bad when hash function is bad , is there a way to change the ... | Yes, you are free to do so.
The third template parameter of std::unordered_map is the hash function going to be used, and it should be a functor that satisfy the requirement listed here.
|
62,632,898 | 62,633,183 | MiniDumpWriteDump() hangs | MiniDumpWriteDump() of DbgHelp library hangs if heap allocation/deallocation/reallocation is in progress in another thread. Here is the call stack: DbgHelp pauses the other threads, then waits indefinitely for the mutexes obtained by those threads.
ntdll.dll!NtWaitForAlertByThreadId() Unknown
ntdll.dll!RtlpWa... | Broadly speaking, MiniDumpWriteDump performs two operations:
Suspend all threads in the target process.
When done, dump the target process' state.
The first step suspends every thread, irrespective of what it's currently doing. If it happens to hold exclusive access to a shared resource, it will hold onto it indefini... |
62,633,015 | 62,637,297 | Update progress bar during emscripten webassembly is running? | I want to show a progress bar during an emscripten webassembly is running. But the progress bar is updatet AFTER the webassembly is finished. Is there a way to either interrupt webassembly (main thread) and then continue or force javascript (main thread) to render the GUI?
main.js
Module.cwrap('calc', 'undefined', [])(... | @schteppe: Thxs! For who have the same issue. I solved it with emscripten_async_call().
main.js
Module.cwrap('calc', 'undefined', [])();
calc.cpp
void calc() {
EM_ASM({ progressBar($0); }, value);
emscripten_async_call("calcfunction, NULL, msec");
}
void calcfunction() {
...
calc something
...
}
|
62,634,042 | 62,687,122 | How install Tizen.NET NuGet package in TIzen IDE? | I'm trying to develop a simple app on Tizen that uses the accelerometer.
https://developer.samsung.com/tizen/blog/en-us/2019/04/15/how-to-use-sensors-on-a-galaxy-watch
states:
To use sensor features on Galaxy Watch and other wearable
applications, refer to the Tizen.NET NuGet package. The
Tizen.Wearable.CircularUI pro... | Simply,
Tizen Studio => C/C++ application, Web application
Visual Studio + Tizen Plugin + Base-SDK (included in Tizen Studio) => C# application
|
62,634,268 | 62,635,437 | How do I force dependents on my INTERFACE library to use C++11 or later? | I'm in the process of splitting a library of mine into a header-only lib and a compiled lib, so, for the first time, I'm trying to use CMake to "build", or rather expose, a header-only library.
Reading this and the CMake documentation, I understand I need to use an INTERFACE library, without sources. But - my headers m... | If you have a fairly recent version of cmake, you can try
target_compile_features(foo INTERFACE cxx_std_11)
This ensures that every library that uses foo, i.e.
target_link_libraries(bar PRIVATE foo)
will be compiled with C++11. For example if bar uses source file bar.cpp, then bar.cpp will be compiled with std=c++11 ... |
62,634,487 | 62,634,551 | Why is copy constructor called rather than move constructor? | I have the following code:
#include <bits/stdc++.h>
using namespace std;
class A {
public:
A(const A& a) noexcept { cout << "copy constructor" << endl; }
A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; }
A(A&& a) noexcept { cout << "move constructor" << endl; }
A& opera... | The issue is with the a parameter in AddData():
void AddData(const A&& a) // <-- const reference!!!
{
aList.push_back(std::move(a)); // selects push_back(const A&)
}
The a parameter above is a const rvalue reference. You are marking with std::move() a const object.
Marking a const object with std::move() for movin... |
62,634,605 | 62,634,854 | Conversion from class member function to C-like function pointer | I am writing a C++ wrapper around cURL library for out HTTP requests.
I would like to use dedicated classes member function for cURL callbacks (cURL requires the client to provide read and write callback functions for reading and writing uploaded/downloaded content). Since cURL lib is written in C, these callbacks must... |
i would like to pass directly to cURL a member function of a given class, using something like std::bind or std::mem_fn, but the result of these templates cannot be assigned to a C function pointer, as required in my case. Is there an elegant solution to this issue?
The solution you already have, using a static funct... |
62,634,760 | 62,635,259 | Specializing template with integer_sequence. GCC vs MSVC | So, I came across a piece of code that behaves differently in GCC and MSVC:
#include <utility>
typedef int IType;
template<typename> struct A;
template<int... Ns>
struct A<std::integer_sequence<IType, Ns...>> {
using type = bool;
};
using B = typename A<std::make_integer_sequence<IType, 3>>::type;
int main() ... | std::integer_sequence is defined as
template< class T, T... Ints >
class integer_sequence;
That is, the type of the values is T.
So when changing IType to long, also the type of Ns... should be changed to long...:
typedef int IType;
template<typename> struct A;
template<IType... Ns> // <--- HERE
struct A<std::integ... |
62,634,960 | 62,635,128 | Why does the system function always return a shifted exit status in C++? | I want to launch a script and get the exit status in C++. But I noticed that the exit status of a system command always has a left shift of 8 bits. Why does the system function do that?
Sample code:
#include <iostream>
using namespace std;
int main()
{
int exit_code_0 = system("exit 0") >> 8;
int exit_code_1 ... | In the C and C++ standards, system returns an implementation-defined value.
In POSIX systems, the return value contains a combination of different values, which can be extracted with macros. To get the program's exit status, you use WEXITSTATUS(return_value), which on your system is defined to be a right shift by 8. Th... |
62,635,033 | 62,647,909 | С++ wxWidgets: Code Architecture, Design Principles and Patterns | I recently started learning C++ and wxWidgets. Now I'm doing a calculator. When I start writing code, everything is ok, but when code gets bigger and bigger, it becomes a mess.
I want to know any C++ GUI code architectures, design principles and patterns that will help to write clean, flexible and scalable GUI applicat... | Your question certainly is broad, (like your code!) which makes an answer challenging. There are a couple of specific things I’d suggest that might help you.
Learn the SOLID Design Principles. They will help guide you through focusing on how to divide your code into manageable classes.
Learn how to write unit tests.... |
62,635,187 | 62,635,293 | build error - expected primary-expression before '.' token | I am trying to run the make command on this program here but I am running into an error that might be related to C++. The error comes up as below:
make
[ 7%] Building CXX object CMakeFiles/m3vcftools.dir/src/Main.cpp.o
/hpc/home/lsiwzyj/programs/m3vcftools/src/Main.cpp:26: error: expected primary-expression before '.'... | The use of designators to initialise structures has a feature of C for quite a while, but only found its way into C++ as of the C++20 iteration.
Hence you need to ensure you have a compiler capable of handling C++20.
Depending on which toolchain you use, you may need specific versions, such as:
gcc 8+, with--std=c++20... |
62,635,462 | 62,637,672 | How to get attribute of a directory like last access and last modify | I wanted to get timestamps of a directory and then show it to the user. I have written the following function, but it doesn't work when I give a full path of a directory to present its timestamp like access time. What should I do to fix this issue? I didn't know how should I open a directory and get information about i... | According to the documentation for CreateFileA:
To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. Appropriate security checks still apply when this flag is used without SE_BACKUP_NAME and SE_RESTORE_NAME privileges.
Your CreateFileA function call curren... |
62,635,623 | 62,636,168 | Algorithm for masking time when the signal is above a threshold | I have a realtime signal from a sensor. I need logic to implement a masking time once the signal is above a threshold. As shown below:
Here the signal (in blue) crosses a threshold. And I need to mask for any checks for the threshold for a period (masking time). (In this way I can detect only the positive pulse, simil... | you can define 2 signal-slots that take care of starting, stopping the elapsed timer,
fortunately, Qt has a class doing this for you, read the doc here and be aware of possible overflows and if required set QElapsedTimer::MonotonicClock
QElapsedTimer timer;
timer.start();
slowOperation1();
qDebug() << "The slow operati... |
62,635,894 | 62,635,965 | Why i am not able to create the Unique pointer | I get c2664 error when i try to create a unique pointer
i did write the copy constructor as well as assignment operator but still i keep getting the 2664 error
class UndoCopyPaste : public UndoRedo
{
private:
Container containerValue;
bool valid;
public:
UndoCopyPaste() = default;
... | This code with make_unique:
x = std::make_unique<Foo>(a, b);
is essentially equivalent to this:
x = std::unique_ptr<Foo>(new Foo(a, b));
Note that the a, b pass to make_unique gets passed directly to the constructor of Foo. So your code
std::make_unique<UndoCopyPaste>(new UndoCopyPaste());
is equivalent to this:
st... |
62,636,024 | 62,636,145 | Redeclaring pure virtual function | I recently came across code of the following kind:
struct A {
virtual void foo() = 0;
};
struct B : public A {
virtual void foo() = 0;
};
struct C : public B {
virtual void foo() override {
}
};
Is there any purpose in redeclaring a pure virtual method?
Even more importantly: Does this change semanti... | Look at the example from cppreference:
struct Abstract {
virtual void f() = 0; // pure virtual
}; // "Abstract" is abstract
struct Concrete : Abstract {
void f() override {} // non-pure virtual
virtual void g(); // non-pure virtual
}; // "Concrete" is non-abstract
struct Abstract2 : Concrete {
... |
62,636,028 | 62,637,122 | Issue with WriteProcessMemory | I wanted to learn a bit how does game hacking work, so I have made a simple game:
#include <iostream>
#include <Windows.h>
#include <typeinfo>
using namespace std;
void main() {
int score = 100;
int* address = &score;
SetConsoleTitle(L"Simple game");
cout << "Address of score is " << address << endl;
... | Look at where you have written (LPCVOID)val. This is the address of the memory you want to copy from in your process. 2000 is probably not a valid address. You want to copy from the val variable itself, so you should use its address, &val.
|
62,636,822 | 62,687,254 | Partial specialization of single type template parameter class template using non-type template parameter through a dependent type | All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.
Consider the following snippet:
#include <type_traits>
template <int N> struct num {};
template <typename> struct A;
// (1)
template <int N> struct A<num<N>> { using type = bool; };
// (2)
template <long N> struct A<num<N>... | As far as I can tell, the first snippet is ill-formed (and a diagnostic is required); compilers should reject the program because of the partial specialization (2).
[temp.deduct.type]/18 applies here:
If P has a form that contains <i>, and if the type of i differs
from the type of the corresponding template parameter ... |
62,636,960 | 62,637,130 | Count and pick top three in sqlite | I have table in db who called answers and i need to get the top 3 usernames who answered the most correct answers and show their username and how much they correct
I am using sqlite
table: answers
Game_id ,Username ,Question_id ,Answer ,Is_correct ,Answer_Time
in Is_correct category 1 is correct and 0 is not correct
E... | You forgot the GROUP BY clause. The correct query is:
SELECT username, SUM(is_correct) as total FROM t_players_answers
GROUP BY username ORDER BY total DESC LIMIT 3
|
62,637,145 | 62,638,236 | Initializing a std::vector replacement with single curly braces instead of double curly braces | I have a code similar to the following one:
namespace mine
{
template<class T>
using _vector = std::vector<T, my_allocator<T>>;
template<class T>
class myvector : public _vector<T>{};
};
This works in most cases as my own std::vector drop-in replacement, but it doesn't quite work at initializing it with a lis... | Note that your class do not have any constructors defined or inherited.
So for moment I was wondering how your code compiles at all.
Your code uses aggregate initialization. Since you do not have any fields just public inheritance, first argument of aggregate initialization is passed to ancestor. This is reason why you... |
62,637,271 | 62,637,379 | Longest Common Subsequence top-bottom | #include <iostream>
#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+1;i++)
for(int j=0;j<=m+1;j++)
{
if(i==0 || j==0)
t[i][j]=0;
}
for(int i=1;i<=n+1;i++)
for(int j=1;j<=m+1;j++)
{
if(x[i-1]==y... |
the o/p to the following code is always zero
because your main does :
...
LCS(x,y,x.length(),y.length());
return 0;
but you want :
...
return LCS(x,y,x.length(),y.length());
Out of that
int t[n+1][m+1];
is a variable length array, do not use them (see Why aren't variable-length arrays part of the C++ standar... |
62,637,287 | 62,637,377 | How can I use va_arg in a loop without knowing how many optional arguments there are in C++? | I want to write a function which takes at least two integer and returns the sum of all integer passed to the function:
int sumOfAtLeastTwoIntegers(int a, int b, ...){
int sum = a+b;
va_list ptr;
va_start(ptr,b);
for(){
sum += va_arg(ptr, int)
}
va_end(ptr);
return sum;
}
I want... | There are generally two ways to handle variable arguments, pre-knowledge and post-knowledge.
Pre-knowledge is like with printf("%d %c\n", anInt, aChar), there's an argument up front which you can use to figure out how many remain. An example of that would be:
int sumOfInts(size_t count, int a, ...); // Needs "count" in... |
62,637,613 | 62,651,645 | cmake: dynamic job pool change | Is it possible to do following? I have a cmake project, I can build it using, say, 16 threads. but in this cmake I include some other project which build as a part of the parent project. The child project cannot be build with 16 thread, for some reason, lets say it has heavily templated code and the machine just gets o... | Just build it separately twice:
cmake --build . --target child --parallel 4
# followed by
cmake --build . --target parent --parallel 16
I think alternatively you may create a job pool with 4 workers and assign that job pool to the child target.
|
62,637,727 | 62,637,783 | Removing spaces from String using another string | I am trying to remove spaces from string trying to use the string itself but it is not working at all. On debugging I found out that it was putting in strange value inside the string str1 which I don't understand why it does that. Following is the code attached, what can be the problem? Why is it not working?
string st... | str1[increment] is UB for any increment > 0, since str1 only has a length of 1. You are also adding the value of a character to each element, not appending a string. Just change
str1[increment] += str[i]
to
str1 += str[i]
And change string str1 = " "; to string str1;
|
62,637,805 | 62,637,968 | Pass input parameters as rvalue references? | Is it a good idea to pass parameters as rvalue references just to make it clear that you're going to manipulate the argument? Kinda like the opposite of const correctness.
For example, this function that takes a vector of strings, manipulates it somehow and returns a boolean value:
static bool isThisSomething(std::vect... |
Is it a good idea to pass parameters as rvalue references just to make it clear that you're going to manipulate the argument?
Not in general. In particular, it depends on how you are manipulating the argument.
If you accept a parameter by rvalue, then you are implying that the argument will be left in an unspecified,... |
62,638,107 | 62,638,900 | Finding words in a (weird) string in C++ | What is technically wrong in this program? The expected result is 6 since that is the total number of words present in the string.
#include <iostream>
using namespace std;
int main()
{
string str = " Let's count the number of words ";
int word = 0;
for (int i = 0; str[i] != '\0';)
... | I think you have some ways to do it. Take a look at this code. Very similar to yours:
string s = " Let's count the number of words ";
int word = 0;
for (auto i = 0; s[i] != '\0'; i++) {
if (i == 0) {
if (s[i] != ' ') {
++word;
}
continue;
}
if (s[i ... |
62,638,201 | 66,542,260 | Suppress ceres logging on console | Below is a dummy snippet for computing covariance in ceres-solver
ceres::Covariance::Options covarianceOptions;
covarianceOptions.algorithm_type = ceres::SPARSE_QR;
ceres::Covariance covarianceComputation(covarianceOptions);
if( not covarianceComputation.Compute(paramBlocks, ceresProblem) ) {
... | Setting the following environment variables would suppress logging in ceres:
GLOG_logtostderr=1
GLOG_stderrthreshold=3
GLOG_minloglevel=3
GLOG_v=-3
GLOG_logtostderr: Log messages to stderr instead of logfiles
GLOG_stderrthreshold: Copy log messages at or above this level to stderr in addition to logfiles. The number... |
62,638,349 | 62,638,722 | Input/Output operations on characters | I'm learning file handling in C++. I was implementing the exact same code in my Code::Blocks 20.03 as given in one of the programs of the book, but it's displaying no output after line 26, i.e.
cout<<"\nReading the file contents: ";
I've figured maybe these lines are erraneous, but I can't debug how:
while(file){
... | The openmode
ios::in | ios::out
will not create a new file if "TEXT" does not exist, but result in an error. Most likely this file does not exist, so you get an error and any subsequent input and output operations on the stream are ignored. You could use
ios::in | ios::out | ios::trunc
to destroy the contents of an e... |
62,638,919 | 62,639,551 | How to create an iterator function | So my task is to create a function with signature: list<Person>::iterator SearchPos(list<Person> &Mylist, Person &person). Which would later get the appropraite position for the person, in order of birth, to be inserted into the list. Its return type should be an Iterator.
I have tried doing the following :
list<Person... | After some getting used to, the compiler error is actually clear. Maybe this will help you to decipher it.
invalid initialization of non-const reference of type 'std::__cxx11::list&' from an rvalue of type 'std::__cxx11::list*'|
std::__cxx11::list<Person> is actually list<Person> in your code. The standard library ju... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.