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,133,176 | 62,134,087 | Where is __USE_BSD flag defined? | My project is building to Debian 8 without any problems.
But when building on debian 10, it leaves for this block:
#if (defined __USE_BSD)
....
#else
#error "this condition is met"
#endif
Where should __USE_BSD flag be defined?
Why is building to 8, but not 10?
| __USE_BSD is deprecated. It has changed to __USE_MISC and it is defined in features.h from glibc. You can see it in issues on github and on LWN. From Debian 8 to Debian 10 the glic package has changed to adapt to this situation, so you have to verify for the definition of __USE_MISC
.
Code below:
#include <features.h... |
62,133,506 | 62,138,880 | DirectX 11 enum D3D11_USAGE and D3D_PRIMITIVE_TOPOLOGY warning | When using DirectX 11 and MSVS2019 I get the following warnings when using the enums 'D3D11_USAGE' and 'D3D_PRIMITIVE_TOPOLOGY:
Warning C26812 The enum type 'D3D11_USAGE' is unscoped. Prefer 'enum
class' over 'enum' (Enum.3).
Warning C26812 The enum type 'D3D_PRIMITIVE_TOPOLOGY' is unscoped.
Prefer 'enum cla... | C26812 is part of the Microsoft Visual C++ Code Analysis (/analyze ) C++ Core Guidelines checkers rules.
Generally the warnings in the Windows 10 SDK system headers are automatically suppressed.
The mostly likely problem is that you are using the legacy DirectX SDK, as those headers will not be automatically suppres... |
62,133,507 | 62,133,803 | How to make step in 10 points without save value outside? | Actually what I need is I have a progress bar logic that tracking every second count of files, but case here that I don't need to update every time when I get trigger, like 1%, 3%, 7% ... I would like to define kind of step_progress variable (for example 10) and get this progress bar update steps like 10%, 20%, 30%...
... | You should stay in integer arithmetic.
[&](int current, int total) {
const int PROGRESS_UPDATE_STEP = 10;
const int MAX_PERCENTAGE = 100;
int step = std::max(total * PROGRESS_UPDATE_STEP / MAX_PERCENTAGE, 1);
if ((current % step) == 0)
{
if (progress_callback != nullptr)
{
... |
62,133,519 | 62,133,688 | Why does c++ std::hash create a functor struct and can it be called without creating a struct each time | I'm writing a program that needs to perform a lot of hashes very fast, and in a threadsafe way. For whatever reason c++'s std::hash seems to require constructing a functor every time you want to hash a value
std::hash<std::string>{}(data);
I'm quite concerned about the overhead of allocating an entire struct every t... |
but I don't understand the actual reason a functor is even necessary in this context.
There is a good reasons why std::hash is a functor and not a function and that is that it can have state. The C++ standard allows for salted hashes so that each execution of the same program can create different hashed values for t... |
62,133,911 | 62,134,196 | About `std::unique_prt<Base>& pBase= make_unique<Derived>();` | The first piece of code does not compile, whereas the second one does. Why?
The code is almost the same indeed.
I would be grateful to have some help with this question.
The code below does not compile. You could check it on http://cpp.sh/8j53y.
dynamic_cast
#include <iostream>
#include <memory>
using namespace std;
... | When you define Base::get_instance inline, Derived doesn't have a definition yet (only the forward declaration). So, it can't convert std::unique_ptr<Derived> to std::unique_ptr<Base>, because the definition where Derived inherits from Base hasn't been seen yet. For the same reason, std::make_unique<Derived>() would al... |
62,134,074 | 62,134,208 | Why does 'typeid(x) == typeid(y)' evaluate to true, where 'x' and 'y' are id-expression of type T and T& respectively? | I am reading the C++11 draft standard and the section on [expr.typeid] mentions the following (emphasis mine):
[...]
When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue ... | The answer is in [expr]
5 If an expression initially has the type “reference to T” ([dcl.ref],
[dcl.init.ref]), the type is adjusted to T prior to any further
analysis. The expression designates the object or function denoted by
the reference, and the expression is an lvalue or an xvalue, depending
on the expr... |
62,134,128 | 62,134,185 | How to define a default parameter of Vector2f ? [SFML] | I have some function func in a class Class:
void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0)){};
And I get a build error:
error C2572: 'Classs::func': redefinition of default argument: parameter 1
I tried many different synataxes but none worked. How can I define a default parameter of this type?
| Specify the default parameter in the prototype only. Don't repeat this in the function definition.
// prototype
void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0));
// definition
void func(int arg1, int arg2, Vector2f vec)
{
...
}
This advice applies to any default parameter. It's got nothing to do with ... |
62,134,254 | 62,134,981 | How to read complex numbers from a file using class and problem with access to private variable in C++? | I get a task. I must read complex numbers from a file and write them into another file. In class, I must create two private variables for the real number and imaginary number. A little bigger function I must create outside class as inline functions.
This is my code:
#include <iostream>
#include <fstream>
#include <cstd... | You have declared two friend operators that can access the private variables. So your code should look something like this
std::ostream& operator<<(std::ostream& out, const Complex_num& c)
{
return out << c.real << ' ' << c.imag;
}
std::istream& operator>>(std::istream& in, Complex_num& c)
{
// code to read c.... |
62,134,349 | 62,140,017 | How do I draw ellipse in opengl with mvp | How to draw circle/ellipse and transform it with Model-View-Projection.
I draw an ellipse in a rectangle with glDrawElements(GL_TRIANGLES, ...).
I made a shader, It works, but how to transform it?
Vertex shader
#version 330 core
layout (location = 0) in vec2 position;
void main()
{
gl_Position = vec4(position, 0.... | There are different options, to achieve what you want. On of them is to create a function, which intersects a ray and sphere.
The following algorithm is taken from Peter Shirley's book Ray Tracing in One Weekend.
The ray is defined by an origin and a direction. The sphere is defined by a center point and a radius:
floa... |
62,134,590 | 65,818,408 | How to deal with C++ header file #include errors in VS Code on Mac? | VS Code on my Mac yields #include errors for header files and third-party libraries (wxWidgets in this case). I read everything I could find, adjusted "includePath" settings in "c_cpp_properties.json", but nothing helps.
Header files are located in the same folder as .cpp files ("/src/"). The project builds and runs ni... | The origin of the problem was in several environment variables in defs.h file of WxWidgets library. To make VS Code recognize them on my system (OS X 10.14 Mojave), I had to add "defines" in the c_cpp_properties.json file in the following way:
{
"configurations": [
{
"name": "Mac",
"... |
62,134,805 | 62,134,958 | Cannot debug C++ dll loaded in C# | I wanna debug a dll made in C++ while it is inside an executable built from C# with Release mode. The C# app is supposed to not be aware. After I run the C# app I'm able to inject the dll manually which currently opens another window (so I know it was a success)
I built the dll in Debug mode in VS2019. I go Debug > Att... |
The dll does not appear in Debug > Windows > Modules
Look in the output window, it will tell you every library it's loading at run-time and whether or not it found symbols for it.
If it says symbols aren't there, make sure the .pdb file is in the same folder with the same name a the .dll, and try again.
Also since y... |
62,135,187 | 62,135,332 | std::map holding any value type | Code:
#include <iostream>
#include<map>
using namespace std;
class MyClass {
public:
class MyFieldInterface
{
public:
int m_Size;
~MyFieldInterface() = default;
};
template <typename T>
class MyField : public MyFieldInterface {
public:
MyField(T val) {m_Val... | You can't use a run-time parameter to choose between multiple types. You need to decide what type is returned at compile time. But this is exactly what templates are for, so you could simply do:
template <typename T>
MyField<T>* getType(T val) {
return new MyField<T>(val);
}
and then use the function like this:
obj... |
62,135,795 | 62,136,051 | Operator Overloading as member function | Why is it giving the error.
class Complex{
int real,imaginary;
public:
Complex():real(0),imaginary(0){};
Complex(int real, int imaginary):real(real),imaginary(imaginary){};
int getreal()const{return real;}
int getimaginary()const{return imaginary;};
Complex &operator=(const Complex& );
... | When overriding operators that have left and right parameters, you should just pass the right parameter and declare it like this:
Complex operator+(const Complex &d){
return Complex(d.getreal() + getreal(), getimaginary() + d.getimaginary());
}
When doing that, when you call getreal() or directly access that varia... |
62,135,822 | 62,136,335 | What makes some named Functions/Operators special? | Documenting on some C++20 features, i crossed some named Functions and Operators like the following under <compare> header :
constexpr bool is_eq (partial_ordering cmp) noexcept { return cmp == 0; }
constexpr bool is_neq (partial_ordering cmp) noexcept { return cmp != 0; }
constexpr bool is_lt (partial_ordering... | The first set of functions is part of the library support for the spaceship operator <=>, added into C++20. Those utilities are there for the cases in which one finds themselves using <=> directly, instead of implicitly via the core language.
On one foot, the way spaceship works is by returning an object which can be ... |
62,136,242 | 62,136,887 | How can I increase my performance with Eigen? (sample code included) | Is there anything overly inefficient with my matrix math in the following function? I have optimizations enabled in visual studio, and am building in 64 bit release mode. I am feeding rather large matricies through here(750X350), but my performance seems slow none-the-less.
void NeuralNetwork::backward(Eigen::MatrixXf... | Avoid memory-intensive operations in performance-sensitive code.
Never pass "big arguments" by value.
For instance
void NeuralNetwork::backward(Eigen::MatrixXf back, float learningRate)
should probably be
void NeuralNetwork::backward(const Eigen::MatrixXf& back, float learningRate)
This avoids copy-constructing the... |
62,136,417 | 62,136,672 | How can I range check C++14 user defined literals? | Is there a way to persuade a good C++ compiler to warn about the overflow
in constructing a user defined type from a user defined literal as shown in the example
code below? At least (via Godbolt) GCC and Clang warn about the overflow in the equivalent intrinsic code, but MSVC doesn't. None care about the same error in... | You can force a hard error by checking if the unsigned long long's value is narrowed when cast to a short value:
constexpr MyShort operator "" _MyShort ( unsigned long long arg )
{
if (static_cast<short>(arg) != arg)
{
std::cout << "oops"; // or some other non-constexpr code
}
return MyShort (arg);
}
He... |
62,136,643 | 62,136,737 | Number of occurrences of an element in a 2d-array c++ | If I'm given a 2d array say {{1,2},{2,3,4},{5,1,2,7}}, how do I count how many times an element say 1 has occurred in the array?
Is there any c++ STL function for this?
| Assuming that the 2d array is nested standard library containers and the outer container is called arr:
auto target = 1;
auto count = std::accumulate(
std::begin(arr), std::end(arr), 0,
[target](auto a, auto const &inner) {
return a + std::count(std::begin(inner), std::end(inner), target);
}
);
(De... |
62,136,719 | 62,137,229 | Counting the balance factor for AVL trees | Hello everyone!
I can't get the idea of how we count a balance factor for nodes in AVL tree. Can somebody explain it?
Here's the code of counting the balance, that I found:
size_t height() const
{
size_t left_h = (left == nullptr) ? 0 : left->height();
size_t right_h = (right == nullptr)... | As Wikipedia states
In a binary tree, the balance factor of a node is defined to be the height difference of its two-child sub-trees.
So, in order to calculate the balance of a node, you have to calculate the heights of its children.
Let's analyze the code which calculates balance:
signed char balance()
{
// cal... |
62,136,944 | 62,137,017 | Recursive function calls working behind the scenes | So I can't wrap my head around recursive function calls especially with this example:
int Addup(int n)
{
//6
if(n <= 1)
return 1;
else
return n + Addup(n - 1);
/*
6 + 5 + 4 + 3 + 2 + 1
*/
}
Now if for example we did Addup(6), how will that work, what will the program do at runt... | The secret to understanding recursion is that recursive functions work exactly like non-recursive functions.
Your functions work exactly like these:
int Addup_1(int n)
{
return 1;
}
int Addup_2(int n)
{
if(n <= 1)
return 1;
else
return n + Addup_1(n - 1);
}
int Addup_3(int n)
{
if(n... |
62,137,340 | 62,137,341 | Redirecting output of boost::timer::auto_cpu_timer | I'm widely using boost::timer::auto_cpu_timer to measure the execution time of different functions and code blocks. I'm using a macro to simplify its use at the time I can easily disable it in production:
#include <boost/timer/timer.hpp>
#include <string>
#ifdef LOG_MEASURE_TIME
# define CPU_TIMER() boost::timer::aut... | I'm documenting it here because after googling and stackoverflowing for it I couldn't find the answer.
I don't know why I didn't pay attention to it first, but there is a constructor for boost::timer::auto_cpu_timer that receives a std::ostream&, so the solution is quite straight forward:
#include <iostream>
#ifdef LO... |
62,137,547 | 62,137,689 | Waking up a thread waiting on a condition in infinite loop | I have a pretty basic producer / consumer implementation. The producer is the "main" thread, and the consumer is executed on a separate thread. However the consumer needs to be explicitly started, using a Start() function. This sets the "processing" flag to true (used in the infinite while loop).
Once in the while loop... | A couple of changes is required for the consumer to wait for change in processing_:
~Consumer() {
if (processing_thread_.joinable()) {
Stop();
processing_thread_.join();
}
}
// ...
void Stop() {
std::lock_guard<std::mutex> lock(mtx_);
processing_ = false;
cv_.notify_one();
}
// ...
void Run() {
fo... |
62,137,725 | 62,139,267 | cmake add_custom_command + Xcode: multi output = multi command invocation | I have custom command that generate several headers at once.
All works fine with make/ninja files generated by cmake.
But if I generate Xcode project via cmake -GXCode,
then instead of once gen.sh was invoked 10 times
and not only that, it also will be invoked every build,
even if timestamps of generated file are young... | In OUTPUT option relative paths are treated as relative to the binary directory.
That is, your add_custom_command actually doesn't produce the files declared as OUTPUT.
This is why it is called more and more: the build tool finds out that an OUTPUT file does not exist, and runs the COMMAND for build that file. (Many bu... |
62,138,000 | 62,138,237 | Is there any data race between std::weak_ptr and corresponding std::shared_ptr? | According to cppref, accessing const members of shared_ptr across multiple threads is safe. But is this statement valid when we have a weak_ptr that corresponds to a shared_ptr?
As an example assume the following code:
#include <memory>
#include <iostream>
#include <thread>
std::shared_ptr<int> sp;
std::weak_ptr<int> ... | Yes. The reference counter is atomic, so there are no data races in your example.
That being said, mutable operations on objects pointed by std::shared_ptr are not atomic, so they must be guarded as you would guard access via a plain pointer.
|
62,138,412 | 62,144,725 | C++ treating object* as int* | I have some code that accepts a pointer to an object, and this has been working fine thus far, however, after some cleanup (I code messy, and then clean up when most of the bugs are gone), a function that accepts a pointer, is now treating the pointer passed to it as an int*.
I have checked that I am indeed passing a p... | The compiler doesn't understand what TreeNode<T> is because it doesn't name a type; TreeNode is not a template. Use TreeNode everywhere you have TreeNode<T>.
TreeNode implicitly gets T from its outer template class, so specifying it in this way isn't even necessary. To put it another way, TreeStructure<int>::TreeNode... |
62,138,526 | 62,138,586 | Dynamically change the behavior of member functions in C++ | For a homework, we need to modify a variety of images with multiple different algorithms and format a document with our answers. I have already coded the algorithms in C++, but I want to write a program that will modify the images and format the document automatically. To do this, I want to have a class of the form
cla... | You'll have to somehow remember the choice. In C++, function pointers and function objects don't participate in overload resolution so you cannot actually replace operator()() with a different function, but you certainly can write operator()() with some type of conditional that checks the choice selected earlier and d... |
62,138,711 | 62,138,982 | Purpose of overloading member function returning iterator and const_iterator | In my class assignment I am suppose to implement member functions of a predefined class. I am confused on the purpose of these the overload on findStudent. Can this class not be designed to only contain one definition, which returns a regular iterator that can be casted as const? Or rather, use std::find since it is al... | The purpose of overloading those functions is that they differ by their const-ness.
Consider:
you pass Class foo; to a function
void bar(Class& foo).
If inside this function you were to call findStudent(), the non-const version of the member function would be invoked. As a result, you would get a mutating iterator of... |
62,139,127 | 62,140,248 | Compile-time detection of missing user-defined to_string() | I want to provide a to_string(obj) function for every object type I create.
I found this question, applied the accepted answer, and it works. So far so good.
Then I created a new type, but forgot to write a to_string() for it (or better: I accidentally made it unreachable by ADL). The problem is: my program still compi... | The idea of that accepted answer is different: you put A outside notstd namespace and then use qualified notstd::to_string instead of unqualified to_string. That is:
namespace notstd {
// ...
}
class A {
friend std::string to_string(const A&);
};
A a;
std::cout << notstd::to_string(a);
Now your code won't co... |
62,139,186 | 62,139,612 | Problem with saving values from function in C++ | Im bad with pointers and references so i have a question why in function hoffman the values are good and fine but when im trying see them out of function hoffman in main() i cant see almost none of this values.
This is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorit... | This code is wrong
tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
You are taking pointers to elements in your vector and pushing back items onto the vector. The problem with this is that if the vector reallocates all your pointers become invalid.
Simplest fix would be to use index... |
62,139,502 | 62,139,591 | C++ pointer not null but cannot be freed | I'm implementing an open HashTable. My trouble arises in the destructor, where I iterate through all the buckets in an array, for each array I would delete all the nodes in a linked list.
// Deallocate all buckets
for (int i=0; i<maxBuckets; i++) {
Cell * p = m_data[i];
while (... | The error is pretty clear. You tried to delete a value that was not returned by new.
What we don't know is if the value is the address of a non-allocated value, just uninitialized (garbage) or if you've corrupted the heap. You haven't provided information to determine that.
But you do know that the value you are trying... |
62,139,823 | 62,140,031 | Conversion from signed int to signed char? | I'm following an example from Stroustrups C_++ 4th Ed. Page 143, where there is Errata. -160, should be -140.
Specifically the conversion of a signed int to a signed char.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
signed char sc = -140;
cout << "signed int = " <<
int((s... | When converting a value to an unsigned type, the value is taken modulo N,
where N = 2sizeof(T)*CHAR_BIT.
In simple terms, it means that N*i is added to the value to put it in the representable range, where i is an integer (possibly negative).
You can always determine a single specific value of i that puts the value in... |
62,140,151 | 62,140,361 | is it possible to explain why this returns 21 | Hello this isn't an assignment or anything but can you explain why this returns 2 1.
#include <string>
using namespace std;
void fun(int);
int main()
{
int a = 0;
fun(a);
return 0;
}
void fun(int n)
{
if (n < 2)
{
fun(++n);
cout << n<<" ";
}
}
| Flow of fun() :
You are passing a which is initialized to 0 as the parameter to the fun(). So, You call fun(0) from main().
In the call fun(0) the condition n<2 is true since at the start, it is 0. So the function fun(0) will
call fun(++n),that is fun(1) and push the current function call on the stack. Notice, the val... |
62,140,266 | 62,140,646 | multiplication of random numbers different from zero | I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?
#include <iostream>
#... | To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
product *= value;
std::cout << value << std::::endl;
}
Next, we only want to do the multiplicat... |
62,140,312 | 62,140,667 | What am I able to (not) include in a .cpp file? | This question is pretty weird.
Say I have a file, called idiot.cpp, and it begins with:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#include "idiot.h"
and I have a header file, idiot.h. First of all, in... | idiot.cpp does not need to include anything included indirectly by idiot.h to be able to compile.
The more interesting case: bonito.cpp #includes idiot.h and idiot.h includes x.h. If idiot.h only uses the content of x.h for private or anonymous namespace code - and bonito.cpp wants to use something from x.h too, then ... |
62,140,370 | 62,140,757 | Iterate through resource string table | I have a string table defined like this in my Win32 app:
STRINGTABLE
BEGIN
IDS_STRING101 "myString1"
IDS_STRING102 "myString2"
IDS_STRING103 "myString3"
END
Since I want all of these strings to be part of an array, is it possible to iterate through this table? Since LoadString... | There is no API to enumerate through the individual strings of a string table. You would have to load the entire string table resource as a whole into memory and then parse it manually per the documentation.
A simpler solution would be to just call LoadStringA() in a loop, since your string IDs are sequential, eg:
char... |
62,140,474 | 62,140,585 | C++ callback functions in class Referention to non-static funct | I have that code and want to modify it and put it in class for example MergeSort
after I convert it to class I get an error in that line in initMergeSort:
error: no matches converting function ‘merge_sort’ to type ‘void* ()(void)’
if (pthread_create(&thread, NULL, merge_sort, (void *) NULL) != 0) {
Referent... | You can't use a non-static class method for a pthread callback. A non-static method has a hidden this parameter that pthread won't be able to account for when calling the method.
You need to use a static method instead (or a non-member function), eg:
class MergeSort {
private:
...
static void* static_merge_so... |
62,140,700 | 62,140,740 | Perspective projection for a polygon Using OpenGL | I'm trying to implement a perspective projection using open-GL
But when I apply gluPerspective(0,0.5,0.5,5) method, the polygon is not shown in a perspective view and shown in orthogonal view instead
here is the output
Anyone can help
my code:
#include<GL/glut.h>
float angle = 2;
void myinit(void)
{
glClearColor(... | the first argument to to gluPerspective is wrong:
gluPerspective(0,0.5,0.5,5);
The first argument to gluPerspective is the vertical field of view angle in degrees. The value has to be greater than 0.0 and less than 180. 0.0 is an invalid argument and causes undefined behavior.
Probably the instruction doesn't set th... |
62,140,998 | 62,141,322 | Questions regarding efficiency | So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is mo... | I would say that both are almost the same, but as mentioned in the comments, the line:
str2.push_back(*it);
Is actually very inefficient, since std::string may copy the existing string to a new location in the memory, and then append the next char to the string, which is wasteful.
But I am wondering, why to create the... |
62,141,022 | 62,141,092 | Virtual overloaded operators >> and << | I need an interface that would require its subclasses to overload << and >>, but I'm not quite sure how since these operators aren't overloaded as member functions:
std::istream& operator>> (std::istream& in, Student& student) {
in >> student.name >> student.group;
for (int& i : student.marks) { in >> i; }
... | You could do something like this:
class StudentInterface
{
public:
virtual void readSelfFrom(std::istream& in) = 0;
};
std::istream& operator>> (std::istream& in, StudentInteface& student)
{
student.readSelfFrom(in);
return in;
}
And then let users derive from StudentInterface, eg:
class Student: public... |
62,141,755 | 62,143,059 | wcstombs_s(), length of converted string | errno_t wcstombs_s(
size_t *pReturnValue,
char *mbstr,
size_t sizeInBytes,
const wchar_t *wcstr,
size_t count
);
Microsoft VS2019's documentation says:
pReturnValue
The size in bytes of the converted string, including the null terminator.
...
If wcstombs_s successfully converts the source string, it ... | Neither. The cppreference is referring to the standards compliant version of the function. The Microsoft documentation is referring to the version implemented in their standard library.
If you're using MS Visual C++, use the Microsoft docs. Otherwise, use the cppreference docs.
|
62,142,357 | 62,143,036 | C++ copy construct rvalue reference question | I'm learning the rvalue reference concept in c++.
When testing the following code, I found the "fun" was called despite it not using fun(abc &&) to accept the temporary object(prvalue).
class abc
{
};
void fun(abc &)
{
cout << 1111111 << endl;
}
void main()
{
fun(abc());
}
output: 1111111
If this is allowed ... | The reason why both fail to compile is that temporaries cannot be bound to non-const references.
In the first case, the expression abc() constructs a temporary abc object. Trying to pass it to fun() tries to bind the temporary to a non-const reference; this is disallowed.
The second case is effectively the same thing:... |
62,142,502 | 62,142,536 | How to use references/pointers with mathematical operations in c++? | I'm pretty new to C++ pointers and references. Say I have two variables i1 and i2, is there a way I can track their difference (or any other operation), even if one of them changes. My attempt at this is shown below, as well as what I want to achieve.
int i1 = 20;
int i2 = 20;
int*r1 = &i1;
int*r2 = &i2;
int s = *r1-*... | What you are asking for is not doable, as you can't take a reference to an expression. Once you have saved the result of the expression *r1 - *r2 into your s variable, you would have to perform the *r1 - *r2 expression again after updating the source values to save a new result into s, eg:
int i1 = 20;
int i2 = 20;
i... |
62,142,574 | 62,189,551 | How can I update global variable value in LLVM IR using IRBuilder? | I want to update value of global variable in LLVM IR.
I created new global variable in ModulePass:
bool runOnModule(llvm::Module &M) {
IRBuilder<> Builder(M.getContext());
Instruction *I = &*inst_begin(M.getFunction("main"));
Builder.SetInsertPoint(I);
M.getOrInsertGlobal("globalKey", Builder.getInt64Ty... | After @droptop helpful comment I changed my code to actually load the global variable's value using load instruction. It works fine now. Updated code is shown below if anyone need it:
Instruction* InstructionVisitor::getGlobalValue(Instruction* I, StringRef Name) {
IRBuilder<> Builder(I->getContext());
Builder.... |
62,142,997 | 62,144,125 | My display function does not display File content in C++ console, the second time I enter the option to display (which is 2 in the menu) | #include <iostream>
#include <string>
#include <fstream>
using namespace std;
//code to register, display and delete a constituency for election using file handling
fstream constituencies("constituencies.txt", ios::out | ios::in);
fstream temp("temp.txt", ios::out | ios::in);
/* declaring files for constituencies re... | First of all, you need to add fflush(stdin) before getline(cin, consti) in the first defined function, since it's skipping to ask for an input.
And now, let's solve the main problem.
The problem was, the file content in second time execution didn't show up anything.
The reason is: Even after not reading, it'll go to en... |
62,143,094 | 62,143,116 | Tuples: No matching function for call to 'get' | I have 3 structs : Student, Citizen, Employee. I want user to be able to choose what struct they want to work with (std::vector of structs, actually). Since there's no way to define type at runtime, I created all 3 vectors, but will use only one of them (depending on the user's choice), others will stay empty:
std::vec... | Unfortunately, what you're proposing isn't possible in C++. The C++ typing and template system works at compile-time, where information read in from the user isn't available. As a result, anything passed into a template's angle braces needs to be determinable at compile-time. In your case, the number the user enters, i... |
62,143,120 | 62,163,867 | OpenCV C++ 3 Dimensional Mat Data Access Wrong Values | I am using C++ OpenCV DNN to get results into a Mat. Here, dnnResult is the output Mat. The output values are float. I want extract 66 values into 3 separate arrays or a 3 x 66 matrix.
dnnResult.size[0] = 3
dnnResult.size[1] = 1
dnnResult.size[2] = 66
dnnResult.dims = 3
I tried looping like this to get value, but the... | change
dnnResult.at<double>(..) to dnnResult.at<float>(..)
+ more information about cv::Mat::at
template<typename _Tp> inline
_Tp& Mat::at(int i0, int i1, int i2)
{
CV_DbgAssert( elemSize() == sizeof(_Tp) );
return *(_Tp*)ptr(i0, i1, i2);
}
inline
const uchar* Mat::ptr(int i0, int i1, int i2) const
{
CV_Db... |
62,143,432 | 62,143,495 | inline functions and forward references | At https://www.studytonight.com/cpp/inline-functions.php they are explaining inline functions
All the inline functions are evaluated by the compiler, at the end of class declaration.
class ForwardReference
{
int i;
public:
// call to undeclared function
int f()
{
return g()+10;
}
in... | The book is explicitly pointing out to you "no inline function in a class is evaluated until the closing braces of class declaration". Outside of a class declaration, with ordinary functions, this fails:
int f()
{
return g()+10;
}
int g()
{
return 0;
}
Try to compile a C++ source file containing just this, an... |
62,143,841 | 62,155,173 | Spirit X3, referring to a previously matched value | I'm writing a parser in Spirit X3 in order to get familiar with it, and even though I'm pretty familiar Qi I'm still hitting some stumbling blocks in X3.
For example, the Qi examples include a basic XML parser that should you how to match a previously matched value using Phoenix placeholders. However, I've only kinda ... | Nice question.
The best answer would be to do exactly what XML does: outlaw [/ inside the tag data. In fact, XML outlaws < (because it could be opening a nested tag, and you don't want to have to potentially read-ahead the entire stream to find whether it is a valid subtag).
XML uses character entities ("escapes" like... |
62,144,108 | 62,144,129 | Why does the pre-decrement cause strange changes? | I have the following code in C++
int factorial_recursivo(int factorial) {
if(factorial <= 1) return 1;
// To show all the factors in each iteration std::cout << factorial << std::endl;
return factorial * factorial_recursivo(--factorial);
}
However, if i write a number n, the result is the factorial of the numbe... | You should do value - 1 instead:
return factorial * factorial_recursivo(factorial-1);
Executing:
return factorial * factorial_recursivo(--factorial);
results in unsequenced modification and access to factorial. On my laptop it actually produces 6 regardless of what I input as a parameter. Thank you M.M for asking me ... |
62,144,138 | 62,154,100 | How do I properly cancel a Boost deadline_timer from a destructor (in a multithreaded environment)? | I have a class called Timer that exposes two methods called start and stop.
void Timer::start() {
_enabled.store(true, std::memory_order::memory_order_release);
_timer.expires_from_now(_delay);
_timer.async_wait(
std::bind(
&Timer::tick,
this,
std::placeholders::... | A pattern is to have a shared_ptr to your Timer (by using std::enable_shared_from_this).
That way you can keep the timer alive as long as the handler hasn't been executed (by keeping a copy of the shared pointer bound to the handler).
Other solutions could be:
having externally allocated timers (e.g. in a container wi... |
62,144,638 | 62,144,663 | Displaying all elements of a vector | First for loop
int i;
for (i = 0; i <= vec.size(); i++) {
if (vec.size() == 0) {
cout << "[] The list is Empty" << endl;
} else {
cout << vec[i] << " ";
}
}
}
Second for loop
cout << "[ ";
for(auto num : vec)
cout << num << " ";
cout << "]";
Why is it that when I display all the elemen... | In the first loop, when i reaches vec.size(), vec[i] is out of bounds of vec, which leads to undefined behaviour (UB). You need to change the loop condition from i<=vec.size() to i<vec.size().
Also, your check for vec.size() == 0 inside of the loop will never be true. That check needs to be moved above the loop.
if (ve... |
62,144,675 | 62,144,863 | How can I fix my code for an Arduino LED string controller? | I'm getting :
invalid types 'int[int]' for array subscript
when I try to compile my code for my Arduino and for the life of me I can't figure out what I'm doing wrong.
Here's my code (feel free to use it although it isn't done yet).
/*
* Changelog 0.5
* pins[], pinFV[], pinV[], pinDelay[] moved
* to pins[][]
*/
int... | You have 2 arrays with the same name. Inside setup the local one is the one that is referred to and it isn't a 2D array so you can't use it as such.
At global scope:
int pins[4][4];
And inside setup:
int pins[4] = {9, 5, 6, 3};
Try naming one of them something different. Having two things with the same name can b... |
62,144,812 | 62,145,110 | Can 3 values (consecutive) of a vector be sorted using this method? | So I'm trying to swap 3 values of a vector of ints by rotating them leftwards , i.e. ABC->BCA
And i want to make this happen by using iterators. Also, i know the iterator referring to C.
So what i did was I made the following function:
void xsort(vector<int>::iterator& it)
{
int temp= *(it-2);
*(it-2)= *(it-1);... | U can use std::rotate, as follows
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector vec {'A', 'B', 'C'};
std::rotate(vec.rbegin(), vec.rend()-1, vec.rend());
for(auto const &el :vec) std::cout<< el <<" ";
}
So the out is -> B C A
If u have two functions and u want to pass ... |
62,145,064 | 62,145,098 | C++ The loop in my switch format isn't allowing me to display menu options or accept input? | I'm needing to write a loan program for a course and I have this bit of code thus far:
/*
Project: Course Project - Loan Calculator
Program Description: To calculate customer's loan
information including interest rate, monthly
payment and number of months payments will be
required for.
Developer: _____... | You had this:
while (choice !=4);
This makes it so that your code never continues further than this while loop. Unless your compiler removes this line during optimization.
This is the correct way:
while (choice !=4) {
switch (choice)
{
case 1:
cout << "Monthly Payment C... |
62,145,083 | 62,145,211 | C++ Passing vector to a function that is already passed | #include<bits/stdc++.h>
using namespace std;
void func(vector<int> &vect)
{
vect.push_back(30);
extra_func(vect);
}
void extra_func(vector<int> &vect)
{
vect.push_back(40);
}
int main(){
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
for (int i=0; ... | You code doesn't compile because func() doesn't know about extra_func(). You either need a function declaration (sometimes called a function prototype) or to rearrange your functions.
void extra_func(vector<int> &); // declaration
void func(vector<int> &vect)
{
vect.push_back(30);
extra_func(vect);
}
void e... |
62,145,451 | 62,145,474 | Trouble calling c++ function | I wrote a c++ function what takes in an array and prints some stuff with no output, yet when I try and call it I get the error:
main.cpp:11:2: error: no matching function for call to 'render'
render(board);
^~~~~~
./functions.hpp:1:6: note: candidate function not viable: requires 0 arguments, but 1 was... | Your render function accepts an array of integers, while you are trying to pass in an array of string.
You can fix this by changing your function to accept the type you are trying to pass.
void render(string board[]){
cout << board[0] << "\n";
}
Your compiler output points to a function prototype for void render(... |
62,145,858 | 62,145,960 | Could a object be moved if this is no `copy constructor` for the class? | Could a object be moved if this is no copy constructor for the class?In another word, is it legal that a class has move constructor whereas its copy constructor is marked as deleted.If it's ok, does it go againt the rule of three, rule of five?
| Yes it's perfectly legal.
Think about e.g. std::unique_ptr, which is indeed movable but not copyable.
|
62,146,104 | 62,146,147 | C++ - Behaviour of derived class constructor | I'm preparing my exam. Below is output of a sample question, the block 3 confuses me.
--- Block 1 ---
H
SM
2 x S
DP
--- Block 2 ---
H
SM
2 x S
DP
--- Block 3 ---
H
Copy SM
1 x S
Copy DP
--- Block 4 ---
H=
--- Block 5 ---
̃H
--- Block 6 ---
̃DP
̃S
̃SM
̃H
̃DP
̃S
̃SM
̃H
We pass a Deadpool type object to construc... |
Who called the Sword constructor?
DeadPool has a data member sword with type Sword, it's not mentioned in the copy constructor of DeadPool, then it'll be initialized by its default constructor. That's why you got the output 1 x S, between the invocation of the constructor of base SpiderMan and invocation of the const... |
62,146,143 | 62,146,195 | Should child class override the constructors if they have identical parameter as the parent class? | I am using VC++.
I define a parent class:
class A
{
A();
A(int a);
virtual ~A();
virtual void DoSomething();
}
Then define a child class:
class B: public A
{
virtual void DoSomething();
}
In class B, only a new version of DoSomething is introduced. All other functions, including the constructors and ... | The default constructor B::B() would be implicitly-defined, while B::B(int) won't. You can define one explicitly, or apply using for inheriting constructor (since C++11).
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base... |
62,146,445 | 62,147,423 | linux g++ regular expressions not working | I'm trying to find sub string using regular expressions on linux g++.
For example :
std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";
std::string sn = "";
std::regex re("SerialNumber\: (.*)\n");
std::smatch match;
if (std::regex_search(logline, m... | you do not need '\' before ':'. so the correct line is:
std::regex re("SerialNumber: (.*)\n");
with this change your code works with gcc starting gcc 4.9.1. https://wandbox.org/permlink/uuVCxdtpHAjZTghP
|
62,146,584 | 62,147,262 | Read file with separation in C++ | I have a script which reads text file into a vector.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
struct Items
{
string Name;
int Number1;
double Number2;
};
int main()
{
ifstream file("file4.txt");
vector<Items> player_data;
... | You have a few problems with your code; this solution works but it's not elegant. I'm sure the people here can give you or direct you to a more elegant one :)
First - after opening a file you need to check if it is open
Second - it is better to use std::getline() to read from the file because it gets the whole line. Th... |
62,146,906 | 62,147,328 | C++ classes vs. C different files | Currently in a project there is a clear set of functions that pertain to a clear responsibility. Because the responsibility is a periodic process that requires buffers and counters for each iteration, I have to reset the variables used by those functions after each cycle. The variables are mostly static because per cyc... | To declare static file scope variables is the simplest form of private encapsulation. Such design is particularly common in embedded systems and hardware-related code. It's perfectly OK practice in a single-threaded program where there is just one single instance of the module/ADT that uses the variables ("singleton pa... |
62,146,986 | 62,147,133 | C++ Implementing class function with nested struct outside | So, I want to make the code a bit more pretty in that I want the class def to contain just function declarations. Here is my code:
template <typename T>
class splay_tree
{
struct node
{
T data;
node* parent;
node* left;
node* right;
};
node* grandp(node* x)
{
... | Like this
template <class T>
typename splay_tree<T>::node* splay_tree<T>::error()
The return type of a method is not the the scope of method so splay_tree<T>:: must be specified separately.
Plus since this is a template, you need template <class T>
|
62,147,481 | 62,148,084 | C/C++ Variadic Macro Function Overloading | I am trying to build a simple c++ logger for learning purposes, but I seem to be stuck at the following issue. Let's say that I have a namespace that contains two functions as follows:
namespace l {
void _p(const char* file, const int line, int vl, const char* fmt, ...) {
printf("%d:%s:%d: ", vl, file, line... |
what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time.
Sure, you can do:
#define p(...) _p(__FILE__, __LINE__, __VA_ARGS__)
Macros are processed at preprocessing stage at which ... |
62,147,515 | 62,147,630 | C++ Question about two class constructors | My teacher gave me a sample code, but I'm a bit confused.
class CBook
{
...
pubic:
CBook();
CBook(string Title, string Auther, int Year); // I know this is the constructor
~CBook(); // and this is the destructor
};
I wish to know the use of CBook();, is this line of code really necessary?
T... | Actually compiler will call this constructor in case you will do like that:
CBook obj;
in another words, you will not pass any arguments to it.
So, if you delete it and try for example:
CBook obj;
compiler will give you an error like "no default constructor"
Sometimes we need object without any of its members filled ... |
62,147,604 | 62,147,810 | Output of pow() function in C++ is not giving accurate answer | The user will give an integer input. I have to find the mod after squaring it. But when I give a big integer, pow() gives the wrong answer. How can I fix that?
#include<bits/stdc++.h>
using namespace std;
int main()
{
//ios_base:: sync_with_stdio(false);
//cin.tie(NULL);
int t;
cin >> t;
for(int i... | As the comments say, pow works on floating numbers. Since you want to square integers, you're better off just multiplying them together using sn = n*n. If you use an unsigned long long you'll be able to exactly compute the square but only if this square is at most +18,446,744,073,709,551,615 (see https://en.m.wikipedia... |
62,147,656 | 62,147,741 | CodeBlocks C++ program not running | Few days back I downloaded CodeBlocks for C++.
I tried to run a HelloWorld program but it does not runs.
When I click on Build and Run nothing happens.
My compiler location is right i think (C:\Program Files\CodeBlocks\MinGW)
Below the inteface is see this error message:-
No such file or directory.
Please Help!
enter i... | It looks like you have something wrong in your compiler settings. Maybe look at this question: CodeBlocks : [highlight: No such directory found
All I did was go to "Compiler Settings" ("Settings" -> "Compiler" -> Global compiler settings), and selected "Reset Defaults".
Does that work for you?
|
62,147,834 | 62,148,401 | How to supply a templated function as a parameter for another function, with a default value, in C++? | How can I have a templated function as a parameter for another function, with a default value?
For example, if I wanted to supply a function with a templated sort function, but have it default to std::sort, what would that look like?
The following does not work:
#include <algorithm> // std::sort
template <class iterat... | An alternative and less constrained solution is to wrap std::sort or another function template invocation into a lambda object:
template <class Container, class Sort>
void temp(Container& c, Sort sort) {
sort(c);
}
template <class Container>
void temp(Container& c) {
temp(c, [](auto& c) { std::sort(c.begin(), ... |
62,147,967 | 62,148,309 | Best way to create a C++ Makefile that mkaes a prod build and creates debugging information? | I'm pretty confused about the idea of makefiles, can't really grasp how to execute stuff on it. I have a program which I would like to create a makefile
Would this be able to produce a build of my program and also output debug info? Honestly completely confused.
| There are two targets in the makefile.
The first target is named TMA1Question3.exe, depends on Loop.cpp and will call g++ -o Loop.exe Loop.cpp. It will build the artifact Loop.exe without debug info.
The second target is named debug, has no dependencies and will call g++ -g Loop.cpp. It will build the artifact a.out co... |
62,148,072 | 62,149,632 | How to visualize the result of pcl::FPFHEstimation in point cloud using PCL? | I'm using pcl::FPFHEstimation class to detect feature point like this:
pcl::FPFHEstimationOMP<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fest;
pcl::PointCloud<pcl::FPFHSignature33>::Ptr object_features(new pcl::PointCloud<pcl::FPFHSignature33>());
fest.setRadiusSearch(feature_radius);
fest.setInputCloud(source_c... | Fast point feature histogram is a point descriptor (which in pcl comes in the form of pcl::FPFHSignature33). This means that the algorithm computes a histogram for all points in the input point cloud. Once the descriptors of the points are computed, then you can classify, segment... the points. But the process of class... |
62,148,630 | 62,149,624 | indexing names in a std::vector | I made a program that lets you enter your name and outputs it.
I can't find a way to index my names. For example, if you enter "John, Jason, Jam", you would get the names numbered like so: "1:John, 2:Jason, 3:Jam"
int main()
{
vector<string> names;
names.push_back(read_string("Enter a name: "));
names.pu... | I think you are looking for something like this:
for(int i = 0; i < names.size(); i++)
{
write_line( (i+1) +names[i]);
}
|
62,148,844 | 62,149,330 | Finding Prime numbers in a vector and print them in revers in another vector | here's the problem:
x is a vector with n elements.. build another vector, y, which will contain prime elements from x, but in reverse order.
My code. Don't know what I'm doing wrong.
| In the for loop you are using in line 16, you should decrement the value of i, i.e, i--, while you are incrementing it, which might be leading it to be an infinite loop. Also, you have not handled the condition if v[i] = 1. According to your code, it will show 1 as prime number though it shouldn't and also you have dec... |
62,148,948 | 62,149,393 | Two pointers or one pointer + size_t? | I'm working on a library that needs to work with pointers and I came across an important design choice. Let's say I have a function do_stuff that needs to work on a pointer. There are two ways to define such a function
1) void do_stuff(T* first, T* last)
2) void do_stuff(T* ptr, size_t count)
where T names an object ty... | Size has the advantage that it is not possible to accidentally pass two unrelated pointers to the function. Sure, it is still possible to pass the wrong size, but the fact that second argument is relative rather than absolute makes that approach simpler.
If we generalise the problem to all iterators, then pair of itera... |
62,148,977 | 62,153,241 | Compile-time Size of Struct Minus Padding | I'm trying to use Boost MPL and Fusion to calculate the size of a struct exclusive of any padding. This is my current best attempt:
Live example
template<class T>
constexpr std::size_t sizeof_members(void)
{
using namespace std;
namespace mpl = boost::mpl;
namespace fusion = boost::fusion;
//This works... | Since you tagged this C++17, the answer is: don't use Boost.MPL. Given C++11 even, the metaprogramming library you want is Boost.Mp11 - it's substantially better in all respects.
The newer, easier-to-use, ridiculously-more-compile-time-efficient version of Boost.Fusion that you want to use is Boost.Hana:
struct Foo_t ... |
62,149,939 | 62,150,143 | Why does the class reference constructor overload get called from an rvalue when there's an rvalue constructor available? | This code
#include <iostream>
struct A
{
A(int i) {std::cout << "int received\n";}
A(A& a) {std::cout << "ref received\n";}
};
int main()
{
int j = 5;
A a = j;
}
unexpectedly throws the following compiler error:
error: invalid initialization of non-const reference of type 'A&' from an rvalue of type ... | A a = j; performs copy initialization.
Until C++17,
If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type deriv... |
62,149,989 | 62,150,070 | Is there a lower_bound() function in C++ for long long data type? | pos is an iterator to the lower bound of q. Here q is a long long integer and prefix is a vector which stores long long elements.
vector <int> :: iterator pos;
pos = lower_bound(prefix.begin(), prefix.end(), q);
I get the following error:
no operator "=" matches these operands -- operand types are: __gnu_cxx::__norma... | Your declaration of pos is incorrect. You vector - prefix is of declared as vector<long long>prefix;. The iterator should also be of the same type.
You can try using the following -
vector<long long>::iterator pos = lower_bound(prefix.begin(), prefix.end(), q);
You can always choose the following syntax as well if you... |
62,150,048 | 62,150,779 | Why does g++ 10.1 complain about a named lambda in a header file and others do not? | I have a header file with a named lambda that I use for measuring the execution time of some functions (the lambda is partially a result of this question How to Write a Lambda Wrapping a Function with Optional Return Value). It resides in a header file that I include from several translation units. This has worked well... |
I get an error when linking.
Why?
Because you violate the One Definition Rule by defining the variable multiple times.
and others do not?
Why?
¯\_(ツ)_/¯ Language implementations are not required to diagnose ODR violations.
I use the named lambda like I would use a template function, therefore I need to write my na... |
62,150,080 | 62,152,870 | How compiler (Visual C++) optimize accessing vector elements by index? | I am trying to build tree where each node can have infinite children, and propagate some values from root down the tree. I tried multiple ways to achieve that.
First was by allocation of each individual node on heap. Then i tried to create vector of Nodes (not pointers to Nodes ) and build tree with Node pointers point... | You'we been told in the comments that comparing the performance of the debug builds is not really useful. That statement is correct, and the issue here is not that release builds do something magical to access your vectors, but that debug builds are slowed down by a lot of verification and instrumentation code that doe... |
62,150,130 | 62,150,343 | Algorithm of checking if the number is prime | Hello everyone!
I came to this algorithm on how to check if number is prime and probably it's fine for me but I want to find out if it can be improved
bool isPrime(int num)
{
bool isPrime = 1;
if (num <= 0)
{
return 0;
}
if (num == 1)
{
return 0;
}
for (int i = 2; i <= sq... | The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient met... |
62,151,257 | 62,151,496 | How to display maximum element of vector<myStruct>? | I have a source code which contains as follows:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct st
{
int id;
double d;
};
bool comp(int a, int b)
{
return (a < b);
}
bool comp2(st &a, st& b) { return a.d < b.d; }
int main()
{
vector<int> v = { 9, 4, 7,... | You did not define the operator << for objects of the type struct st. So the compiler issues an error for this statement
cout << "Max element of vec: " << *max2;
Instead you could write for example
cout << "Max element of vec: " << max2->id << ", " << max2->d << '\n';
Or you cold define the operator << for objects of... |
62,151,602 | 62,151,750 | Read and write complex numbers from a file in C++ (translation from C)? | I have a big problem. I get a task in which I should write a program in C++, which I previously write in C. This program in C++ must read complex numbers from a file and write them. I must create a class and real and imaginary parts must be private. I also must create operators << and >>. I don't know what I should do.... | read.h:18:17: error: invalid use of non-static data member ‘Complex_num::real’
cout << real << '.' << imag << ',' << ' ';
Your friend operator functions are not member functions, so they dont have access to member variables. You should make use of their parameters:
friend std::ostream& operator<<(std::ostream... |
62,151,764 | 62,151,909 | Adding two numbers through recursion C++ | #include <iostream>
int sum(int a, int b) {
if (b != 1) {
sum(a, b - 1);
}
a = a + 1;
return a;
}
int main() {
int a = sum(10, 12);
std::cout << a;
}
Basically I am adding two numbers through recursion, so I am recursively calling function by decreasing number b and incrementing number a th... | Let me rewrite your code just a bit to make the mistake more obvious:
int partial_result(int a,int b) { /*....*/ }
int sum(int a, int b) {
if(b != 1){
partial_result(a, b-1);
}
a = a+1;
return a;
}
Calling the partial_result has no influence on what sum returns and sum is the same as
int sum... |
62,151,805 | 62,152,976 | Can someone help me with this problem of finding indices of the pairs of elements of an array that sum to k? | #include <vector>
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> nMap;
int a[] = {3,4,5,6,5,7,4};
int k = 10;
for(int i = 0; i < 7; i++) {
int rem = k - a[i];
if(nMap.find(rem) != nMap.end()){
printf("(%d,%d)\n",nMap[rem], i);
... | The input 1,1,1,1,1,1,1 produces 6+5+4+3+2+1 = 21 = N * (N-1) / 2 = N²/2 - N/2 outputs:
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
(2, 3)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
(4, 5)
(4, 6)
(5, 6)
You need an algorithm with complexity O(N²) to produce such output. Your code doesn't... |
62,151,954 | 62,152,030 | Template pointer to a member function - getter | So i'm making a sorting function and i want it to sort my elements depending on the getter i give it.
The problem is my getter is const and thats why my current code doesn't work. If i remove const it works just fine.
struct User {
string name;
string getX() const { return name; } //// doesnt work with this
... | Just make the parameter const as well:
template <typename ElemType, typename MemberType>
void _sort(std::vector<ElemType>& vec, MemberType(ElemType::* member)() const, bool ascending = true)
________________________________________________________________________^^^^^
Or don't make the parameter that specific:
templat... |
62,152,528 | 62,152,768 | namespace altering the function definition | I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform:
#include <stdio.h> /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrent... | Your fUtils::getcwd() function is attempting to call itself when the GetCurrentDir macro is evaluated (to getcwd), and this results in a function that expects no argument but is being given two arguments.
To resolve this, add the global namespace operator (::) in the definitions for GetCurrentDir, as follows:
#ifdef WI... |
62,153,301 | 62,153,512 | Does dividing float by int always give float? C++ | I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double.
I... | From the C++20 standard draft [expr.arith.conv]:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, ... |
62,153,969 | 62,154,517 | How to comprehend that the type of `std::function` depends solely on its call signature? | As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:
Class that can wrap any kind of callable element (such as functions
and function objects) into a copyable object, and whose type depends
solely on its call signature (and not on the callable element type
itself).
... | The template type effectively denotes a function signature (excluding name of course).
std::function<bool(Bar const&, Foo const&)>
Can hold a functor, member function pointer, function pointer or lambda. But the callable must have the bool (Bar const&, Foo const&) signature.
class Foo {};
class Bar {};
class FunctorE... |
62,154,053 | 62,154,132 | How to prevent mutation of private structures returned by reference | I have following code:
struct MyStruct {
int a;
int b;
};
class Foo {
public:
MyStruct const &getValue() {
return value;
}
private:
MyStruct value{10, 20};
};
int main() {
Foo foo{};
auto v = foo.getValue();
v.a = 42; // compiles! it shouldn't!
}
I want to return a reference ... |
Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to.
That's wrong. References can't ever be reassigned anyway. This is the correct way to return a reference to an immutable object. However you actually copy the re... |
62,154,056 | 62,154,111 | What does ( [ ]( ){ output;}); mean? | Currently using the ESP8266ServerSecure.h library , HelloServerBearSSL example.
What does this mean? Is the output server.send being initialize as an array? I'm really confused.
server.on("/inline", [](){ server.send(200, "text/plain" , "this works as well"); } );
| This is a lambda: https://en.cppreference.com/w/cpp/language/lambda
Equivalent of:
struct Callback
{
void operator()() {
server.send(200, "text/plain" , "this works as well");
}
};
server.on("/inline", Callback{});
|
62,154,178 | 62,154,766 | Why doesn't C++20 use `requires` to restrict the T for atomic<T>? | A generic std::atomic<T> is required to have a T that is Copy Constructible and Copy Assignable:
[atomics.types.generic]/1
The program is ill-formed if any of
(1.1) is_trivially_copyable_v<T>,
(1.2) is_copy_constructible_v<T>,
(1.3) is_move_constructible_v<T>,
(1.4) is_copy_assignable_v<T>,
or (1.5) is_m... | The library specification deliberately avoids using any particular technology to achieve its goals P0788:
IV. Let’s avoid any specification that demands any particular technology by which implementations must comply with Library specifications.
a) Let’s permit an implementation to use a requires-clause, an enable_if, ... |
62,154,280 | 62,158,456 | C++: storing a matrix in a 1D array | I am very new to C++, but I have the task of translating a section of C++ code into python.
Going through the file, I found this section of code, which confuses me:
int n_a=(e.g 10)
int n_b=n_a-1;
int l_b[2*n_b];
int l_c[3*n_b];
int l_d[4*n_b];
for (int i=0; i<n_b; i++){
for (int j=0; j<2; j++) l_b[i*2+j]=0;
... | A common way to store a matrix with R rows and C columns is to store all elements in a vector of size R * C. Then when you need element (i, j) you just index the vector with i*C + j. This is not the only way your "matrix" could be stored in memory, but it is a common one.
In this code there are 3 C arrays that declared... |
62,154,300 | 62,188,526 | Dynamic switching of implementation in hardware abstraction layer (HAL) | I'm trying to implement a hardware abstraction layer (HAL) to access several similar devices using all the same interface.
The question is, how should I implement the dynamic switching of the implementation for one device class vs. another.
The following code shows how I do that actually.
However, I am not sure if this... | Seems like overengineering. Simply implement your abstract device and pass a proper instance to Work. At least in your example, there is simply no need for the ImplementationDispatcher.
|
62,154,830 | 62,154,991 | delete without a head pointer | Question:
You are given a certain node somewhere in the middle of the linked list and you need to delete that node.
You are not given the head node to the linked list.
Condition: the given node has atleast one node next to it.
The structure of the node:
struct Node {
int data;
struct Node *next;
Node(int x) {
... | The struct Node has a default copy assignment since neither it nor a move assignment is declared.
So *node = *(node->next); copies both attributes (data and next) from *(node->next) to *node making it exactly the same as:
(*node).data = (*(node->next)).data
(*node).next = (*(node->next)).next
|
62,155,040 | 62,155,125 | Manually implement structured binding in C++14 | Would it be possible to implement C++17 structured bindings using C++14?
I am targetting a simple proof of concept with the following syntax:
int a,b;
(a,b)=std::tuple<int,int>(4,2);
The way I imagined it is :
template <typename T, typename U>
operator=(operator()(T a, U b), std::tuple<T,U>(x,y))
So the = receives a ... | Sure. This even already exists in the standard library as std::tie():
std::tie(a, b) = std::make_tuple(4, 2);
Note that this only works for tuples on the right-hand side. You could fairly straightforwardly extend this to work for raw arrays. But getting it to work for aggregates is much harder - without extra language... |
62,155,041 | 62,155,134 | why is the address the same? |
why is the address of temp (in the while loop in main) the same everytime the loop runs
i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist... |
why is the address of temp (in the while loop in main) the same everytime the loop runs
Because object you get address of has automatic storage duration. It means that object lifetime ends at the end of block it was created (end of loop in your case) and you have dangling pointer after that. As that memory considered... |
62,155,276 | 62,155,470 | Using static functions of different class in worker class for experimenting | I have two classes which are inheriting from some virtual base class
class A : public BaseClass {
public:
static int foo(){ ... };
static void bar(){ ... };
};
class B : BaseClass {
public:
static int foo(){ ... };
static void bar(){ ... };
};
I have another class Worker that is ... | You could make a class template like this:
template <typename T>
class Worker_T {
public:
static void doFoo(){
int result = T::foo();
}
static void doBar(){
T::bar();
}
};
and then to choose which class to actually use, you only have to choose one of the following... |
62,156,260 | 62,158,731 | Valgrind reports memory leak on QThread::start() | The issue is on VMware, somehow 3D acceleration causes memory leak and SIGSEGV, resulting in program crashing.
=============================
I have a problem with following codes:
gc = new GameController(scene);
subthread = new QThread(this);
gc->moveToThread(subthread);
subthread->start();
This should... | You're using the GTK+ style in your Qt application. That's clearly visible in the call stack from the crash: all those symbols that contain gtk in them are the GTK+ Qt style. This is bad news in most cases as far as profiling or memory leak testing is concerned.
Start your program like myprogram -style Fusion - that wa... |
62,156,521 | 62,156,598 | Is a good practice to used shifted unsigned numbers as an index number of array | Defining the enum as flags in the following way
typedef enum
{
NOT_PID = 0,
PID1 = (1U << 0),
PID2 = (1U << 1),
NUM_PID = 3
} pid_t;
float m_derivative[pid_t::NUM_PID];
and using it as follows:
m_derivative[pid_t::PID1] = 4.0
m_derivative[pid_t::PID2] = 3.0
Is... | What happens if you go one further?
typedef enum
{
NOT_PID = 0,
PID1 = (1U << 0),
PID2 = (1U << 1),
PID3 = (1U << 2),
NUM_PID = 4
} pid_t;
float m_derivative[pid_t::NUM_PID];
m_derivative[pid_t::PID3] = 4.0; // out of bounds
Here, PID3 = 4 which is not less than NUM_PID. This causes an out of boun... |
62,156,957 | 62,157,370 | Visual Studio C++ Project and Referenced Project's References | I'm trying to setup a C++ solution that has multiple projects, for simplicity I'll call them ProjectA and ProjectB.
ProjectB is setup as a Static Library and uses an external library, I'll call it ExternalLib, that's been added to the Additional Includes in the properties of ProjectB. ProjectA has ProjectB added as a ... | Check your ProjectB header files, if header files included by ProjectA reference anything from ExternalLib then ProjectA will need to be told about ExternalLib. Usually I find the problem is that ProjectB is only supposed to use ExternalLib internally but that some part of ExternalLib has snuck into the public face of ... |
62,156,981 | 62,157,185 | (Why) can we assign non-static class members to static variables in initialization? | In a larger code base I have encountered code like this (see on godbolt):
struct Foo {};
struct Base {
Foo* a;
};
struct Bar : public Base {
static Foo* Bar::*mybar[];
};
Foo* Bar::Bar::*mybar[] = {
&Base::a
};
To be honest, I'm baffled. This looks like it's initializing a static array of Foo pointers i... | To start with, Bar::mybar is an array of pointers to members. Those aren't actual pointers. They are more like an abstraction over an offset into the object. They allow accessing members indirectly. Given a Base object (or one derived from it), we can invoke them, as follows
aBar.*mybar[0] // This resolve to a Foo* ins... |
62,157,361 | 62,163,494 | Relative performance of std::atomic and std::mutex | I am considering options for implementation of a queue for a project, a requirement of which is that the producer, at least, must be as low latency as possibe. To this end, I have been investigating "lock free" queues using std::atomic to control access to the data structure by the producer and consumer threads. It wa... | What hardware are you testing on?
Since you're using GCC, the std::atomic seq_cst store will be using a mov + slow mfence instead of a somewhat less slow xchg-with-mem (which is also a full barrier, like all other x86 atomic RMW operations).
Taking a mutex costs an atomic RMW (like xchg, not mov + mfence). And if you'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.