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,327,044 | 62,327,302 | c++ When/Why are variables captured by value constructed/destroyed | I have trouble understanding what is going on here with calls to C(const C&) and ~C()
So, I make a lambda that captures by value, and then return it.
As I understand, each returned lambda has it's own context
(the trace is consistent with that claim).
However, according to stroustrup describing of lambda as a function... |
I would expect one copy only to be made for the captured variable
And indeed the captured variable is copied once. That is, it's the source in a copy operation only once.
A std::function is not a lambda. Its initialization involves copying the callable object. So when the lambda is copied into the std::function, the ... |
62,327,253 | 62,327,480 | custom optional breaks strict aliasing rules | I wrote a custom optional class (since I am forced to use C++98 without STL).
It looks like this:
template <typename T>
struct optional {
char value[sizeof(T)];
bool has_value;
T& operator*() {
return *reinterpret_cast<T*>(value);
}
};
The compiler produces the warning dereferencing type-punne... |
What can I do to make this class without UB?
Use placement-new to create the object.
Call the destructor of the created object in destructor of optional
Do not reinterpret the address of the storage. Use the pointer returned from placement new. This unfortunately means that you need to store the pointer as a member.... |
62,327,296 | 62,330,123 | cross compile for android on linux with __ANDROID_API__ predefinition fails my program | I setup conan for cross building android app on my linux, i have my_profile below for conan for this cross building, which that I run conan create . user/testing -pr=my_profile
include(default)
target_host=aarch64-linux-android
android_ndk=$HOME/android-ndk-r21
api_level=21
[settings]
arch=armv8
build_type=Release
comp... | This #define __ANDROID_API__ 16 comes from the NDK itself (this is the lowest supported API for android-ndk-r21. To set it to 21, you must pass ANDROID_PLATFORM parameter to CMake. Update: this is actually wrong. For ABI arm64-v8a the minimal API is 21. So, the problem is that arch=armv8 didn't work.
According to the c... |
62,327,596 | 62,327,842 | C++ argument list for alias template is missing | I use the “alias template” in my “ListNode.h”,there is the code:
Note: IDE I use is visual studio 2019
//ListNode.h
#ifndef DSACPP_LIST_LISTNODE_H_
#define DSACPP_LIST_LISTNODE_H_
typedef int Rank;
template<class T>
class ListNode
{
private:
T data_;
ListNodePosi pred_; ListNodePosi succ_;
public:
List... | Much like a class template (in a non-deduced, C++17, context), you need to explicitly provide a template argument list when using an alias template.
ListNodePosi<single-type-template-argument> ...;
Your program contains several other errors, though:
In the declaration and definition of the ListNode class template, th... |
62,327,672 | 62,327,866 | What does [decl.constexpr].5 mean exactly? | The standard on constexpr functions states under point 5 of [decl.constexpr]:
For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpressi... | The rationale for this rule is that there should be at least one context where the function can be evaluated in a constexpr context. e.g. given:
constexpr int f(bool b){ return b ? throw 0 : 0; } // OK
constexpr int f() { return f(true); } // ill-formed, no diagnostic required
There is no way to invoke ... |
62,328,001 | 62,328,322 | Is there a way to loop over different data members of an object in C++ | If I have a class object comprised of 3 doubles; x, y and z, is there a way to loop over them in a function?
e.g.
for(i in (x,y,z))
do something;
I can do something similar with explicit casting, but I am wondering if there is a more elegant solution to this.
class testc {
public:
double x, y, z;
testc(d... | (C++20) Looping over a known number of public members: structured bindings in a range-based for loop initialization statement
As of C++20 we may combine structured bindings with range-based for loop initialization statements (the latter is a C++20 feature):
Grammar
for ( init-statement(optional) range-declaration : ra... |
62,328,169 | 62,328,218 | Program printing % after expected output | I am new to C++ and just ran my first program. The problem is that the output has a '%' after the expected output.
I have installed LLVM using Homebrew,
brew install llvm
I have tried compiling with clang++ (installed with llvm) as well as g++ (macOS default).
#include <iostream>
int main()
{
std::cout << "Y... | The '%' is printed by your shell (probably Zsh?) after a program finishes without printing a newline character as the last character of its output.
To prevent this, output a newline:
std::cout << "Hello\n";
|
62,328,203 | 62,328,425 | C++ Check how many times there are numbers in the resulting array | I'am beginner in C++
Somebody could help me with it.
INT array.Random.
fill an array of 1000 integers with random numbers from 10 to 77.
Check how many times in the resulting array there are numbers 10, 20, 30, 40, 50, 60 , 70.
Print the received statistics.
I see it like this but i dont know how make count of numbers... | Start the same way as if you were counting only one number, except you have seven checks and seven counters:
for (int i = 0; i < 1000; i++)
{
if (number[i] == 10)
countUnits[0] += 1;
else if (number[i] == 20)
countUnits[1] += 1;
else if ...
...
}
Then you notice that there is a pattern to t... |
62,328,243 | 62,328,333 | How to pass arguments from two different functions | I've got a basic question:
There is a function that can take six arguments:
void dataSlot(double val1, double val2, double val3, double val4, double val5, double val6);
How can I pass those arguments from two different functions, simultaneous?
void functionOne()
{
// val1, val2 and val3 from functionOne
}
void fu... | Return the values each function produces and use them when you have all the values:
#include <array>
std::array<double, 3> functionOne()
{
// ...
return {val1, val2, val3};
}
std::array<double, 3> functionTwo()
{
// ...
return {val4, val5, val6};
}
void overallFunction()
{
auto firstThree = funct... |
62,328,574 | 62,328,726 | Why many projects don't provide a pre-compiled binary file? | This question has been for quite a long time for me. I don't use c++ very often, and it seems most cpp libraries are provided as a zip file or tar ball containing source code.
So, the question is:
Why those projects don't provide a pre-compiled binary file?
My current understanding of the "autoconf, make, make install,... | Platforms generally have a common C ABI that dictate symbol naming, function calling conventions, and other low-level details. Compilers that target that ABI can interoperate with other compilers that do the same. Linux libraries and Windows libraries are incompatible, but it is usually possible to build a small handfu... |
62,328,594 | 62,328,727 | Is there a way to not use an item from a namespace? | I've learned that typing
using namespace std;
at the beginning of a program is a bad habit, because it includes every function in the namespace. This risks causing errors if there is a name collision.
My question is, does there exist a way to specify which namespace functions you don't want to use? Is there some state... | You cannot do that (include everything and then selectively exclude something).
Your options are:
1) always explicitly qualify names. Like std::vector<int> v;
2) pull in all names with using namespace std;
3) pull in just the names you need with, for example, using std::vector; and then do vector<int> v; - names other ... |
62,329,159 | 62,329,366 | Time and space complexity of c++ program | #include<iostream>
#include<vector>
using namespace std;
vector <int> removeFirstOrder(const vector<int>& orders)
{
return vector<int>(++orders.begin() , orders.end());
}
bool isFirstComeFirstServed(const vector<int>& takeOutOrders,
const vector<int>& dineInOrders,
... | Each time removeFirstOrder is called the returned vector is smaller by 1.
n-1 + n-2 + n-3 + ... + 1
From arithmetic progression rules, the sum is (n+1)*n / 2 which is order n^2.
Tail call optimization could make it O(n) space behind the scene, but it's not guaranteed be performed at all.
|
62,329,195 | 62,329,355 | When is a constexpr evaluated at compile time? | What assurances do I have that a core constant expression (as in [expr.const].2) possibly containing constexpr function calls will actually be evaluated at compile time and on which conditions does this depend?
The introduction of constexpr implicitly promises runtime performance improvements by moving computations in... | When a constexpr function is called and the output is assigned to a constexpr variable, it will always be run at compiletime.
Here's a minimal example:
// Compile with -std=c++14 or later
constexpr int fib(int n) {
int f0 = 0;
int f1 = 1;
for(int i = 0; i < n; i++) {
int hold = f0 + f1;
f0 =... |
62,329,244 | 62,329,445 | How can I typedef a namespace qualified type? | I want to do something along the lines of #define std::unordered_map my_namespace::my_map. There are various complicated reasons for why I want to do this (legacy code, future upstream merging, performance, etc.). Unfortunately, #define doesn't work with :: and typedef seems to have issues as well. How might I do this?... |
How can I typedef a namespace qualified type?
You define a typedef for a (type that is in a namespace) like this:
typedef some_ns::type alias;
You define a (typedef that is in a namespace) for a type like this:
namespace other_ns {
typedef some_ns::type alias;
}
Or, you can use the corresponding using syntax, w... |
62,329,300 | 62,331,485 | MFC: Can you change the acceleration of the spin in a CDateTimeCtrl? | I am using VS-2015 and I'm trying to extend CDateTimeCtrl to detect when it surpasses 59' and change the hour accordingly.
The problem is now that when I hold the arrow to increment or decrement, it accelerates and I can no longer check if it changed from 59 to 00 or vice-versa because increasing or decreasing in more ... | You can retrieve the handle of your CDateTimeCtrl object's contained 'spin button' using the class GetDateTimePickerInfo() member function, which will be in the hwndUD member of the returned DATETIMEPICKERINFO structure.
You can then effectively disable acceleration for that spin control by sending it the UDM_SETACCEL ... |
62,329,621 | 62,666,498 | SC_METHOD in custom constructor | In my custom constructor i want to use SC_METHOD:
class host_command : public sc_module, public bus_if {
public:
// sc_out<packet_type> out_packet;
sc_buffer<packet_type> out_packet;
host_command(char *name, unsigned int limit) : sc_module(name) {
SC_METHOD(write);
sensitive << out_packet;
... | When you declare a module without using the SC_MODULE macro, you must use the SC_HAS_PROCESS macro to indicate the current module for SC_THREADs and SC_METHODs:
SC_HAS_PROCESS(host_command);
host_command(char *name, unsigned int limit) : sc_module(name) {
SC_METHOD(write);
sensitive << out_packet;
}
|
62,329,796 | 62,394,252 | How to obtain CAN transmitted data (256 bytes)using Diagnostic functions using CAPL? | 256 bytes of data is transmitted to CAN bus as response to a particular DID. It consists of 14 samples of data AND one sample consists of 12 bytes of data (10 different values of 10 different variables packed across 12 bytes). I need to collect these different samples with the help of CAPL using diagnostic functions.
| You can use diagGetPrimitiveData or diagGetPrimitiveByte for raw data. Details and example you can find in CANoe help
For reading parameters defined e.g. in .cdd you can use diagGetParameter
|
62,329,827 | 62,447,492 | "Undefined symbols for architecture x86_64" In SDL 2 (macOS) | Basically, I was trying to make my first SDL2 game in C but encountered the same error every time. Undefined symbols for architecture x86_64 Where i can't call simple functions like the SDL_CreateWindow from SDL. I thought something like this would happen because I have a very limited understanding of C and C++ as I on... | I think I figured it out, the problem was I also needed to compile the source libraries but I had no idea how to do this and how to ensure that gcc would link everything together.
All the other tutorials were just telling me to put the framework in /Library/Frameworks which was wrong.
Turns out I had to mess around wit... |
62,329,978 | 62,330,104 | Potential Overflow Comparing Sorts and Comparisons of Various Sorting Algorithms | Im currently working with a simple program which compares the number of comparisons and swaps for a number of common sorting methods and testing it on data sets of size 1000, 2000, 5000, 10000, 50000 and 100000. The program appears to be working perfectly up until 50000 values however for example, testing the insertion... |
is there potentially some sort of overflow occuring as the number of swaps and comparisons grows too large to properly keep track of?
The output seems to indicate that overflow is happening.
You can add a test to be sure.
void swap(int& a, int& b)
{
++swaps;
if ( swaps == std::numeric_limits<decltype(swaps)>... |
62,330,537 | 62,330,605 | Call class function with macro | Here i want to call world function from class Hello with macro MPRINT() but it doesn't recognize the macro syntax:
#include <windows.h>
#include <iostream>
#include <string.h>
using namespace std;
// first try
#define MPRINT(text) \
[]() -> Hello::world(#text)\
}()
// second try
#define MPRINT(text) \
Hello ... | In your first attempt, you are trying to use Hello::world, but this is not the correct syntax for calling a non-static member function.
In your second attempt, using MPRINT would result in:
string test1 = Hello obj; obj.world(text); ;
which is also clearly invalid.
You could write the macro like this:
#define MPRINT(t... |
62,330,746 | 62,339,360 | How to use gcc __is_class with preprocessor if in C++ | I want to send a var to a function if is it a class. I try with std::is_class but this gave me an erros because std::is_class is run time and not a preprocessor. I can't make the preprocessor if to work. any suggestions? in the function 'toJson' in the loop I am adding the types to the json object. I need to check if t... | if constexpr Is exactly what I needed. It can compares the type at compile time, which allow me to call the right function and ignore completely the other function that is not compatible with this type.
if constexpr (std::is_class<Type>::value)
{
// call the class function
}
else
{
// not call the class functio... |
62,330,908 | 62,331,014 | ReadFile returning INVALID_HANDLE on second call | I am trying to read data all of the data in a PCAPNG file in chunks only using the Windows API's.
I have the first read of the file working with ReadFile and the data that is being returned is correct but on our subsequent call, we are failing the ReadFile with INVALID_HANDLE.
HANDLE hFile;
DWORD dwBytesToRead ... | You're reading 32 bytes into a buffer that is only 8 bytes long.
You need to either change ReadBuffer to be larger, change the type from a DWORD to something that is 16 bytes long, or change dwBytesToRead to be the appropriate size (sizeof(ReadBuffer), and change the declaration order).
|
62,331,220 | 62,332,159 | How do I run something inside a class concurrently (in single threaded platform)? | I have to write a class that implements the given interface below. When I call the start function it should starts counting every 1 millisecond and when I call the stop function it should stop counting. The read function should return the value of the counter.
How should I go about writing this implementation as I'm i... | If you use HAL libraries:
class Counter{
public:
void stop()
{
end = HAL_GetTick();
}
void start()
{
start = HAL_GetTick();
}
uint32_t read()
{
return end-start;
}
};
If you want to be able stop counting just use any hardware timer this purpose instead of... |
62,331,265 | 62,331,315 | c++: how to access variables in the same namespace but defined in a different file? | Consider the following two files:
a.cpp:
#include <string>
namespace a
{
const std::string str = "something";
}
b.cpp:
#include <iostream>
#include <string>
namespace a
{
extern const std::string str;
}
int main(int argc, char **argv)
{
std::cout << a::str;
return 0;
}
When I compile them, thusly (... | const std::string str = "something";
should be
extern const std::string str = "something";
const qualifying objects at namespace scope has the additional property of imposing internal linkage on their name. Your original code is the same as
static const std::string str = "something";
|
62,331,988 | 62,332,423 | Is there a way to get a type of a template-provided size? | I seem to remember that there is some way to do something like this, but I can't find it:
template <int SIZE>
struct S {
uint_least<SIZE>::type my_uint; // <-- I made this up, but I am looking for something equivalent
};
Is there such a thing? If so, what is the real syntax?
| I ended up doing this:
#include <cstdint>
template <std::size_t N>
struct sized_ints : sized_ints<N-1>
{};
template <>
struct sized_ints<65>
{};
template <>
struct sized_ints<0>
{};
template <>
struct sized_ints<33>
{
using int_fast_t = std::int_fast64_t;
using int_least_t = std::int_least64_t;
using ui... |
62,332,217 | 62,332,284 | If lambdas don't have a specified type, how does std::function accept a lambda? | Can anyone explain how lambda functions are represented in std::function? Is there an implicit conversion by the compiler and std::function used as a container?
I recently asked a slightly different question, which was marked as a duplicate of this question. The answer is the type of a lambda function is not defined ... | The type is there. It’s just that you don’t know in advance what it is. Lambdas have type - just the standard says nothing about what that type is; it only gives the contracts that type has to fulfill. It’s up to the compiler implementers to decide what that type really is. And they don’t have to tell you. It’s not use... |
62,332,345 | 62,335,551 | Cast LPHMIXER to HMIXER in Windows mmeapi | I'm trying to figure out how to call the mixerOpen() and mixerClose() functions using C++ on the Windows 10 platform. I'm using cl.exe as the compiler.
The mixerOpen() function fills an LPHMIXER with a handle to the mixer object. When I call the mixerClose() function, it expects a HMIXER instead of the LPHMIXER.
Questi... | LPHMIXER is just a typedef for HMIXER *. The sequence to open/use/close the mixer object is:
HMIXER hmixer;
MMRESULT retval = mixerOpen(&hmixer, 0, NULL, 0, MIXER_OBJECTF_AUX);
if(retval != MMSYSERR_NOERROR) { /* error */ }
/* use hmixer */
retval = mixerClose(hmixer);
|
62,332,442 | 62,332,782 | How to call thread with a public member function from another class as argument | I already checked Start thread with member function and similar posts, and followed the instructions, but I get this error message:
'std::invoke': no matching overloaded function found
SerialPort.h
#include <array>
#include <string>
class AudioClass
{
public:
void playAudio(std::array<std::string, 11> turretDete... | The this pointer needs to be passed as the 1st argument:
void exampleReceiveData(void)
{
AudioClass ac;
std::thread t(&AudioClass::playAudio, &ac, turretDetectionWavFiles,
turretActivationWavFiles, turretSearchingWavFiles,
turretPowerDownWavFiles, turretAttackWavFiles, ... |
62,332,536 | 62,391,503 | Static member variables are not translated by gettext | Problem
My software is translated via gettext. The locales are called at the very beginning of the main function. Unfortunately, the static member variables of my monostate "Messages" which contains all message strings are not translated as static member variables are processed before the main. The rest of the software... | I got it with the comment of Reinstate Monica.
Just put an unused variable before all static member variables and calculate its value in a lambda function. The value itself does not matter at all. The only thing that matter is that the lambda function makes the right locale function calls.
See my solution below:
#inclu... |
62,332,714 | 62,332,803 | What does the standard say about this pointer-to-member-function type template parameter? Is my code wrong, or is MSVS 16.6 buggy? | Here's some code that works in GCC, Clang and MSVS (at least, those versions currently available on Compiler Explorer):
template <typename T, auto T::* MemberPtr>
struct Foo
{
Foo(const T& e) : _e(e) {}
void operator()() const
{
(_e.*MemberPtr)();
}
private:
const T& _e;
};
struct Bar
{
... | The parameter/argument combo is valid as is
[temp.param]
4 A non-type template-parameter shall have one of the following
(optionally cv-qualified) types:
...
a type that contains a placeholder type.
[temp.arg.nontype]
1 If the type of a template-parameter contains a placeholder
type, the deduced parameter type i... |
62,332,775 | 62,333,008 | How to divide code into multiple .cpp files C++ | I want to create a function outside the main.cpp file
i've tried creating a header file but it doesn't work:
Main.cpp:
#include "other.h"
int main() {
MyFunc();
}
Other.cpp
#include <iostream>
#include "other.h"
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
Other.h
#includ... | You must include a header file and not a C++ file.
And therefore, you need to remove:
#include "other.cpp"
from other.h & use the following command-line for compiling:
g++ -o output main.cpp other.cpp
You'll get it linked and then compiled, then everything should be working fine.
|
62,332,890 | 62,332,961 | Are the following initializations equivalent in C++ | I read that often list-initialization is preferred over the 'old' way of using round braces, because they don't allow narrowing conversions.
The auto keyword has similar attributes, in that it avoids conversions at all.
I wonder whether the following two statements are equivalent:
auto a = SomeClass(arg_a, arg_b);
auto... | They may or may not be the same, it depends on the type. For instance, if you have a std::vector then
auto vec1 = std::vector<int>(1, 2);
calls the constructor with the form of
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
Which creates a vector of size 1 with the el... |
62,333,120 | 62,334,224 | Declare std::array member variable's size based on constructor string literal | I need a class which takes in a compile-time string literal (const char* const) as its only constructor argument.
I would like to have an std::array member variable store the words in this string literal (split up using spaces, for example). The size of this array therefore will never change, as the string literal is k... | First, you have to use class templates, as there should be a different size of the class for different string literals. Template arguments should at least contain the size of the enclosed array (e.g. template<std::size_t N>).
Then you may find Class Template Argument Deduction from C++17 useful so you don't have to spe... |
62,333,392 | 62,333,480 | How do I get VS Code on WSL to debug my C++ code? | I have installed Ubuntu 20.04 on my Windows 10 system. Before I first ran VS Code from within Ubuntu, VS Code worked fine in Windows. Now, I can build my C++ app there, but cannot debug it. I get an alert box saying "Cannot find runtime 'node' on PATH. Is 'node' installed?"
Whenever I start VS Code, a background pro... | Some time ago for me also was tricky to run debugger on VS Code under WSL Ubuntu. With a lot of attempts I have got next .vscode/launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.micros... |
62,333,477 | 62,383,502 | How can I get access to parameters passed to the program in QT | I have 4 processes in which are related to each other. In the first program, I have a function in which it gets input from the user and then execute the second program. The following function execute the second program:
void MainWindow::ExecuteCuiMode(QString arg_username, QString arg_password, QString arg_domain, QStr... | there is such a subtle point that the arguments that QApplication does not handle are simply deleted and those that don't work with them are equal to 1 so it’s not a fact that 1 will be the arguments that you want, I think that you need to call
QStringList QCoreApplication :: arguments ()
and looked if there are any... |
62,333,479 | 62,333,760 | c++ const mysqlpp::String ambiguous error | I'm a newbie to c++ and have just got c++ querying an sql database with mysql++.h
The SQL query itself works, and I can print out results.
char *token;
Query query = conn.query();
query << "SELECT title, description FROM mydb.mytable LIMIT 2";
StoreQueryResult ares = query.store();
for (size_t i = 0; i < ares.num_rows... | strtok will alter the string you pass in that it inserts string termination character 0x0 after each token. So you need a char*, but c_str returns a const char*.
If you want to use strtok, you will need to get a copy of the const char* returned by c_str(). The probably easiest way is to use strdup:
char* c = strdup(are... |
62,333,691 | 62,333,805 | I am trying to solve this problem but getting a run time error due to segmentation fault | I used scanf to get inputs for 3 variables but I believe it crashes when it gets only 2 integers as input, Can someone suggest a better way to scan all 3 variables
Question:
You are hired to offer phone number look up service for a company's internal network. The company has N employees with employee ID 0 to N−1. Your ... | You are reading 3 values at a time:
scanf("%d %d %d\n", & t, & i, & k);
but the actual number of integers depends on the value of t. This means that for the sample input the first time you read these data the values for (t, i, k) would be (0, 2, 0). The next read is surprisingly (7, 0, 3), and the program is not prepa... |
62,333,828 | 62,334,788 | Navigating the while loop | I'm making a sort of hang-man type game and have things working pretty well apart from having a message appear when the player does not guess a letter in the phrase. If they guess a number that's in the phrase, the phrase "nice" appears as normal. However, with the wrong letter, it just prints out "wrong" 10 times (whi... | You check for matches for every letter in the phrase in a for-loop. So if a guess matches nothing, it will miss 10 times so it prints out "WRONG." ten times. Also correct guess of repeating letters will also print out that many "NICE!". You probably just want to declare a int flag = 0 just before the for-loop to set to... |
62,334,210 | 62,334,245 | Why i can't to display my string value after assign number to it? | i want to get all numbers from my string and after it push them to vector but before this i want to display value of my "string number" to check effects, the problem is than i don't see it.
string napis = "ada87dasu3da1";
string number = "";
int counter = 0;
for(int i = 0; i < napis.size(); i++){
... | number[i] = ... does not append a new character, like you are expecting it to. It modifies an existing character at a given index, but there are no characters to modify because number is always empty! You are not doing anything to increase its size().
You need to use the string's push_back() or operator+= instead:
nu... |
62,334,215 | 62,334,383 | Returning Composite object of composite pattern doesn't return the whole object | I created a composite pattern with Component, Leaf and Composite Classes, where only the Composite Class has both a member variable vector and add method:
void add(Component *a);
vector < Component * > children;
In a separate class B, I created a method getComponent() to return a Composite member variable
Class B: p... | Your problem arises in main(). You are creating empty object of type A* which points to nullptr. Then you are tying to call member function of myA, which in this case points to nothing, try to initialize it correctly, then call you member function via myA.
|
62,334,326 | 62,334,372 | behavior of c++ code changes depending on the compiler | I’m really new to c and c++
I tried to experiment with structs to create a list-like structure that can contain float and lists, basically.
This code compiles, but it behaves differently depending on the compiler:
with the latest version of visual studio community, it outputs 5 and then 0.
with an online shell, I get ... | On this line:
aBox.value.elements = &newVec;
you are storing the address of a local variable. When you return from the newBox function, that variables dies, and then accessing that memory via the pointer invokes undefined behavior.
|
62,334,452 | 74,083,393 | fast-math cause undefined reference to `__pow_finite' | on ubuntu 20.04, when I use clang-8 or clang-9 (clang version 9.0.1-12) to compile a simple code containing reference to libm, it will fail with error "undefined reference to __pow_finite"
#include <math.h>
int main()
{
double x=1, y=1;
x = pow(x,y);
}
clang-9 -lm test.c -ffast-math
/usr/bin/ld: /tmp/test-9b1... | TL;TR: This was a bug in clang which fix in clang-10. Anyone has the same problem please either use gcc or use latest clang version.
The root cause of this is clang wrongly called some non-API functions in libm:
They were only ever an ABI (selected by use of -ffinite-math-only or
options implying it, which resulted in... |
62,334,775 | 62,341,983 | Why does my C++ to hexadecimal conversion cause different formatting? | I have a memory address as a const void * variable. For printing that memory address as hexadecimal I'm using the following function(s):
inline void replace_all(std::string& text, const std::string& replace, const std::string& replacement)
{
if (replace.empty())
{
return;
}
size_t start_positio... | Your intention is not fully understandable. The inserter operator is alread overloaded to print out pointer. If you have a pointer, regardless which, you can simply insert the address into a stream:
#include <iostream>
int main() {
double d = 3.14;
// Print address in hex
std::cout << &d << '\n';
re... |
62,334,798 | 62,335,166 | Operator overload in a templated method | I have a class (with irrelevant details stripped):
template <typename... Ts>
class ParameterPack
{
private:
std::tuple<Ts...> parameters;
public:
ParameterPack<Ts...>(const char* pVariableName)
{
/// Irrelevant extra details
}
template <typename T, std::size_t idx>
T getValue()
... | It's not possible to specialize a templated operator[] on the index, since the index is a run-time property.
For this reason std::tuple has a get<idx>() member function instead of operator[] (see this related question).
In addition, it's not possible to deduce a function (or operator) return type from an assignment.
So... |
62,334,870 | 62,335,673 | How do I calculate the time complexity of the function? | int coin_row(int[] array, int index, int length)
{
if (index >= length) //beyond last coin
{
return 0;
}
int value = array[index];
if (index >= length - 1) //last coin
{
return value;
}
else if (index >= length - 2) //second last coin
{
return max(value, coin... | It's O(n).
To see this: write a recurrence relation. Here is it T(n) = T(n+1) + O(1) and T(l) = 1. The O(1) in the first equation comes from the max() function.
Since each step requires O(1) operations, and there are n recusive calls where n is the length. The time complexity is O(n*1) = O(n).
|
62,335,017 | 62,335,098 | Conversion of string to double without scientific notation in C++ | I have a string variable and want to convert it into double without any scientific notation. I tried using std::stod but that doesn't work.
std::stringstream timestamp;
timestamp << t_val;
string test = timestamp.str();
cout << test << endl; // this gives 1506836639.96
double d = std::stod(test);
cout << d << endl; //... | The scientific notation has to do with std::cout, not the way the value is stored, so you must use std::fixed before you print the value:
std::cout << std::fixed << std::setprecision(2) << d << std::endl;
As you can see in the demo, this works fine, it should work for you as well.
As @goodvibration commented std::to_s... |
62,335,149 | 62,335,402 | Trying to create a random number generator in c++ and getting an error | I'm pretty new to c++ and currently trying to code a random number generator from scratch.
However, I'm getting an error under while statement and I don't know what I am doing wrong.
I have some experience in python, so maybe I guess I might be creating python like syntax instead of c++ one? Thank you.
#include <iostr... | The problem is that your generator code is not inside a method of the class, it is in the class declaration itself, which is a syntax error. Try something more like this instead:
#include <iostream>
using namespace std;
class Random {
public:
double oldRoot;
double newRoot;
int iteNum;
Random(double... |
62,335,249 | 62,339,388 | Qt Signal/Slot Issue | I can't figure out what's going wrong here.
I want to pass a value from a class to another.
Here's the code:
mainwindow.h
public slots:
void printNumbers(int);
mainwindow.cpp
void MainWindow::printNumbers(int a)
{
qDebug() << a;
}
myudp.h
signals:
inline void sendBuff(int);
myudp.cpp
[***]
... | remove the inline declaration of the slot, and if your class needs an internal use for sendBuff then declare a new method for that...
signals:
void sendBuffSignal(int);
and in the cpp
void MyUDP::sendBuff(int a)
{
qDebug() << "sending " << a ;
}
|
62,335,968 | 62,336,282 | Is member access on a null pointer defined in C++? | Is address computation on a null pointer defined behavior in C++? Here's a simple example program.
struct A { int x; };
int main() {
A* p = nullptr;
&(p->x); // is this undefined behavior?
return 0;
}
Thanks.
EDIT Subscripting is covered in this other question.
|
&(p->x); // is this undefined behavior?
Standard is a bit vague regarding this:
[expr.ref] ... The expression E1->E2 is converted to the equivalent form (*(E1)).E2;
[expr.unary.op] The unary * operator ... the result is an lvalue referring to the object ... to which the expression points.
There is no explicit men... |
62,336,076 | 62,336,110 | map c++ with const char* keys retrieves null | So, I am trying to learn map in C++. I put the type as std:: map <const char *, int> to a variable month.
Say, the data is month["Jul"] = 7;
When I tried to retrieve the value directly
printf("%d", month["Jul"]);
It succeeds and outputs the value.
7
Trying with another variable succeeds too.
const char *p = "Jul";
... | When you use const char* as the key, std::map will compare on the pointer directly, but not the content pointed by the pointer. For c-style string literals, the identical string literals might be compared as equal, but this is not guaranteed.
The compiler is allowed, but not required, to combine storage for equal or o... |
62,336,295 | 62,336,977 | Sorting a buffer of data packets with specific structure | I need to sort data packets which have been transmitted over a TCP server/network in ASCENDING order based on the SEQ number (which is just an unsigned 4 byte integer). In other words, I want to rearrange my data buffer (I am using std::vector for simplicity), so that the data is ordered in ASCENDING order by SEQ, foll... | By your question. A vector<byte> represents your buffer
Following are pseudo code for explanation.
vector<byte> buffer;
// receive data;
// packet as a struct
vector<packet> packets = extract_packet( &buffer );
sort(packets .begin(), packets .end(),
[](const packets & a, const packets & b) -> bool
{
return ... |
62,336,297 | 62,336,345 | constexpr with conditional statement error, using Stroustrup example | Stroustrup C++ 4th Ed. Page 311 describes constexpr fac for factorial, which includes a conditional statement. Then on Page 312, describes constexpr bad2 with a conditional statement and a comment that it results in an error. He also states on Page 312 that "A constexpr function allows recursion and conditional expre... | Before C++14, if statement can't be used in constexpr functions, and it could have exactly one return statement.
(until C++14)
the function body must be either deleted or defaulted or contain only the following:
null statements (plain semicolons)
static_assert declarations
typedef declarations and alias declara... |
62,336,355 | 62,338,928 | Pass formatted text from QML to C++ | I have a simple pdf generator in my QML app, which uses C++ to receive a signal and write my PDF document to the device - when using a sample TestHtml.html document in the resources prints as intended, but I'm struggling to be able to send over custom HTML formatted text directly from the QML page.
What I want to do
M... | You can expose your pdf class to QML. Make functions Q_INVOKABLE to be able to call them directly from QML or even better use Q_PROPERTY
Docs for Q_INVOKABLE
Docs for Q_PROPERTY
Here is an example:
Register/expose your pdf class to qml in main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "p... |
62,336,402 | 62,356,987 | Why does void * pointer to SetArgPointee in gmock cause error | Consider this:
struct INFO {
unsigned char a;
int b;
char c[100];
};
...
INFO inf = {'X', 1010, "AOK Message"};
void *mdptr_s = reinterpret_cast<void *>(&inf);
size_t msiz1 = sizeof(inf);
The mock is:
MOCK_METHOD((size_t), recv, (void *buf_, size_t len_), (override));
In my mock test there is an EXPECT_CALL usi... | There was a similar problem asked and answered on this other thread, perhaps that will help: https://groups.google.com/forum/#!topic/googlemock/sWBP2q8VZaA
|
62,336,542 | 62,336,673 | Using enum as a condition, what will the if condition return, True or False? | enum segment
{
OFF,
ON
};
int main()
{
segment indicator;
int temp_prev = 37;
int temp_curr = 39;
indicator = OFF;
if ((temp_curr > temp_prev and temp_curr > 39) or !indicator)
{}
This is part of a basic program to understand the use and properties of enum.
What confuses me is, what does !enum return... | (Assuming C) An enum is stored as an int. In your example, OFF would default to zero, which is treated as false in a conditional, any non-zero value would be considered true.
|
62,336,568 | 62,336,591 | C++: constexpr fibonacci sequence evaluation | I'm studying constexpr and trying to implement an example in Stroustrup C++ 4th Ed. Page 312. My understanding was computation of fib(45) should be done at compile time, however my results suggest the computation is taking place at run time.
Does anyone know where I have gone wrong in establishing computation of fib(4... | constexpr means that a function could be evaluated at compile time.
This statement:
cout << fib(45) << endl;
is not a context that requires compile time evaluation of fib, so the compiler may or may not evaluate this at run time.
You can force it to be evaluated at compile time like this:
constexpr auto res = fib(42);... |
62,336,657 | 62,336,793 | how to write a function such that if we print a object then it's need to print a arguments passed in object | In the class base, we need to write a function such that printing an object will print arguments of an object using oops concept.
#include <iostream>
using namespace std;
class base{
int num;
string s;
public:
base(int elem,string p){
cout<<elem<<" "<<p<<endl;
}
// todo:
};
int main() {... | Your current idea is not far from working, except you print the constructor arguments to std::cout as soon as an instance of base is created - not when the programmer using the class expresses such a wish. What you need to do is to save the arguments given when constructing a base. You'll then be able to print them on ... |
62,336,732 | 62,336,945 | C++ UDP Socket not working to send back from server to client after receiving first packets from client | Writing a UDP client-server app in C++ (done that lots of times before in many languages in the past 15 years), but somehow this one is not working correctly.
I cannot post actual code nor minimal reproducible app at the moment but I am willing to pay for live help if anyone is available to help solve this quickly wit... | Only the original receiver socket is allowed to reply to the client, because it's the client request that opens the port in the NAT. So either use the same socket in the server to receive and reply, or get the port that the second server socket was bound to and transfer it with an initial message through the original s... |
62,336,911 | 66,606,237 | Ultralight - how to minimize window | I am making my first app with Ultralight and I am trying to make a custom title bar. The problem is: I am not able to minimize my window. Currently, I tried using the ShowWindow function and the GetForegroundWindow to grab y window but, it just minimize the window and the one beside it. If anyone have any question or c... | As mentioned in Ultralight's github repository, ultralight is currently not supporting borderless windows
AppCore is currently under active development and only supports single-window apps at this writing. A number of planned features (app icons, automatic packager, borderless windows with custom draggable titlebars, ... |
62,337,244 | 62,337,530 | How to return a current function value in a recursive function call | int countdown(int num)
{
if (num ==1)
{
return 1;}
else
{
return num + countdown(num-1);}
}
I want to know the current value of the function each step .How can i print out the value of countdown function each time num decrease ?
Thanks
| If I understand correctly, you want the value returned by countDown(num-1) each time.
You can try this.
int countdown(int num)
{
if (num ==1)
{
return 1;}
else
{
int temp = countDown(num-1);
count<< temp<<endl;
return num+temp;
}
Let me know if this worked for you.
|
62,337,376 | 62,337,479 | An implementation of std::atomic_thread_fence(std::memory_order_seq_cst) on x86 without extra performance penalties | A following-up question for Why does this `std::atomic_thread_fence` work
As a dummy interlocked operation is better than _mm_mfence, and there are quite many ways to implement it, which interlocked operation and on what data should be used?
Assume using an inline assembly that is not aware of surrounding context, but ... | Short answer for now, without going into too much detail about why. See specifically the discussion in comments on that linked question.
lock orb $0, -1(%rsp) is probably a good bet to avoid lengthening dependency chains for local vars that get spilled/reloaded. See https://shipilev.net/blog/2014/on-the-fence-with-dep... |
62,337,659 | 62,338,792 | The quote about implicitly-declared copy constructor is unclear on logic |
The implicitly-declared copy constructor for a class X will have the form
X::X(const X&)
if each potentially constructed subobject of a class type M (or array thereof) has a copy constructor whose first parameter is of type const M& or const volatile M&
Otherwise, the implicitly-declared copy constructor will have t... | The two formulations are entirely equivalent. The standard statement is of the form if(all P) then A else B, while the proposed re-statement is simply if(exist non-P) then B else A which is logically the same.
The question raised boils down to how this works when the set all P is empty i.e. class X has no "potentially ... |
62,338,445 | 62,352,515 | Calling a lua function with it's address in C/C++? | I've been wondering if it would be possible to call a lua function in C/C++ by using it's address.
For instance,
function print2(arg)
print("Printed: "..arg)
end
print(print2) -- prints what seems like a 64 bit address.
I am not very experienced with C nor the inner workings of the lua language, so sorry if this is ... | No, you can't. Three reasons why:
The documentation says "There is no way to convert the pointer back to its original value."
Light C functions, C closures, and Lua functions have different internal representations, but all just look like function: 0x55664ffe8de0 when printed.
Even if you used some nonpublic function ... |
62,338,661 | 62,338,844 | printing nullptr with std::cout and printf | I wonder about "cout" nullptr doesn't work.
It work only once.
But "printf" work on the main function.
#include <iostream>
int main() {
const char *np=nullptr;
std::cout << "np: "<<np<<std::endl;
std::cout << "np: "<<np<<std::endl;
std::cout << "np: "<<np<<std::endl;
printf("printf np:%s\n",np);
std::cout... | It's undefined behaviour
In both cases you are printing a C-style-string (a const char *). So the implementation needs to find the length of this string and searches the terminating null character in it. But the pointer is invalid, so you get undefined behaviour.
Technically both cases are UB, but the implementation o... |
62,338,747 | 62,338,819 | String array length C++ issue? | I've understood that string arrays end with a '\0' symbol. So, the following code should print 0, 1, 2 and 3. (Notice I'm using a range-based for() loop).
$ cat app.cpp
#include <iostream>
int main(){
char s[]="0123\0abc";
for(char c: s) std::cerr<<"-->"<<c<<std::endl;
return 0;
}
B... | s is of type char [9], i.e. an array containing 9 chars (including the null terminator char '\0'). Ranged-based for loop just iterators over all the 9 elements, the null terminator char '\0' is not considered specially.
Executes a for loop over a range.
Used as a more readable equivalent to the traditional for loop
... |
62,338,767 | 62,338,938 | I am getting different answer by doing the same calculation in different ways ( which are almost similar ) in GNU C++17 | I was basically trying to find the number obtained on multiplying 2 with the quotient obtained on dividing 5e+8 with 3. I tried a couple of ways as shown in the snippet with GNU C++17 and got the correct answer only in the Approaches 2 and 4. I was first expecting it to be some sort of overflow situation however the ma... | We can verify that both the answers are in fact correct my hand.
(2*500,000,000)/3 = (1000,000,000)/3=333,333,333
and
(500,000,000/3)*2 = (166,666,666)*2 =333,333,332
This has to do with how in C++ integer division always rounds down and nothing to do with overflow. Arguably 333,333,333 is more accurate approximation o... |
62,338,955 | 62,339,734 | Forcing Dynamic Encoding only in zlib c++ library | I was wondering if it would be possible to force the zlib library (c++) to encode the compressed file in dynamic huffman only (no literal or fixed). I am looking at the Advance Functions in the zlib manual and under deflateInit2, it has the following parameters to select upon:
196 #define Z_FILTERED 1
197... | zlib does not have an option to force only dynamic blocks. Huffman-only would not guarantee that, as stored blocks would be smaller for random data.
|
62,339,623 | 62,343,427 | C++ function in python return number instead of string | C++ that creates string:
#include <iostream>
#include <string>
using namespace std;
extern "C" {
string getchars() {
string output = "";
char letters[4] = { 'A', 'G', 'T', 'C' };
for (int i = 0; i < 10000000; i++) {
output += letters[rand() % 4];
}
return output... | Have a look at this discussion. This issue seems a lot similar with
How to return char ** from C++ and fill it in a list in Python using ctypes?
It appears you need to specify the return type of the fuction in cdll.
So you need to define the result type before calling the method.
I think this should work. Otherwise hav... |
62,339,953 | 62,340,037 | C++ User-defined names for keys/values of map? | When iterating through a map (or unordered_map) in c++, the keys and values are accessed through .first and .second. But is there a way to access the key/value pairs in a more semantically meaningful way?
As an example, if I store an algebraic expression in a map< set, int> as:
x - 2yz + 3xyz --> expr = { {{'x'}, 1},... | If c++17 is available to you then you can use structured bindings to decompose the pair
for (auto [vars, coeff] : expr) { ... }
without changing anything else.
If you can not use c++17 then your Term struct can be used in a std::vector or another sequence container as you have taken away the associativity and put it i... |
62,339,977 | 62,344,284 | Estimating size required for memory mapped boost rtree | We have a scenario where we dynamically grow a memory mapped file used for boost's r-tree geometric index. We also make use of boost's interprocess memory mapped file api's.
Mechanics are already sorted out in terms of unmapping the file, growing, and remapping - this all works.
Thus far we've tried overestimating the ... | In the pure sense, the question is largely unrelated to boost-interprocess.
You want to know allocation patterns (not just net allocation volume, but also the effective "pool" use due to fragmentation.
What you could do is statistics on allocator use (good question: is there some kind of statistics-gathering allocator ... |
62,340,153 | 62,340,367 | How to mock a template class with gmock(Google Mock)? | I have a class template as following:
struct DailyQuote_t;
struct TickQuote_t;
template <typename Q>
class QtBuffer_t {
public:
virtual int size() const noexcept = 0;
};
When testing another class named OrderBook_t, the instances QtBuffer_t<DailyQuote_t> and QtBuffer_t<TickQuote_t> are both required.
class OrderBo... | Well by looking at the cook_book https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md you can in fact do it. It might be interesting maybe to check if you are using the latest version.
|
62,340,197 | 62,340,893 | Does members of class location in memory depend on the location of class members in the class definition? | I have a part of chain class
template <typename T>
class Part
{
public:
part* prev;
part* next;
T data;
}
Size of T is undefined now and i think it must be better to place it in the end in memory.
For example, if I move 8 bytes to the right, then I’ll definitely go to the beginning of the next class member (on a 64... | I can't say for sure because it is implementation-defined between various compilers...
I added this to your code:
template <typename T>
class Part {
public:
Part* prev;
Part* next;
T data;
};
template<typename T>
Part<T> makeClass(T value) {
Part<T> part{};
part.data = value;
return part;
}
int m... |
62,340,326 | 62,340,420 | uninitialized value usage, error while using sprintf or strcat | The piece of code given below works completely fine on my IDE. But when I submit this on codeforces, I get an error pointing at the sprintf line.
Probably, the solution is executed with error 'uninitialized value usage'
I used sprintf instead of strcat to concatenate two arrays as suggested from a stackoverflow answ... | You can only use strcat() if you've already initialized both strings.
Since you haven't put anything into d yet, you don't need to concatenate to it. Just copy the contents of a to it with strcpy().
strcpy(d, a);
Also, even if you have initialized d, you can't use
sprintf(d, "%s%s",d,a);
It's not valid to use the sam... |
62,340,673 | 62,341,606 | How can I maintain polymorphism when creating an instance on stack in C++? | To create instance on the heap and maintain polymorphism, and that'll give the right answer:
class Father
{
public:
virtual void Say()
{
cout << "Father say hello" << endl;
}
};
class Son : public Father
{
public:
void Say()
{
cout << "Son say h... | This is a recurring problem/dilemma: you can maintain a value semantic at the expense of some boilerplate code. Here is a minimal working example of such kind of idea:
#include <iostream>
#include <memory>
#include <vector>
class Father
{
protected:
struct Father_Interface
{
virtual void
Say() const
... |
62,340,884 | 62,341,210 | How to read multiple files in C++ one by one using a loop | Hello dear: this is my first time here and really appreciate some help.
I have this files in my folder:
name1.dat
name2.dat
name3.dat
name4.dat
...
name{i}.dat
I'd like to read them using function.
Thank you in advance.
| Like this, you didn't say how many files you have so I just assumed you have 100.
#include <fstream>
#include <string>
for (int i = 1; i <= 100; ++i)
{
std::string name = "name" + std::to_string(i) + ".dat";
std::ifstream file(name);
...
}
|
62,341,022 | 62,343,805 | REGEX error when using with `list(FILTER)` | I have a CMakeLists.txt which compiles my C++ project. The "problem" is that I used to define the source files that should be compiled like:
set(SOURCE_FILES main.cpp src/file1.cpp ... src/fileN.cpp)
add_executable(MY_PROJECT_NAME ${SOURCE_FILES})
All the *.cpp files are in the src directory. There are some cases wher... | The CMake documentation for list(filter ...) has the following syntax:
list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>)
There has never been a MATCH subcommand in this command (as there is with string()), nor is there a need to add the last argument ${SOURCE_FILES}. So, your earlier version of CMake ... |
62,341,223 | 62,517,576 | CreateService fails 0x6f7 The stub received bad data | CreateService WINAPI (tasked with creating a Kernel Driver or Windows Service) will randomly fail on some hardware with the error 1783 (0x6F7): The stub received bad data.
From the error definition RPC_X_BAD_STUB_DATA looks like this could be related to a Remote Procedure Call that may be happening on the internal side... | In my case the reason for CreateService's LastError being RPC_X_BAD_STUB_DATA, RPC_S_CALL_FAILED, RPC_S_CALL_FAILED_DNE and even sometimes ERROR_ACCESS_DENIED is because the windows firewall has blocked a Remote Procedure Call. Simply whitelisting the app or disabling the firewall fixes the issue.
|
62,341,355 | 62,346,160 | Function that sorts a vector of pairs with templated allocator and pairs | This is the function I have, it sorts a vector of pairs by the first element of the pair.
std::vector<std::pair<int,std::string>>
sort_pairs(std::vector<std::pair<int,std::string>>&& items)
{
std::sort(std::begin(items),std::end(items));
return items;
}
But when I try to generalize it to accept any type of all... | Is the fact that the underlying type is a pair salient? The body of the algorithm doesn't make use of that in any way. We can start with just:
template <typename R>
std::decay_t<R> sort(R&& items)
{
std::sort(std::begin(items),std::end(items));
return items;
}
Which in C++20 we can properly constrain by requir... |
62,341,602 | 62,341,649 | C++ iterating std::accumulate() over a map of unique_ptr: no known conversion | This is probably a case of Friday afternoon blindness... why is the accumulation over the map not working. It hands me a compile error
main.cpp:35:80: note: no known conversion for argument 2 from ‘std::pair, std::unique_ptr >’ to ‘const std::pair, std::unique_ptr >&’
What is wrong with this cast?
#include <vector>
... | The value_type of std::map is std::pair<const Key, T>; note that the key is qualified as const. So for std::map<std::string, std::unique_ptr<Foo>> the value_type is std::pair<const std::string, std::unique_ptr<Foo>>, but not std::pair<std::string, std::unique_ptr<Foo>>. Because of std::unique_ptr, a temporary std::pair... |
62,342,152 | 62,345,041 | Getting 3D world coordinate from (x,y) pixel coordinates | I'm absolutely new to ROS/Gazebo world; this is probably a simple question, but I cannot find a good answer.
I have a simulated depth camera (Kinect) in a Gazebo scene. After some elaborations, I get a point of interest in the RGB image in pixel coordinates, and I want to retrieve its 3D coordinates in the world frame.... | I assume you've seen the gazebo examples for the kinect (brief, full). You can get, as topics, the raw image, raw depth, and calculated pointcloud (by setting them in the config):
<imageTopicName>/camera/color/image_raw</imageTopicName>
<cameraInfoTopicName>/camera/color/camera_info</cameraInfoTopicName>
<depthImageTop... |
62,342,171 | 62,381,160 | How to catch the click event of checkbox which is in a listctrl cell? | Insert checkbox column on a listctrl
I made a list with a checkbox column consulting the answer above.
Now my superior asks me to disable the OK button at first, enable it when at least there is one line is checked.
I looked up seems there is easy way to catch the click event when a checkbox is in a listctrl.
| Add LVN_ITEMCHANGED to the message map. This will notify the dialog when changes are made to the list item:
BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST1, OnItemChanged)
...
END_MESSAGE_MAP()
Next, handle the message and respond each time a list item is checked or unchecked. Then... |
62,342,291 | 62,342,351 | << operator priority with string comparison | #include <iostream>
using namespace std;
int main() {
string line1("Mike");
cout << line1 < "mike" << endl;
return 0;
}
The code above is running correctly only if i use parentheses around the comparison. I think this is happening because the priority of those operations. Can somebody explain... |
that's what i'm asking. if the < has higher precedence than <<, than why the code above is wrong?
As per the operator precedence rules of C++ the bitwise left shift operator << has higher precedence than the relational operator < [emphasis mine]:
C++ Operator Precedence
[...] Operators are listed top to bottom, in d... |
62,342,616 | 62,342,643 | definition of "operator +=" behaving unexpectedly | Brief
I am defining my own String class. Everything works fine except for my definition of += which I intend to use to concatenate Strings
//expected behaviour
String c = "foo";
String d = "lala";
c+=d;
cout<<c;
Should output:
foolala
I am having an issue with it as it does seem to work correctly except for the last... | Because you didn't write any code to change c.
There is no "pointer c" and, even if there were, you'd not be overwriting it.
Your += creates a new, dynamically allocated string, using the data from the original two strings, then returns a pointer to it which your program then throws away (incidentally, leaking that new... |
62,342,804 | 62,342,948 | How to send lambda function as parameter to another function | How to write "find" function definition if I have lambda as expression:
int main() {
vector<Student> v = { Student("Pero", "Peric", "3882"),
Student("Ivo", "Ivic", "10991"),
Student("Mara", "Maric", "40911"),
Student("Ivan", "Juric", "93877"),
Student("Ivo", "... | Prototype for a find function which accept your input :
vector<Student*> find(vector<Student> & v, std::function<bool(Student*)> lambdaFct)
Obviously except if your find call if the std::find. Your question isn't very clear.
Edit after next comment :
Or template way :
template<typename Func>
vector<Student*> find(v... |
62,343,424 | 62,343,499 | Detecting if a class member exists with C++17 | 7 years ago I would write something like that:
#include <iostream>
struct A {};
struct B {
static const char* message;
};
const char* B::message = "Hello, world!";
template <typename T>
void PrintMessage(...) {}
template <typename T>
void PrintMessage(decltype(&T::message)) {
std::cout << T::message << std:... | If you know which function or member you would like to check you can create a type_trait
template<class T, class = void>
struct has_message : std::false_type { };
template<class T>
struct has_message<T, std::void_t<decltype(T::message)>> : std::true_type { };
template<class T>
void PrintMessage()
{
if constexpr (... |
62,344,047 | 62,344,273 | How to write std::chrono::high_resolution clock class template specialization only if it is not alias | I want to write class template specializations for std::chrono::system_clock, std::chrono::steady_clock, and std::chrono::high_resolution_clock.
I wrote a straight forward code as follows:
#include <chrono>
template <typename T>
struct foo;
template <>
struct foo<std::chrono::system_clock>
{};
template <>
struct fo... | You could provide an additional template parameter that depends on the condition you want to check. The primary template would be:
template <typename T, bool = true>
struct foo;
and then the specialization would be:
template <>
struct foo<std::chrono::high_resolution_clock,
!std::is_same_v<std::chrono::high... |
62,344,392 | 62,344,447 | std::endl, is there an equivalent in Python? (return + flush) | In C++, std::endl is used to add a return and flush the string.
In Python, there is no need to use this special functionality, except for specific uses.
One of the uses that may justify its use is when the output is redirected to a file, for example:
outfile = open("output_file.txt", 'a')
sys.stdout = outfile
print("So... | os.linesep is the platform-dependent line separator. If you want something shorter, you can give it an alias when you import it, e.g.:
from os import linesep as endl
|
62,344,724 | 62,344,787 | Why does strlen in a if statement behave oddly? | #include <stdio.h>
#include <string.h>
int main()
{
const char str[11]= "Hello World";
if(-1 > strlen(str)){
printf(str);
}
return 0;
}
This if condition should always return false. But here it's not.
But if I put strlen(str) value to another variable and compare with that, then it works as ... | strlen returns an unsigned type.
That has the effect of converting -1 to an unsigned type, which is a large number.
That number will be greater than the strlen result so program control reaches the if statement body.
If you assign the value of strlen to a variable of signed type, and compare using that, then the conver... |
62,344,819 | 62,402,361 | Why Glib::VariantBase::store method ruins the start of given buffer | The fun of working with Glib::VariantBase might be priceless. But brings up many obstacles with itself as well. I am having hard time to understand why the very basic Glib::VariantBase::store method is changing the start of my buffer.
Please assume i have a buffer allocated enough, better to write it down :
my_beautif... | The problem has solved with some changes in the createData method.
The method was producing a Glib::VariantBase with a{sa{s(vt)}} type, apparently packing and unpacking custom types is not really strong point of Glib::Variant.
I had to convert my object into just v type. And the problem has fixed.
This is how i have ch... |
62,344,879 | 62,345,436 | qnetworkreply no statuscode or error but failing | Im trying to find out what goes wrong when doing a get request in qt.
I have the following slots attached to my networkmanager:
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestFinished(QNetworkReply*)));
connect(mgr, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetwor... | You can get the error directly using:
qDebug() << reply->error();
This won't work if the network request never happened:
if ( !statusCode.isValid() )
Because this means that the QVariant itself is invalid and has type QMetaType::UnknownType Documentation. Hence it will not give any information about what went wr... |
62,345,199 | 64,972,015 | How to read ORC file column data | I have downloaded ORC c++ API and built it on my Ubuntu. Now I am trying to read its columns data in batch. In this reference it is mentioned that orc::ColumnVectorBatch can be dynamic_cast to specific column data type batch Like : orc::Decimal64VectorBatch. But it is not giving null pointer as dynamic cast result.
Bel... | I have resolved this problem a while ago and now I am writing an answer to my own question. Hope also helps in your code as well.
In code above it is trying to convert the bath which it reads from row_reader into an orc::Decimal64VectorBatch but the batch should first get converted into orc::StructVectorBatch. Then usi... |
62,345,460 | 62,345,483 | Prevent two methods to share the same code? | In my .cpp file for IntMatrix class, I wrote the following code:
IntMatrix& IntMatrix::operator+=(int num) {
int matrix_size=size();
for (int i=0;i<matrix_size;i++)
{
data[i]+=num;
}
return *this;
}
As you can see both operator+ functions have exactly the same code, how may I prevent that a... | Yes, you can just call the operator+ with a flipped order:
IntMatrix operator+(int scalar, const IntMatrix &matrix) {
return matrix + scalar; // calls operator+(const IntMatrix &matrix, int scalar)
}
Also, for operator+ taking an IntMatrix as the first argument, you can take the argument by value, since you are ma... |
62,345,466 | 62,345,621 | How to compile parts of code with different floating-point options? | I'm optimizing some C++ code using the Intel compiler and I need to use different compile options in some parts of code, in a single source file.
I know the #pragma pack directive can change structure members' alignment inside code but I'd like to know if there are other directives for other options.
In my case, I'm co... | You can select some floating-point options for specific functions using #pragma float_control (supported by both MSVC and the Intel® C++ compiler).
However, note the important caveat given in the linked document:
The float_control pragma doesn't have the same behavior as the /fp
compiler option. The float_control pr... |
62,346,230 | 62,359,359 | Loading a point cloud in CImg | I am trying to create a 3D CImg object from a point cloud to use the editing capabilities of CImg.
I have a point cloud that I save in ascii format
pcl::io::savePCDFileASCII("/path/data.txt", *cloud);
Then i initialize a 3d CImg object and try to load the asci file
CImg<float> image(cloud->width, cloud->height, 5);
im... | Your PCL file doesn't match what CImg is expecting. It is looking for a file that starts with:
WIDTH HEIGHT DEPTH NUMCHANNELS
float1
float2
float3
...
So, I made this example:
#include "CImg.h"
#include <iostream>
using namespace cimg_library;
using namespace std;
int main()
{
// Load image
CImg<float> imag... |
62,346,734 | 62,348,547 | Inheritance in C++ ,How to call specific function from class | In this program How to access specific function in there child class.
Class A
{
Private:
Int variables,....;
Protected:
Void funA{
};
Void funB{
};
Void funC{
};
};
Class B :public class A
{
funC();///Here I want to access only function f... | Given that you have those three classes, you can use the friend keyword to mark class C to have access to private and protected members from class A.
class A
{
public:
void FunC() {};
private:
friend class C;
void FunA() {};
void FunB() {};
};
class B : A
{
public:
B()
{
FunC();
}... |
62,347,264 | 62,347,707 | Can I use multiple main function under a project on Visual Studio 2019? | I am using Visual studio 2019 for learning C++. Every time I am crating project for each program. Is it possible to crate and run multiple main source file on Visual Studio like Java on Eclipse/Netbeans/IntellijIdea? Thank you.
| The short answer "You can't and you can".
main() is called an entry point. In Java you can have main() in every class because each class can be self-contained in theory.
C++ doesn't work like this because at the end every thing get linked to a single executable.
If you want to have multiple entry points You need to:
C... |
62,347,458 | 62,347,692 | size of template parameter pack pointer | Im a little stuck.
How would i go about getting the size of the struct inside the parameter pack loop
if i pass just the struct i get the correct size, but if i pass it by a pointer or a ref the size is always 8
struct foo_s {
int i1;
int i2;
int i3;
};
template<typename ...Args>
void Call(Args&& ...args)
... | We can remove the reference, then remove the pointer if it's a pointer type, and get the size of that:
std::size_t size = sizeof(std::remove_pointer_t<std::remove_reference_t<Arg>>);
If it's not a pointer type then remove_pointer_t will still give us T so there's no danger here.
This is of course deducing size by type... |
62,347,462 | 62,347,589 | Fix use of overloaded operator '+' is ambiguous? | I wrote the following code using C++11 standard:
.h file:
#include "Auxiliaries.h"
class IntMatrix {
private:
Dimensions dimensions;
int *data;
public:
int size() const;
IntMatrix& operator+=(int num);
};
Bit I am getting and error saying that:
error: use of overlo... | You declared the operators in the mtm namespace so the definitions should be in the mtm namespace.
Since you define them outside, you've actually two different functions:
namespace mtm {
IntMatrix operator+(IntMatrix const&, int);
}
IntMatrix operator+(IntMatrix const&, int);
When you do matrix + scalar in operat... |
62,348,007 | 62,348,165 | Given std::map with pointers to a non-constant class for keys, how to access it via a pointer to const? | There is a map of a type std::map<A*, B*> m that describes correspondence between objects of type A and objects of type B.
There is a function int exctractInfo(const A *a) that needs to read some info from an object of type B which corresponds to a given object of type A. This is a semantically constant operation, noth... |
I don't understand why it doesn't work. If the key is std::string or int, for example, I can access std::map via const std::string just fine. So what's wrong with my example?
Because there is a significant difference btw constant pointer to non constant data and non constant pointer to constant data. Your map has fir... |
62,348,184 | 62,348,767 | Vector push back function | I am Trying to push back a number in the vector for using push_back() function of vector ,function is taking the number but not adding it to the list
char p is to display the list
char a is to add a number to the list
char m is show mean of the list
Here is my code :
#include <iostream>
#include <vector>
#include <str... | You need to receive the vector by reference in operation function
operation (char selection,vector <int> list)
Change the above function to
void operation (char selection,vector <int> &list)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.