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 |
|---|---|---|---|---|
63,820,176 | 63,820,475 | Non verbose solution to make a class member variable optional based on the type of template? | I want the class member variable only_if_int to be defined only if the class is instantiated with the template type int. I have a working solution, but it is too verbose.
#include <iostream>
#include <type_traits>
template<typename T, typename Enable = void>
class MyClass;
template<typename T>
class MyClass<T, std::e... | One approach would be to have a type that contains an int member only if it's instantiated with int, like this:
template<typename>
struct OnlyInt {};
template<>
struct OnlyInt<int> {
int only_if_int;
};
Then MyClass can just inherit from this type:
template<typename T>
class MyClass : public OnlyInt<T> {
publ... |
63,820,547 | 63,820,722 | std::array initialization, for objects without a default ctor? | I work on a memory constrained system where new/malloc calls are wrapped to fail at build time. So std::vector is not an acceptable solution, unfortunately.
I have an std::array member of a class where the size is known at compile time, but may vary between particular targets (e.g. from a config file) so I have access ... | Option 1: Use a named constructor idiom
We'll write a named constructor idiom, array_repeat(), which takes a single value and produces - at compile-time - an array with all values set to it. You can then write:
class Foo {
public:
Foo() : fooArr {array_repeat<arr_size>(Bar(ctor_arg))} {}
private:
std::array<Bar, ar... |
63,820,715 | 63,821,306 | What do they mean by the expressions "of the same type" highlighted below in [class.derived]/7? | [class.derived]/7:
[Note: A base class subobject might have a layout ([basic.stc])
different from the layout of a most derived object of the same
type. A base class subobject might have a polymorphic behavior
([class.cdtor]) different from the polymorphic behavior of a most
derived object of the same type. A base clas... | struct B { /* ... */ };
struct D : B { /* ... */ };
B b;
D d;
The base class subobject B of d may have different layout than the most derived object (b here) of the same type (B). For example, an implementation may reuse the tail padding of B for D's members.
|
63,821,182 | 63,837,017 | ISO C++ forbids declaration of 'int32' with no type | Trying to build an AOSP version and got this error
error: ISO C++ forbids declaration of 'int32' with no type
error: typedef 'int32' is initialized (use decltype instead)
error: 'loc_event_cb_f_type' was not declared in this scope
this is the declaration that throws the error
typedef int32 (loc_event_cb_f_type)(
... | The problem was that int32 was not defined or included anywhere
as @luserdroog wrote,
Should it be int32_t?
int32_t and other intX_t typedefs are defined in /usr/include/stdint.h, so it can be solved by replacing all int32 by int32_t or, as @JonathanLeffler proposed, defining the int32 type, which is more convenient ... |
63,821,798 | 63,822,035 | An issue about converting a pointer to char to another type pointer | #include <iostream>
struct Test{
int a;
int b;
};
int main(){
char* buffer = (char*)malloc(sizeof(char)*32); //#a
char* ptr = buffer + 4; //#b
new(ptr) Test; //#c
char* ptr2 = buffer + 4; //#d
Test* tptr = reinterpret_cast<Test*>(ptr2); //#e
tptr->a = 1; // #f
}
Consider the above code, at the p... |
Does the code at #f have undefined behaviour due to tptr does not point to an object of type Test?
The program has undefined behavior since #a, because malloc is defined as triggering implicit object creation and returning a pointer to a suitable created object, but the set of objects which would give the rest of the... |
63,821,897 | 63,821,955 | Why is my array of pointers displaying "Index is out of valid index range"? | I am working on a school project and I am trying to add each student object "objStudent[5]" to an array of pointers "classRosterArray". When I try to initialize the pointer in the constructor "Roster". I receive the warning "Index 5 is out of valid index range". This is my first time learning C++ so I'm not sure what t... | You're getting this error:
“Index is out of valid index range”
because when you create an array of 5 elements, you only have an index from 0 to 4.
The largest valid index to access your specific array is 4.
If you change this line:
classRosterArray[5] = nullptr;
to:
classRosterArray[4] = nullptr;
should fix it.
|
63,821,958 | 63,822,230 | Why does this code throw a read access violation? | I need help figuring out why this code is a throwing a read access violation
The Code throws a read-access violation at the 4th value of the array, this started happening when I added the dynamic memory allocation in lines 7 & 8
ProceduralStories.cpp
#include <iostream>
#include "ProceduralStories.h"
void main()
{
... | Please don't do this.
Take the time, learn to write a RAII class.
If you write new you must call delete or you'll leak memory in larger projects.
A destructor does this for you when the object falls out of scope. But in this case, you call the default destructor which only calls child destructors and pointers don't cle... |
63,821,980 | 63,823,496 | What does double ampersand do in bpf filter? | I'm reading bpf(berkeley packet filter) core part in linux kernel, and I'm a little bit confused in the following.
This is the part of the code:
static unsigned int ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn,
u64 *stack)
{
u64 tmp;
static const void *jumptable[256] = {
[0... | Even if this were C++, &&ALU_ADD_X and so on are expressions, not types, so the && couldn't indicate an rvalue reference.
If you scroll down a bit, you will find that all the ALU_* things, and default_label, are labels.
You will also find a goto *jumptable[op];, where op is a number.
GCC has an extension where you can ... |
63,822,001 | 63,827,371 | C++ overriding default less than argument for std::set for a particular data type | I have lots of code which creates a std::set<Port*>. Now by default this uses less<Port*> which sorts the set on pointer values. This creates problem in our tool. I want to provide a default comparator my_less for all set<Port*> without having to go and change all the code. So I tried template specialization :
namespac... | Since C++11, you can inherit constructors easily with the using-declaration, like this:
namespace std {
template<> class set<Port*> : public set<Port*, my_less> {
public: using set<Port*, my_less>::set;
};
};
|
63,822,209 | 63,877,843 | Gstreamer appsink playlist failed : Too many files | I'm new to Gstreamer and I'm trying to make a playlist feature using Gstreamer on specified GLES window, these are my Pipeline elements:
gstPipeline = gst_pipeline_new ("_pipeline");
data.source = gst_element_factory_make ("filesrc" , "_source");
data.decoder = gst_element_factory_make ("decodebin" , "_dec... | I found a solution myself.
in my appsink, the information transforms like this :
GstSample -> GstBuffer -> GstIonBufFdMeta -> EGLImageKHR
the EGLImageKHR is not deleted after usage, so meta.fd(file descriptor) is continuously increasing.
I use eglDestroyImageKHR in EOS to manage ImageKHR and solved my problem.
There is... |
63,823,492 | 63,823,567 | how can I make branchless number cycle? | I need a branchless number cycle code.
like this:
int i = 0;
i = (i + 1) % 4 //1
i = (i + 1) % 4 //2
i = (i + 1) % 4 //3
i = (i + 1) % 4 //0
i = (i + 1) % 4 //1
...
But it should work in the reverse order of the code above. (3 > 2 > 1 > 0 > 3 > ...)
I first tried "i = (i - 1) % 4".
But this worked differently ... | The error happens because in C89 the remainder of negative numbers was underspecified and from C99, negative % positive will result in a negative number which is unlike in some programming languages such as Python, where (-1) % 4 would indeed result in 3.
But it is easy to circumvent. When you subtract 1, it is the sam... |
63,823,503 | 63,823,935 | QGridLayout Widgets Set Equal Size | .h file:
QChartView *chrtViewArr[5];
QGridLayout *graphLayout;
QFrame *graphFrame;
.cpp file:
{
...
this->graphLayout = new QGridLayout(this->graphFrame);
for(int i=0;i<3;i++){
this->graphLayout->addWidget(this->chrtViewArr[i],i,0);
}
this->graphFrame->setLayout(this->graphLayout);
for(int i=0;i<machine... | You could set the chart widgets' sizePolicy to ignore the sizeHint
|
63,823,544 | 63,824,018 | Default-construct all the types in a std::variant and put them in a std::vector | How would I make a std::vector that contains a default-constructed instance of all the types contained in a std::variant?
using TaskVariant = std::variant<TypeA, TypeB, TypeC>;
std::vector<TaskVariant> variants;
// I'd like to do this in a loop
variants.push_back(TypeA());
variants.push_back(TypeB());
variants.push_ba... | 1.Solution: You can convert variant to tuple and then use C++17 std::apply:
#include <variant>
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
using namespace std;
template <typename... Types>
struct ToTuple;
template <typename... Types>
struct ToTuple<variant<Types...>>
{
using type = t... |
63,824,190 | 63,824,923 | What is the best way to empty an object? | Say I have the following code(this is just an example, obviously not practical):
std::list <Object> objects;
Object cur_object;
for(int i = 0; i < 11; i++){
switch(i){
case 0:
cur_object.foo = true;
break;
case 5:
case 10:
objects.push_back(cur_object);
... | You could circumvent that completely by simply keeping that extra object at the end of the list:
std::list<Object> objects;
objects.emplace_back(); // temporary object is at the end of objects
for(int i = 0; i < 11; i++){
switch(i){
case 0:
objects.back().foo = true;
break;
... |
63,824,854 | 63,825,111 | Return optional from class method | I have a optional member in a class, which I want to return by value, via a method.
Sample code:
#include <stdio.h>
#include <optional>
#include <iostream>
using namespace std;
class bar {
public:
int a;
bar(const bar &obj) {
a = obj.a;
}
};
class foo {
public:
void init(){
abc->a = 1... | You need to use the constructor of optional to ensure that it contains an object: (assuming that the redundant copy constructor of bar, which blocks it from being constructed, is removed)
foo()
: abc{bar{100}}
{
}
or, after the optional has been created:
void init(){
abc = bar{100};
}
Otherwise, the optional ... |
63,825,243 | 63,825,300 | Why do I get the letter 'e' instead of the value I gave it? | I have this piece of code, and I want if someone is older than 30 (general) that person needs to be spoken to with good language for old people and otherwise normal language, but if I run this the piece of older than 30 works I get "u" but otherwise I get te letter "e" instead of "je", does someone know what is wrong?
... | 'je' is a multicharacter literal with an implementation-defined value: 'e' + 28 * 'j' is common. It is an int type. Importantly it's not syntactically invalid, although some compilers can warn you of their use.
You are most likely overflowing the char to which this is being assigned, with undefined or implementation d... |
63,825,642 | 63,826,547 | Can't call class function from a template function class inside a template class | I am trying to create a pattern where an abstract class has several methods where all get the same member. The derived implementation is on a specific member type and the pattern should redundant the need to downcast the types.
The following is not working:
Assume these type classes
//--------------
// Data classes
//-... | Note :
main should return an int, not void
if (&specificVal != nullptr) will be always true, reference cannot be null.
I am not sur why you got this error message, with gcc I got :
no matching member function for call to 'fRunner'
Because pf type was bool (ExampleSpecific1<TypeB>::*)(TypeB &) which didn't match with... |
63,825,858 | 63,902,820 | Recording using sox in c/c++ | I am trying to record sound using microphone and sox library in C/C++.
sox_open_read("default", &_input->signal, NULL, NULL)
I am trying to use default input device. I am getting the error
formats: can't open input file `default': No such file or directory
Which I guess is caused because I did not pass the last argum... | As the last parameter to sox_open_read function for microphone input, one of the audio devices drivers should be passed. In my case, it is 'alsa'.
Example:
#include <sox.h>
#include <memory>
sox_signalinfo_t _intermediateSignal;
sox_format_t* input;
sox_format_t* output;
sox_effects_chain_t* effectsChain;
void addEff... |
63,825,959 | 63,826,171 | How to elegantly avoid code duplication, when class T and T_ref only differ in the constructors & destructors? | class HugeTpool{ // Owner of *_dataPool memory
int x;
int y;
// ... etc; // Data Members (many)
size_t* _dataPool; // pointer to huge contiguous data
T_ref operator[](int i){ // used to emulate vector<T> like behaviour
/* Implementation details*/
return T_ref_Obj;
... | It may be that you should be using T & not T_ref, or if you need it to be a regular type, std::reference_wrapper<T>.
If that isn't the case, write a borrow_ptr template, very similar to unique_ptr except that it also tracks if it doesn't own it's element. Then use borrow_ptr<size_t> data; in T, and discard T_ref.
As a ... |
63,826,319 | 63,827,095 | c++ multiple copy assignment operators | I'm studying C++ and I have a question regarding assignment operators.
Based on what is written here https://en.cppreference.com/w/cpp/language/copy_assignment, it seems that
...a class can have multiple copy assignment operators, e.g. both T&
T::operator=(const T &) and T& T::operator=(T).
I tried to make a class wi... | The documentation you cite derives its statement from the C++ standard's [class.copy] (C++14) / [class.copy.assign] (C++17) section:
15.8.2 Copy/move assignment operator
A user-declared copy assignment operator X::operator= is a non-static
non-template member function of class X with exactly one parameter of
type X,... |
63,826,765 | 63,827,203 | Is it possible to define type cast operator for non-structural (esp. numeric) types? | For struct or class I'm able to define own type conversion operator as a member:
FOO operator FOO(BAR b);
Is there any way to do it for non-structural types, for example something like this:
int operator int(float x);
?
| From the CPP Official Reference document, operator overlaoding (cast operator as well) is defined as below:
Enables implicit conversion or explicit conversion from a class type to another type.
Which means, the answer is NO.
If you think about it, that seems a valid rule. There wont be a reason to redefine int + int ... |
63,827,605 | 63,830,221 | Why QProgressDialog is shown without an explicit call to `exec()` or `show()`? | I have the following code
#include "dialog.h"
#include <QApplication>
#include <QProgressDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QProgressDialog w;
//w.show();
return a.exec();
}
The execution of this code shows a QProgressDialog UI.
I would like to have the explanatio... | Both constructors of QProgressDialog call QProgressDialogPrivate::init, where forceTimer : QTimer is started:
...
forceTimer = new QTimer(q);
QObject::connect(forceTimer, SIGNAL(timeout()), q, SLOT(forceShow()));
...
forceTimer->start(showTime);
The forceShow() slot in turn looks like this:
void QProgressDialog::... |
63,827,620 | 63,827,827 | how can i access a vector of pointers pointing to other vectors? I tried the hackerrank program variable sized arrays in c++: |
Consider an n-element array a, , where each index i in the array
contains a reference to an array of k(i) integers (where the value of
k(i) varies from array to array).
Given a , you must answer q queries. Each query is in the format i j,
where denotes an index in array a and j denotes an index in the array
located ... | The chief problem here is that each member of a should point to a different array. That's at least what the exercise suggests. You make all elements of a point to the same vec vector.
There's also the slight matter that vec.data() keeps changing as it grows, but that's probably solved when you fix that first problem.
N... |
63,829,226 | 63,839,487 | Hierarchical listing of a folder tree using Windows API | I use this code to list recursively a folder and its subfolders in C++, the code works fine, I modified it from many Stackoverflow questions asking about recursive folder listing.
#include <iostream>
#include <string>
#include <windows.h>
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
#end... | As @Shubham said, you need to use a queue to complete the function you want.
When traversing a folder, if a folder is encountered, push it into the queue, and then pop the folder from the queue after traversing it, thereby achieving a breadth traversal of the folder.
Here is the sample:
#include <Windows.h>
#include <i... |
63,829,231 | 63,829,313 | What does vector.back().back() return? | Suppose I have vector<string> v
What does v.back().back() return?
Does it return the last string of the last string of the vector?
It is same as v.end().end() ?
| v.back().back() is equivalent to ( v.back() ).back().
for a nonempty vector v, v.back() is the last element of v: http://www.cplusplus.com/reference/vector/vector/back/
for a nonempty string s, s.back() is the last character of s: http://www.cplusplus.com/reference/string/string/back/
If v is vector of strings, the... |
63,829,314 | 63,829,403 | Forwarding reference for return type | Is there a difference between those those two
struct S;
int& foo(S&);
auto&& bar1(S& s) {
return foo(s);
}
decltype(auto) bar2(S& s) {
return foo(s);
}
for the compiler? I've been always using decltype(auto) in cases like this but is seems auto&& does the trick. Is it a coincidence or are both the identical?... | For your particular case it results in the same: The deduced return type of both bar1() and bar2() is int&.
However, note that auto&& always results in a reference, i.e., bar1() is always going to return by reference regardless of whether foo() returns by value or by reference. On the other hand, declaring bar2() retur... |
63,829,411 | 63,829,549 | CMake - How to add lpthread to command line | Here is my CMakeLists.txt:
if(WIN32)
if(MSVC)
list(APPEND PRIVATE_SOURCES AuthServer.rc)
endif()
endif()
add_executable(AuthServer
AuthServer.cpp
${PRIVATE_SOURCES}
../Database/Implementation/LoginDatabase.cpp
../Database/Implementation/LoginDatabase.h
../Databas... | Maybe something like :
target_link_libraries(
AuthServer
pthread
)
?
|
63,829,690 | 63,829,981 | call operator argument evaluation order | #include <string>
struct X
{
char y;
std::string z;
X & operator()(std::string && s)
{
z = std::move(s);
return *this;
}
X & operator()(char c)
{
y = c;
return *this;
}
};
int main()
{
X x;
std::string y("abc");
x(y[0])(std::move(y));
}
i... | Before c++17, chaining function calls that modify the same l-value, like in your example, is indeed undefined behavior, since the order of evaluation of these expressions is unspecified.
However, a proposal to fix that was merged into c++17.
Here's the relevant rule (emphasis mine), which also contains an example from ... |
63,829,777 | 63,854,994 | How to do Operator overloading with move semantics in c++? (Elegantly) | class T {
size_t *pData; // Memory allocated in the constructor
friend T operator+(const T& a, const T& b);
};
T operator+(const T& a, const T& b){ // Op 1
T c; // malloc()
*c.pData = *a.pData + *b.pData;
return c;
}
T do_something(){
/* Im... | This is performant and elegant but makes use of a macro.
#include <type_traits>
#include <iostream>
#define OPERATOR_Fn(Op) \
template<typename T1, typename T2> \
friend auto operator Op (T1&& a, T2&& b) \
-> typename std::enable_if<std::is_same<std::decay_t<T1>,std::decay_t<T2>>:... |
63,829,918 | 63,830,296 | using std::find to find elements in vector of std::pair | Is there a way to use std::find within a std::vector of std::pair?
I want to go over the pairs' first members and search for the given value in the first members of the pairs only.
Of course, I can do it explicitly with a for loop, but can I do it in a more elegant way?
(I'm using c++14 if that matters)
| Here's an example using std::find_if
include <iostream>
#include <vector>
#include <utility>
int main()
{
std::vector<std::pair<char, char>> v {
std::make_pair('a', 'A'),
std::make_pair('b', 'B'),
std::make_pair('c', 'C')
};
auto it = std::find_if(
v.begin(),
... |
63,831,450 | 63,831,514 | Why doesn't address change in forked process? | I'm trying to understand fork() and process address spaces. I wrote a basic proof of concept program that forks a new process and changes a variable in the new process. My expectation was that when I change a variable in the child, this should cause that variable to get a new address. If I understand correctly, Linu... |
My expectation was that when I change a variable in the child, this should cause that variable to get a new address.
No, because they are virtual addresses.
If I understand correctly, Linux does copy-on-write with fork. So I would expect the variable address in the parent and child to match until I change it in one ... |
63,831,498 | 63,840,241 | Disabling \ enabling an audio device with WinApi | Story first: ( Skip if not interested )
I've encountered a very annoying daily task where every time I play a game, I need to switch between my speakers and my headphones. This involves in getting to the Control Panel ( Because for some reason Windows 10 removed the option to right click the audio icon in the taskbar a... | There may be no programming method to achieve this requirement.
As @Larry Osterman said that,
There is no public API which allows you to change the default audio
device, that is functionality that is considered to be under the users
control. This has always been the case in Windows.
Having said that, if you search the... |
63,831,523 | 63,831,677 | Directly create a node handle | As I get it, C++17's node handles allow you to splice items inside and outside of some containers without actually moving the key and value objects. This is great, for example, if you need to keep some references to them in some other part of the program. In line of principle you can also keep a node handle outside of ... | The short answer to your question is - no, you have to use extract. Though there is problem with your idea how node handle works. You mistakenly think that reference to the value would remain valid after inserting the node into the new container - IT WILL NOT. Take look here:
Pointers and references to an element that... |
63,831,545 | 63,831,645 | Scanf does not read leading 0s if digit after leading 0s are 8 or 9 | I have a very strange question which stems from a bug of a C++11 program I have been writing.
See the following code:
long long a[1000];
int main(int argc, char * argv[]) {
for(long long i = 0; i < 300; ++i) {
scanf("%lli", &a[i]);
std::cout << a[i] << std::endl;
}
return 0;
}
Try... | Use %lld instead of %lli.
The reason %i doesn't work is because 0 is interpreted as a prefix for octal numbers, and the digits 8 and 9 don't exist in octal:
d Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i Matches an optionally signed integer; the next pointer m... |
63,832,286 | 63,832,368 | Assign address of number to a pointer | int *n=(int *)5;//Valid
cout<<*n;//Invalid
Why pointer n can point to an address although 5 is not a memory location.
Why I can not print out the screen the value of n.
| You are attempting to dereference memory address 0x5, which is probably restricted memory.
int *n=(int *)5;
You are casting the integer literal 5 as an int*. What that means is you are saying 0x5 is an address. When attempting to dereference that pointer with *n, you will get an error.
Instead, you would need to do so... |
63,832,442 | 63,832,478 | How to properly operate with wstrings? | I am learning about wstrings because I want to understand UTF-8 for a project. I made a simple program to test operations using wstrings:
int main()
{
std::wstring test;
std::wstring test2;
std::wstring test3;
int n;
getline(std::wcin, test);
std::wcout << "\n" << test;
for (n = 0; n < test.size... | Your test2 string is empty, so when you do:
test2[n] = test[n];
you are indexing at an invalid location, which invokes undefined behavior. This could result in an exception being thrown.
Instead, you can do:
test2.push_back(test[n]);
You have the same issue with test3, which you can fix the same way.
Alternatively, ... |
63,832,846 | 63,832,915 | If there is no else-if, how come we can do multiple else-if and not multiple else? | In the following video (19:46) Cherno says "else if(x<y){}" is equal to "else {if(x<y){}}", or that and else if statment is not a keyword but just a combination of one-line else statment and an if statment.
https://www.youtube.com/watch?v=qEgCT87KOfc
Now if that is true, i should not be able to write more than one else... | The if of the else if can also have an else.
Then that else can also have an if, and that if can have an else, and the chain can continue indefinitely.
The structure can also be visualized this way:
if (test0)
true0statement;
else
if (test1)
true1statement;
else
if (test2)
true2s... |
63,833,243 | 63,834,232 | Can I use proto2 generated code stubs with libprotobuf3.x? | I have a legacy application using proto2 with libprotobuf2.x. There is another application application that I would like this application to talk to with proto3.
I checked on possible solutions and the discussion in this thread
says that libprotobuf3.x provides compatibility with proto2.
Does this mean that I can use t... | No, you can't link .pb.* files generated with protoc 2.0 against libprotobuf 3.0.
Just like with any shared library, an increment in the major version number means a breaking API change.
Compatibility with proto2 means that Proto 2 syntax is supported (syntax = "proto2"). Also proto3 is binary-compatible with proto2 on... |
63,834,285 | 63,838,165 | Buttons in vector not responding to custom drawing | I have a Win32 program in which I have a vector which contains the HWND of some buttons which I want to custom draw. I can owner-draw them, but all I want to do is change the background color, so it seems unnecessary to do so. However, they don't seem to change as a result of being custom drawn. They look the same.
I c... | I needed to add the following line:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version = '6.0.0.0' processorArchitecture = '*' publicKeyToken = '6595b64144ccf1df' language = '*'\"")
This makes sure that ComCtrl32.dll version 6 is being used, allowing the custom-... |
63,834,530 | 63,834,704 | Is there any benefit of storing lambda function into std::function? | From https://en.cppreference.com/w/cpp/utility/functional/function
void print_num(int i)
{
std::cout << i << '\n';
}
int main()
{
// store a free function
std::function<void(int)> f_display = print_num;
f_display(-9);
// store a lambda
std::function<void()> f_display_42 = []() { print_num(42)... | The advantage is that you don't need to know what is the type of the callable in order to store it. For instance, how do you declare an std::vector of things that can be called as a function? With std::function is easy:
std::vector<std::function<void()>> handler_list;
You can easily store in handler_list lambdas, expl... |
63,835,364 | 63,835,396 | virtual method of header give errors during g++ compilation | I'm initiating to C++ and I'm struggling with a compiling problem
I have a source file "binomial.cpp" in which I define the methods of my classes :
#include "binomial.hpp"
using namespace std;
int Bernoulli::operator()(){
return (rand() < p*RAND_MAX) ? a : b;
};
int Binomial::operator()(){
int re... | You should replace both
int operator()(){};
with
int operator()();
in the header files. You meant to provide declarations, not definitions. To provide just a declaration (not provide the code right away), just drop the {}.
|
63,836,615 | 63,836,975 | How to turn an int into a string? | I've been trying to find how to do it online. I'm restricted from not using ready-made functions, like to_string or boost::lexical_cast, not even the <sstream> library. How can I do it with these limitations?
| You can use '0' + i to get the char value of 0 and offset it. I.e.
#include <cmath>
#include <string>
#include <iostream>
int main() {
int number = 12345678;
int nrDigits = std::log10(number)+1;
std::string output(nrDigits, '0'); // just some initialization
for (int i = nrDigits - 1; i >= 0; i--) {
... |
63,836,766 | 63,838,079 | How to avoid ambiguous template instantiation? | I'm trying to define a class whose behavior varies in two ways, currently based on two different template parameters.
Originally I thought that template specialization simply augmented the primary class with functionality, and so my thought was to partially specialize the two arguments separately, in the hopes that thi... | You can use inheritance to add degrees of freedom in functionality in "layers".
enum class Weight { Skinny, Fat };
enum class Height { Short, Tall };
struct PersonBase {
const char* name = "name";
};
template<Weight W>
struct PersonWeight : PersonBase {
void SayHello();
};
template<Weight W, Height H>
struct... |
63,837,742 | 63,837,792 | Getting root type of multidimensional variadic std::array | I have nested std::array which dimension is handled by template arguments std::array<type, n, ...>.
I was wondering how to get for example in std::array<std::array<int, 2>, 2>, the type int.
in this case we could just do std::array<std::array<int, 2>, 2>::value_type::value_type, but how can I do this without having to ... | You can use a basic recursive technique:
template <typename T>
struct nested_value_type { using type = T; };
template <typename T, std::size_t N>
struct nested_value_type<std::array<T, N>>
{
using type = typename nested_value_type<T>::type;
};
Provide an alias template for convenience:
template <typename T>
using... |
63,837,927 | 63,838,608 | how to access ui structures(textboxes,labels) inside static function MouseProc, SetWindowsHookEx? | In my .h file function mouseProc is declared as static(it has to be)
.h file
static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
initially i thought i would add &ui as a parameter to this function, but i am not able to do so. it gives me error "incompatible parameter type with HOOKPROC"
so, now ... | You can't add extra parameters to mouseProc. The compiler won't accept it, it needs to match the signature that SetWindowsHookEx() is expecting. If you resort to using a type-cast to force the compiler to accept it, the OS still won't know how to populate the new parameters with values at runtime when the hook is call... |
63,838,064 | 63,838,230 | How to convert bytes from uint64_t to double? | I have binary file from which I read uint64_t val (using little-endian). Now I want to convert this uint64_t to double (not just casting, but exactly the number that would be double if I entered it from the file). So the should has the same bit representation. How I should do this?
| Simple portable way:
uint64_t u64 = read_from_file();
double d;
memcpy(&d, &u64, sizeof(d));
Most compilers will generate just a couple of instructions for this.
|
63,838,129 | 63,838,212 | Determine if string is located in text file? | I'm trying to write some code that will determine if a string (and/or char array) is present in a text file, but I'm stuck here. Any advice? I'm also pretty new to c++ so it would be nice if you guys could keep it simple for me :) thanks
Okay so the following code is edited from what I previously posted, and I'm editin... | There's no need to make a copy of tp().
You should be searching for dict with tp.find(), not cstr.
You can't know that the string is not found until you get to the end of the loop. You shouldn't print Not found on every line that doesn't match. Use a variable to record whether the string was found during the loop.
The ... |
63,838,160 | 63,838,189 | Is it correct to assign a slice_array to another slice_array? | int input[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::valarray<int> test(input, sizeof(input)/sizeof(input[0]));
const std::slice_array<int> s1 = test[std::slice(1, 3, 2)];
const std::slice_array<int> s2 = test[std::slice(0, 3, 1)];
// is it correct to do this?
s1 = s2;
std::valarray<int> temp(s1);
printf("temp[0]=%d... | Yes, you can assign one std::slice_array to another with operator=
Assigns the selected elements from sl_arr to the referred to elements of *this.
Also, there's no bug here, the result of s1 = [0, 0, 2] is correct.
In your case:
test { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
s1 ^ ^ ^
s2 ^ ^ ^
Notice that... |
63,838,411 | 63,838,436 | I'm having an issue with not converting const__gnu_cxx::__normal_iterator<long long int* , std:: vector<long long int> | I'm trying to solve a question from a Div 3 competition. I'm having troubles with line 25 and 26, it's saying
error: cannot convert ' const__gnu_cxx::__normal_iterator<long long int*, std::vector<long long int>
I'm not too sure what's wrong. The goal for this line is to store the minimum of vector a and b into a long ... | std::min returns the minimum of 2 elements, not the minimum element of a range. Assuming you don't want the minimum of 2 iterators, but the minimum element of a range, you need std::min_element and you need to dereference the result, like this:
amin = * min_element(a.begin(), a.end());
// ^
And you need to do the ... |
63,838,607 | 63,838,636 | cpp array element repeat, but with different start | I have a cpp array whose size is 5 including 3,4,2,5,1 as element.
I would like to make another array size 25, but element order like this:
3,4,2,5,1 / 4,2,5,1,3 / 2,5,1,3,4 / 5,1,3,4,2 / 1,3,4,2,5
If the array size is not big, then I can make the array manually.
But, if the array size is bigger, manual is not a good w... | Use nested loops.
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
array_b[i*5 + j] = array_a[(i + j) % 5];
}
}
The modulus operator makes it cycle around to the beginning of array_a.
|
63,838,856 | 63,877,738 | Difficulties troubleshooting this build error for a Maya plugin (v2016.5) | Trying to build this plugin from source but using Visual Studio 2017:
https://github.com/david-cattermole/mayaMatchMoveSolver/blob/master/BUILD_WINDOWS.md
I followed its directions except i have been using x64_x86 Cross Tools Command Prompt for VS 2017, but I keep getting these errors when attempting to build
preview o... | I submitted an issue in the original repo and the plugin's author has helped me resolve the issue, here are the steps i took:
re-installed VS 2012 with Update 4 (https://my.visualstudio.com/Downloads?q=visual%20studio%202012)
re-generated a solution/project for this plugin via the docs
removed C:\MinGW from the "Addit... |
63,838,948 | 63,839,192 | C - Cannot read all characters when reading a file | I am currently working on a lossless compression algorithm using the Huffman technique.
I managed to compress the desired file, and save the compressed data to a file.
However, I am unable to correctly read what is recorded in this file. Preferably, I would like to store the contents of this file in a std::string.
Here... | Here is a short example that opens the file in binary mode and reads the entire file into a std::vector<uint8_t>. (you can also use a std::array<uint8_t> if you like). You open the file, .seekg() to the end, get the number of bytes and create the vector with that number of bytes and then .read() the file into the vecto... |
63,839,466 | 63,839,677 | std::swap loses information used by Type-Based Alias Analysis? | By examining the implementation of the vector class in the GCC headers (stl_vector.h), I found the following two member functions inside the vector base implementation class (Which I renamed in the example as Data_Class to avoid long_and_weird name).
void
_M_copy_data(Data_Class const& __x) _GLIBCXX_NOEXCEPT
... | For a std::vector object, the three contained pointers will never address the same memory as the pointers in another std::vector - each manages its own contiguous memory region. This insight can be used for type-based aliasing optimisations, which continue to be possible if the individual pointers are moved around in ... |
63,839,878 | 63,841,307 | Do I Need To Store Length Info With Protobuf? | I am storing Protobufs inside of some non-volatile memory in order to save configuration information. I am using NanoPB to decode/encode them. Since I do not know how large the encoded Protobufs are, when I go to grab a serialized proto from memory and decode, I just grab the maximum number of bytes that the enocded pr... | Yes, the end of protobuf messages has to be indicated somehow, as the format is not self-delimiting.
Nanopb provides two built-in methods for this:
pb_encode_nullterminated() and pb_decode_nullterminated(), which append a 0x00 byte to the encoded data and detect it when decoding. It is a neat way to do it, but does no... |
63,840,677 | 63,841,754 | Why is there no duplicate definition error when I define a `const int` in header file? | Apologies if this has been asked before. I searched the internet and did not find an answer.
Say I have a file Common.h, and A.cpp and B.cpp include Common.h.
If I want to have a global const char * in the Common translation unit, I must make it extern in Common.h, and define it in Common.cpp. Otherwise, if I simply de... | This is one of the differences of C and C++.
In C++ a const variable is implicitly static, i.e. only visible to the current translation unit. In C it is implicitly extern so visible to the entire program (which is also the default for the other non-const declararions in both C and C++).
This explains your observation.
... |
63,840,842 | 63,840,949 | How to implement a thread safe logging? | I have implemented a Logging class here.
class Log : public std::streambuf, public std::ostream {
public:
Log(int severity, const char* func, int line) :
std::ostream(this), severity_(severity) {
(this->severity_ == ERROR) ? std::cout << RED << "ERROR " :
std::... | I worked on something like this some time ago.
My solution was to add a member mutex (m_queue_mutex in the example) to control access to a member queue that stored strings to be logged, to which strings are enqueued using a function like
void print_log(std::string& msg)
{
// Format the message here, maybe add some ... |
63,841,230 | 63,841,515 | no matching function call for variadic template function | the code is as follows
#include <iostream>
#include <functional>
using namespace std;
template<class F, class ...Args>
result_of_t<F> foo(F&& f,Args&&... args){
cout<<sizeof...(args);
f(args...);
}
int main(){
foo([](char a){ cout<<a<<'\n'; },'a');
return 0;
}
while I compile the code, it says
templ... | Because return type of foo cannot be deduced.
result_of takes full signature of functor, Args.. is missing there.
template<class F, class ...Args>
result_of_t< F(Args...) > foo(F&& f,Args&&... args){
cout<<sizeof...(args);
f(args...);
}
Demo
|
63,841,324 | 63,841,412 | C/C++: What does the comment "/*< */" stand for? | I've got a rather general question: I've recently seen many #defines in C/C++ code that were commented with "/*< ... */", for example:
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0])) /*< macro to determine the size of an array */
I personally only saw that in comments for defines and a search in Google did... | Generally, < is Doxygen's syntax for documentations that come after the item that they document.
An example from the "Putting documentation after members" section of the Doxygen documentation:
int var; /**< Detailed description after the member */
What's curious about the example you gave, though, is that it uses a n... |
63,841,587 | 63,841,668 | Python var operand in c++ | What is mean Python .var operand using with OpenCV Mat and how convert it to c++?
Code: cv2.Laplacian(image, cv2.CV_64F).var()
| The python version of OpenCV uses numpy arrays instead of the cv::Mat class in c++ (those two are somehow inter-operable, so that each time the python api call c++ code the storage of the numpy array is transferred to a cv::Mat).
the var operand is thus the one from numpy: https://numpy.org/doc/stable/reference/generat... |
63,841,880 | 63,844,479 | adding install to QT pro file | when compiling qt app I'm running qmake && make.
I would like to run make install as well, so I've added the fillowing to my pro file:
target.files += $$OUT_PWD/$(DESTDIR)/$(TARGET)
target.path += /opt/zview
INSTALLS += target
but running make install
make: Nothing to be done for 'install'.
How can I correctly add i... | qmake checks for file existence before adding it to install target. As your build target doesn't exist yet it fails.
You should omit "target.files" completely to let qmake decide itself (see "Installing Files" subsection under qmake's manual Advanced Usage).
# target.files are set by qmake automatically as it's a well-... |
63,842,238 | 63,842,687 | Difference between Assert function in cpp and error handling | I have referred to some sites online and It has made me curious about this function. One site recommended the use of assert as function precondition where it could be used for detecting problems related to manipulation of data during parallel threads. But as people say that assert should be removed during release of th... | In the end it comes down to there being two (or more) kinds of "errors" that you can encounter in your program:
If you have a text field and ask a user to input a date in "yyyy-mm-dd" format, and the user writes "It is tuesday". Then that is a type of error that you can catch and respond to - and moreover, it is not so... |
63,842,240 | 63,842,602 | What integer type does bitwise shift use as shift size? | I'm trying to find information about shift's size type in C++. For example:
int x = 1;
char char_var = 1;
short short_var = 1;
int int_var = 1;
long long_var = 1;
long long long_long_var = 1;
x = x << char_var; // works
x = x << short_var; // works
x = x << int_var; // works
x = x << long_var; // works
x = x << ... | It is explained in [expr.shift]/1: (N4860)
The operands shall be of integral or unscoped enumeration type and integral promotions are performed
Unlike most other binary operators, the usual arithmetic conversions are not performed. The integral promotions mean that in your examples the operands of type char and shor... |
63,842,472 | 63,843,180 | OpenGL depth test doesn't work on some computers | My first question here. In my program depth testing works properly on some computers, but it doesn't work on others, objects that are located farther away cover those which are located closer. I called glEnable(GL_DEPTH_TEST); and tried to call glDepthFunc(GL_LESS); and as I said, everything works properly on some comp... | In addition to activating the Depth Test (glEnable(GL_DEPTH_TEST)), it is important that the current framebuffer has a depth buffer.
The default framebuffer is created at the time the OpenGL Context is constructed. The creation of the OpenGL context depends on the OS and windowing library (e.g. GLFW, SDL, SFML). Whethe... |
63,842,626 | 63,843,564 | Partitioniing a sequence to minimize difference | Question: We are given a sequence 1,2,3...N. We need to divide the given sequence into two parts A and B. We need to minimize |a - b| (where a is sum of elements in A, similarly b). To denote if it goes to A denote by "1" and if B denote by "0".
Example: For n = 3. The sequence will be 1,2,3 . Therefore (A:1,2) and (B:... | Simpler code with the same result
int main() {
int n;
cin >> n;
int odd = n % 2;
for (int i=0; i<n; i++) {
if (((i + 1 - odd) % 4) / 2)
cout << "1";
else
cout << "0";
}
//bonus: difference
cout << "\n" << (n + 1) % 4 / 2;
return 0;
}
|
63,842,635 | 63,842,709 | How to use the "clockwise/spiral rule" to read a const class member function? | How to use the "clockwise/spiral rule" to read a const class member function? Like:
class Box {
// ...
double volume() const; // <= How to read this function?
}
| It's not quite the spiral rule here, as that isn't a singular type definition, but a function instead:
double volume() const;
^ ^ ^---- Operates on const instance of Box
| \--- Function name
\-- Return type
Anything with a trailing const on it can operate on const Box, while absent that, you n... |
63,843,111 | 63,846,281 | Retrieve element from list of Object in cpp | I want to retrieve each element from the list of object in cpp and we have classes like below:
class User{
public:
bool isAvailable;
string value;
};
class Users{
public:
User dateFrom;
User dateTo;
User add1;
User add2;
};
Now somewhere else I have created a list of objects of User like std:: list<User> us... | This is just a guess of what you might want:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class User {
public:
bool isAvailable;
string value;
};
int main()
{
User someuser;
someuser.value = "Some user";
someuser.isAvailable = true;
User someotheruser;
someotheruser.... |
63,843,166 | 63,857,294 | What is the correct way to set up a UnitTest project for C++ in Visual Studio with additional include directories in the main Project? | I am trying to test a C++ Project in Visual Studio 2019.
The project, which should be tested, has a class MyClass. The project folder has a directory "include" and I did set up the path in Properties > C/C++ > General > Additional include directory.
MyClass.h:
#pragma once
#include <string>
class MyClass
{
public:
... | The solution is to also add the same "include" folder from the first project to Properties > C/C++ > General > Additional include directory in the TestUnit Project.
Then I can add
#include "MyClass.h"
#include "..\ConsoleApplication1\MyClass.cpp"
to the TestUnit1.cpp file and use the class MyClass correctly.
|
63,843,676 | 64,363,727 | Why std::future is different returned from std::packaged_task and std::async? | I got to know the reason that future returned from std::async has some special shared state through which wait on returned future happened in the destructor of future. But when we use std::pakaged_task, its future does not exhibit the same behavior.
To complete a packaged task, you have to explicitly call get() on futu... | std::async has definite knowledge of how and where the task it is given is executed. That is its job: to execute the task. To do that, it has to actually put it somewhere. That somewhere could be a thread pool, a newly created thread, or in a place to be executed by whomever destroys the future.
Because async knows how... |
63,843,708 | 63,844,071 | How to get function pointer from many functions and pass args to it? | I have many defined functions as follows, all return an int
int fn1(int x) {
return x;
}
int fn2(std::string x, int y, std::string z) {
// process string x and z
int x1 = process(x);
int z1 = process(z);
return x1 + y + z1;
}
// ... and many more similar functions
For some reasons, I need to impl... | Inspired by the comments:
A wrapper that takes some_struct_t data, std::vector<std::string> field_names. Assuming a
template <typename T>
T get_from_data(some_struct_t, std::string);
You have a function type
using func_t = std::function<int(const some_struct_t &, const std::vector<std::string>&)>;
which you can insta... |
63,844,854 | 63,846,623 | MS Visual Studio subproject compilation prebuilt events IF condition error | My solution has two projects: c++ dll and c# web.
Dll project has pre-built event like this
IF 2 == 1
(
echo ERROR: Dll building error
)
And, obviously, this condition not interrupts building process and it finishes with success, if I run it for dll project.
But..
the Web project depends on the dll and therefore u... | The problem appears to be that you're misusing MSBuild. The proper way to handle "subprojects" is to use a Solution. In this solution, you have both projects, and a project dependency from the web project on the DLL. You build the solution, and that's one MSBuild command. Therefore, the C# web project does not need to ... |
63,845,078 | 63,845,227 | Changing value of volatile const - G++ vs Visual Studio 2019 | So I have a following snippet (and a good reason behind it):
#include <iostream>
volatile const float A = 10;
int main() {
volatile const float* ptr = &A;
float* safePtr = const_cast<float*>(ptr);
*safePtr = 20;
std::cout << A << std::endl;
return 0;
}
Under G++ v8.2.0 (from MinGW suite), this ... | All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.
As governed by [dcl.type.cv]/4, your program has undefined behaviour
Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior. [ Ex... |
63,845,094 | 63,845,423 | value_comp and * before a iterator | What does the value_comp do, like does it check the first value equal to the second?
and * operator before the iterator?
map<char, char> m =
{
{ 'a', 'A' },
{ 'b', 'B' },
{ 'c', 'C' },
{ 'd', 'D' },
{ 'e', 'E' },
};
auto last = *m.rbegin(); // How does "*" affect the iterator returned
auto i = m.begin(... |
How does "*" affect the iterator returned?
It dereferences the iterator and gives the pointee. Meaning the last has type
std::pair<const char, char>
or
decltype(m)::value_type // or std::map<char, char>::value_type
If you would have just auto last = m.rbegin(); (i.e. without dereferencing), you would get the itera... |
63,845,216 | 63,845,385 | By using min_element(v.begin(),v.end()) - v.end(); getting wrong output for a certain vector array 10 10 58 31 63 40 76 | n=7
10 10 58 31 63 40 76
For this When I am using min_element(v.begin(),v.end()) - v.end(); I am getting the index as -7 but I should be getting -6 as it comes first from the end where am I wrong?
| min_element returns the first occurrence:
An element is the smallest if no other element compares less than it. If more than one element fulfills this condition, the iterator returned points to the first of such elements.
Your range is [v.begin(),v.end()), so the first occurrence would be the first element of v. The ... |
63,845,458 | 63,846,017 | How can I access member function of a class via a shared ptr to a shared ptr? | I have two classes, foo and bar, where bar contains a pointer to foo, as below.
#include<iostream>
#include<memory>
class foo {
private:
int num{4};
public:
void sum(const int& to_add) {num += to_add;}
int access_num() {return num;}
};
class bar {
private:
std::shared_ptr<foo> ptr;
public:
void change_ptr(foo... | This code
void change_ptr(foo& f) {
auto new_ptr = std::make_shared<foo>(f); // copy constructor
ptr = std::move(new_ptr);
}
calls a copy constructor to create an instance of foo on the heap and manage it with std::shared_ptr. You can check it if you delete the copy constructor in foo declaration. The code w... |
63,846,099 | 63,846,234 | c++ warning C4114 same type qualifier used more than once | I got a warning: same type qualifier used more than once
with these prototype:
static std::wstring joinWS(const vector<wchar_t*> Vect, const const char* delimiter);
static std::wstring joinWS(const vector<char*> Vect, const const char* delimiter);
wchar_t* and char* are different.
There is a way to fix it ?
Thanks you... | const is the type qualifier, and you should not use it twice in the same place like that.
"It’s like, how much more const could this be? And the answer is none.
None more const."
-- Bjarne Stroustrup
|
63,846,953 | 63,847,102 | how to pass function agruments(pointer, reference) to a "new thread" and expect return value? | I'm trying pass the pointer received from a member function of a class to another member function of that same class using thread and expect a return value.
class tictactoe
{
...
..
.
};
class AI {
public:
int pickSpot(tictactoe* game){
t = new thread([this]() ... | To get the return value you can us std::future and std::async:
#include <future>
#include <thread>
int pickSpot(tictactoe* game){
std::future<int> f = std::async(std::launch::async, [this, game]() { return findOptions(game); });
f.wait();
int res = f.get();
return res;
}
|
63,848,447 | 63,849,035 | What is the correct way to use oatpp::Enum as a path parameter type in Endpoint? | I'm using Oat++ framework (https://oatpp.io/) to build a REST API.
I want to manage user roles, and I want to have an endpoint to update a single field of a user record - the user role. To achieve this, I've created an end-point:
ENDPOINT("PUT", "/users/{userId}/role/{role}", updateUserRole,
PATH(oatpp::String... | Declare an Enum in the DTO code-gen section:
ENUM(UserRoles, v_int32,
VALUE(ADMIN, 1, "admin"), //<- you may use qualifiers here
VALUE(GUEST, 2),
VALUE(USER, 3)
)
Declare an endpoint:
ENDPOINT("PUT", "/users/{userId}/role/{role}", updateUserRole,
PATH(oatpp::String, userId),
PATH(oatpp::Enum<Us... |
63,848,737 | 63,848,857 | How to pass the reference of the class "Randomer" without constructor to a class via constructor. How does the class Randomer work? | I'm trying to store the reference of the class "Randomer" initiated in "main" to another class.
What would be best approach, the pointer or reference?
How does the class "Randomer" takes is initial values.
How does this work?
operator()()
size_t operator()() {
return dist_(gen_);
}
Randomer taken from: htt... | Both constructors of someClass initialize the random member too late. By the time the constructor body is called, all members are either initialized from the member initializer list, or default-initialized.
Randomer does not have a default initializer, so that is what the compiler is complaining about.
To fix that prob... |
63,849,410 | 63,849,688 | What are the advantages or implications of using assert vs exit or vice versa? | As far as I understand, a call to assert(e), where e is a boolean expression, executes something roughly like if (!e) { printf("%s:%d: failed assertion `%s'\n", __FILE__, __LINE__, e); abort(); } which terminates the program abruptly if the given expression is not true.
On the other hand, instead of using assert, I cou... |
what other advantage do you think one has over the other?
A macro is used because you want to be able to remove it via conditional compilation. In other words, you don't want the code to even appear in the binary.
Have I got the distinction right, or are there conceptual differences between the two which I am unawar... |
63,849,827 | 63,849,882 | change the value of const_cast ptr/ref doesn't change the original object value? | I found a weird problem of same address with different values after change const_cast ptr/ref object value.
#include <iostream>
using namespace std;
int main(void){
const auto i=123;
auto &ref2i=i; auto ptr2i=&i;
auto pp=const_cast<int*>(ptr2i); *pp=456;
cout<<&i<<" with value "<<i<<endl;
cout<<pp... | If you spell out the type of ptr2i you get:
const int * ptr2i = &i; // since i is const
Now you can const_cast this const int * to an int *:
auto pp = const_cast<int*>(ptr2i); // ok
But the pointed at variable i has type const int, so if you then try to modify this pointed at value:
*pp = 456; // oops, UB since yo... |
63,849,948 | 63,898,363 | QSqlQuery::lastInsertId doesn't work with MS Access | I work with MS Access database (.accdb) and I need to insert some data and then get the last inserted ID. When I use QSqlQuery::lastInsertId method I see the following error:
"QODBCResult::lastInsertId: not implemented for this DBMS" Error: ""
I tried to use SELECT @@IDENTITY and similar expressions (SCOPE_IDENTITY and... | Thanks to the @user9601301's comment. I just needed run SELECT @@IDENTITY; in a separate query just after the INSERT query, then it works.
|
63,850,414 | 63,850,498 | function pointer member variable | I have a member variable in a class of type double ()(double) but there are some functions id like to store that have a 2nd default parameter so they're double ()(double, double) so I can't store it in my current member variable.
Is it possible for me to make my member variable a double ()(double, double) so it could a... | You need two variables. The number of arguments in the call has to match the number of arguments in the function pointer variable, so you can't use the same variable for a different number of arguments.
If you only need one of them at a time, you can save space in the structure by using a union.
double somefunc(double)... |
63,850,579 | 63,983,459 | How to return a function value when using a dropdown list widget | I'm on Ubuntu. I need to return a function when I click in a dropdown list, but don't understand how to do that. For example:
...
dropdownList.set_active_text("Choose");
dropdownList.signal_changed().connect(sigc::mem_fun(*this, &usb_boot::showing));
std::cout << "var = " << var << std::endl;
...
void usb_boot::showin... | If I understand your question correctly, you want to reuse some values you get from within your handler (i.e. showing) outside of its scope. To do this, I would suggest using a lambda expression and capture by reference your variables. For example:
#include <iostream>
#include <gtkmm.h>
int main(int argc, char **argv)... |
63,851,474 | 63,853,245 | i have preorder and in-order of a tree. how to generate array representation of this | consider the below binary search tree
a
/ \
b c
/ \
d e
the pre-order is a b d c e
in-order is d b a c e
and array representation is a b c d \0 \0 e
now the question is
root of a tree is given and I can generate preorder and inorder from that root using the below code
void preorder(struc... | The array index can be calculated like:
Root->arrayIndex = 0
LeftChild->arrayIndex = 2 * parentNode->arrayIndex + 1
RightChild->arrayIndex = 2 * parentNode->arrayIndex + 2
To make it easy, let's assume you already know the resulting array size (if not, it's easy to calculate).
char array[ARRAY_SIZE];
memset(array, '\... |
63,851,753 | 63,852,126 | Operator Issue with creating this 2D array of nodes? | So I'm trying to create a 2D array, I'm new to C++ so I'm a little confused, I know I am using too many new operators but I don't know which one to keep. And I'm not sure what to do about the operator error.
Node class -
class Node
{
public:
int name;
Node *topedge;
Node *bottomedge;
Node *leftedge;
Node *ri... | A sample example with std::array. Explanatory comments inserted where I saw a need.
#include <iostream>
#include <array>
#include <string>
// using namespace std; prefer not to use this. It can cause confusing bugs
// simple test node
struct Node
{
std::string name;
};
int main() // no need for void C++ knows wh... |
63,852,548 | 63,852,973 | SFML How to spawn random shape and not have it overlap with another shape | I am having trouble spawning shapes in SFML in Codeblocks and verifying if its overlapping another shape and if it is indeed overlapping then trying to spawn it again in another position.
Here is the code:
srand(time(0));
CircleShape circleObjectArray[50];
for(int i = 0; i < 50; i++)
{
for(int j = i - 1; j < 49; j... | To check if the currently spawned shape doesn't intersect with any of the already spawned, your nested loop needs to iterate from the first to the previously spawned shape, so from the index 0 to the previous spawning index i - 1, not start from the previous. In case of overlapping, you also need to reset the inner loo... |
63,852,554 | 63,852,704 | Why do I get so precise floating-point number from std::cout? | The program
int main ()
{
long long ll = LLONG_MAX;
float f = ll;
std::cout << ll << '\n';
std::cout << std::fixed << f << '\n';
return 0;
}
gives:
9223372036854775807
9223372036854775808.000000
How is it possible? If 23-bit mantissa can have only 8,388,607 maximum value, why does cout output a 64... | You stored 2^63-1 in a float, which was rounded to 2^63 = 9223372036854775808. The powers of 2 are exactly representable.
The nearest number which is exactly representable is 2^63 + 2^40 = 9223373136366403584.
|
63,852,863 | 63,854,244 | Calling std::move without move constructor or move assignment | We know that std::move does not actually move anything. It just cast an lvalue reference (&) to rvalue reference (&&).
Then how in the following example, the copy constructor is called? If there is not move constructor, how does constructing an object that is using std::move() falls back on copy constructor? Exactly ho... | Let's reason by analogy. Think about this code:
void doSomething(const int& x) {
std::cout << "You like " << x << "? That's my favorite number!" << std::endl;
}
int main() {
doSomething(137); // <-- Here
}
Now, focus on the call in main. This code compiles and runs just fine, but there's something a bit weird... |
63,853,293 | 63,853,477 | Repeat template enable_if condition on multiple templates | I have the following code...
#include <iostream>
#include <map>
template <typename T, typename...>
struct is_contained : std::false_type {};
template <typename T, typename Head, typename... Tail>
struct is_contained<T, Head, Tail...>
: std::integral_constant<bool, std::is_same<T, Head>::value ||
... | If I understand correctly, you're looking for a simple using, like
template <typename T>
using TypeIsInMyList
= std::enable_if_t<is_contained<T, Fruit, void, int, char>::value>;
that you can use as follows
template <typename T,
typename = TypeIsInMyList<T>>
But I suggest to modify it as follows
template ... |
63,853,471 | 63,853,653 | PtInRect not picking up when a point (should) be within a rect | I have a Win32 program in which I need to detect if a button has been clicked, however the button's default functionality has been broken due to it being located on top of another control (a tab control). My solution to this has been to try and detect a click manually, like so:
//within WM_NOTIFY:
case TCN_SELCHANGING:... | Your POINT pt; variable is uninitialized when you are calling ScreenToClient(hWnd, &pt);, and thus its value is invalid for use when calling PtInRect(&rcButton, pt). On input, you have to specify the screen coordinates that you want ScreenToClient() to convert into client coordinates.
You can use GetCursorPos() to get ... |
63,854,135 | 63,854,388 | "Probability Based" Time Delay of Arrival Algorithm Producing Weird Results? | I've written the following algorithm designed to solve the Time Delay of Arrival problem through a "brute force" method. The problem is as follows: given the known locations of three receivers in a plane, and the propagating speed of some signal, determine the location of the signal source knowing only the times at whi... | alphaEst, betaEst and gammaEst are assigned the same values.
betaEst = sqrt(pow(i-statn1x,2) + pow(j-statn1y,2)) / c
probably it should be
betaEst = sqrt(pow(i-statn2x,2) + pow(j-statn2y,2)) / c
|
63,854,341 | 63,854,404 | Show Properties on far right of IDE in VS | I am trying to follow a tutorial where the teacher clicks the properties button on the far right
under "server Explorer, Toolbox" of the VS IDE. I do not have this and can not figure out how to enable it.
Example:
Everything I can find on google tells me to go to View->Properties, but this is not the same window that ... | View --> other windows --> Properties Window (alt+Enter)
|
63,854,923 | 63,854,984 | Compile-time Type Replacement in C++ | Say I have a program that uses a built in type such as float and I want to have the ability to supply a command-line argument to my compiler to change all float declarations to be fixed_point<8,8> instead.
Presuming that they're the exact same interface (as in, they can be treated the same with regards to assignment / ... | You can declare your variable with an alias type, which is defined conditionally based on a preprocessor definition, like this:
#ifdef LARGEFLOATS
using MYFLOAT = long double;
#else
using MYFLOAT = double;
#endif
You can then use the -D compiler flag to set the preprocessor definition, e.g. -DLARGEFLOATS (for MSVC, th... |
63,855,170 | 63,855,227 | std::stoul() takes a long time when input buffer is a very large char* | I have a char* buf that is 1024^3 (1G) in size. It contains newline delimited hex numbers (7fefdfff7\n7fefdfff8\n7fefdfff9\n7fefdfff\n7fefdfffb) and I am trying to read and parse each one of them.
My first approach was:
int buf_length = 1024 * 1024 * 1024;
char *buf = new char[buf_length];
std::size_t numchars = 0;
for... | std::stoul takes a const std::string& and not a const char*. That means that a std::string is constructed from your null terminated string, needing to copy every character.
You can instead use std::strtoul which takes const char* arguments directly:
for (const char* ptr = buf; ptr < buf + buf_length;) {
unsigned lo... |
63,855,339 | 63,855,906 | Why operator () is called twice in my program? | #include <unordered_set>
#include <stdio.h>
int hcount=0;
struct A{
int i=0;
A(){}
A(const A&a) :i(a.i){}
A(int const & i):i(i) {
printf("A ctor i=%d\n", i);
}
A&operator=(A &&a){
this->i= a.i;
return (*this);
}
bool operator==(A const &rhs) const {
... | Presumably, you are using libc++. Clang with libc++ exhibits this behavior. Clang with libstdc++ does not.
The initializer list insert calls the range insert which calls __hashtable::__insert_multi which calls __construct_node which hashes, after which __insert_multi calls __node_insert_multi which also hashes.
I see n... |
63,855,524 | 63,855,745 | C++ delete duplicates from cstring | I have a c-string that looks something like ABBBCACACACBA and I'm supposed to create a function that deletes the duplicate characters so I end up with ABC. I created a nested for loop that replaces every letter that matches the letter in the outer loop with a \0 and increments a counter that keeps track of the repeats.... | It is not enough to just replace duplicates with '\0', you have to actually remove them from the string and shift the remaining characters down. Try something more like this:
int size = SIZE, i = 0;
while (i < size)
{
int j = i + 1;
while (j < size)
{
if (letter[j] == letter[i])
{
... |
63,855,894 | 63,858,131 | Do SmartPointers passed as a generic pointer type need to be freed before passing to another function? | I presume Smart Pointers need to be specifically deleted when passed as a generic pointer type that gets assigned a value or a memory or resource leak will occur?
I'll use CComPtr as example. Will This Leak:
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
SomeOtherComObject2->Fu... | It ultimately depends on how the start pointer and the function are written, but in general, with ATL pointers and functions coded as they should be:
In debug mode:
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
SomeOtherComObject2->FunctionToFindComObject(&mycomobj); // will th... |
63,855,915 | 63,855,952 | C++ One-liner. Is it legal to construct an object and call a function on the same line | This code appears to break on one widely used compiler with optimizations enabled, although it works fine in Visual Studio.
struct foo
{
foo(int a) { s[0] = '0'+a%10;s[1] = '\0'; }
const char * bar() const { return &s[0]; }
char s[4];
};
int main( )
{
const char * s = foo(1234).bar();
printf("%p %s... | On this line:
const char * s = foo(1234).bar();
s is pointing to the char s[4] member of a temporary foo object. At the end of the full expression, this object dies, and s is now pointing to invalid memory. Printing it on the next line will invoke undefined behavior.
The issue here is with the use of the return value... |
63,856,259 | 63,856,316 | C++ No operator [] matches these operands | Sorry if this is a noob mistake, I'm really new to C++. My cin is not taking the value I'm trying to pass it.
void getData(incomeInfo incomeInfo, const int NUM_EMPS) {
for (int i = 0; i < NUM_EMPS; i++) {
cout << "Employee #" << i + 1 << "'s name: " << endl;
cin >> incomeInfo[i].name;
cout << endl;
cin... | You're declaring your function wrong, you need an array or pointer and incomeInfo is just a structure so you cannot use incomeInfo[i].name. Here's something that should work, pay attention to the upper and lower case names:
struct IncomeInfo
{
string name;
double pay;
double healthInsuranceDeduction;
};
void ... |
63,856,439 | 63,856,499 | undefined reference to `print(char const (*) [80], int, int)' collect2: error: ld returned 1 exit status | Does anyone have any idea what's wrong with my code? I keep getting an undefined reference error and I don't know what's causing it. Everything looks correct to me. I'm not very good with using pointers and references, but I checked my textbook and everything seems like it's written as it should be.
//System Libraries ... | Your prototype for the print function doesn't match the print function definition below; one has a const array parameter and the other doesn't. Just include const in the function defintion and it should work.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.