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 |
|---|---|---|---|---|
67,821,852 | 67,821,942 | Is there a way to "discard" the output argument of std::getline()? | In C, getchar() can be used to get a character from the input buffer(char c = getchar();), but it is also possible to use the function as a key press detector by ignoring the return value.
char c = getchar(); // get a character
getchar(); // detect pressing the enter key
In C++, I can use std::string in; std::getline(... | What you want is std::cin::ignore. Using
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You will pass over all of the character in the stream until you hit a newline character, thus discarding the current line.
You can change the '\n' to any other character and ignore will read until it hits that... |
67,821,946 | 67,822,740 | how'd I get the sum of all positively entered numbers | I've been trying to come up with a method to get the sum of all positively entered numbers based on the code below
#include <iostream>
using namespace std;
void myFunction(int num1, int num2, int num3) {
int x;
x = 0;
if (num1 > 0) {
x++;
}
if (num2 > 0) {
x++;
}
if (num3 > ... | as mentioned in comment you are counting not summing, but as new programmer you can think about the condition where you check if the integer is positive - for example if (num1 > 0) { // here you add sum or count depends what you want }
so i can suggest your myFunction can be like :
void myFunction(int num1, int num2, i... |
67,822,517 | 67,822,662 | define a boost::units angle in degrees | How do I define a boost units angle in degrees? The below shows radian which works and degrees which does not.
#include <boost/units/unit.hpp>
#include <boost/units/systems/si/io.hpp>
#include <boost/units/systems/angle/degrees.hpp>
// This works for defining an angle in radians
boost::units::quantity<
boost::unit... | Use boost::units::degree::degree:
my_angle_degree(2.0 * boost::units::degree::degree);
The two lines
BOOST_UNITS_STATIC_CONSTANT(degree,plane_angle);
BOOST_UNITS_STATIC_CONSTANT(degrees,plane_angle);
becomes these two static constants in the boost::units::degree namespace:
static const plane_angle degree;
static cons... |
67,823,057 | 67,823,383 | error_category mismatch in asio when used across dlls | I have a problem with handling asio::error_code values when they are received from another dll or executable. For instance, I may run an asynchronous operation with a handler:
socket.async_receive([](const asio::error_code& errorCode)
{
if (errorCode == asio::error::operation_aborted)
return;
}
If the handl... | This is what I meant with this comment
though boost::system::system_error could invite issues back
The trouble is, error categories are global singleton instances, with object identity (i.e. compared for equality by their address).
You'r ending up with multiple instances in multiple modules. The usual solution is to
... |
67,823,114 | 67,823,832 | Error: g++.exe: No such file or directory g++.exe: fatal error: no input files in Visual studio code? | There is no error in my code, and I have configured Mingw in Environment Variables but showing this error. I've created this file in Dev C++ and is running well in it. The Error is :
g++.exe: error: Calculator: No such file or directory
g++.exe: error: .cpp: No such file or directory
g++.exe: fatal error: no input file... | Your problem is the filename for your source file is Calculator .cpp which contains a space. This is problematic for languages that use command line compilers like c or c++ because on the command line a space separates arguments so without quotes around the filename your compiler sees Calculator and .cpp as 2 separate ... |
67,823,916 | 67,823,939 | How do i calculate total without manually inputting it? | I have identified that the problem is when calculating total. When i key in the value manually as 281 it works fine but i do not want to do that. So how can i solve this issue? Please help thank you. I have a added a comment in the line where the problem is.
#include <iostream>
using namespace std;
int main() {
... | total = total + mark[5];
That is wrong. mark subscripts range from 0 through 4 inclusive. You accessed an out of range index which results in undefined behavior.
double average = total / 5;
At this point, the only line that set a value for total is the wrong one above. If you removed that wrong line, total is undef... |
67,824,091 | 67,825,964 | In custom class when calling a=s+b causing s (or b) also be effected (and even when declared as constant) | So recently I'm working with my custom class which when I preform arithimetic operation it'll also effect the argument within the equation (so when called auto a=s+b will also caused s getting changed). Even when I declare those variables as const and pass arguments all with value (not reference).
So here's (part of) m... | There is no copy constructor and/or copy assignment so when you copy the coord<T> only the pointer d will be copied, not the memory that d is pointing to. This could be solved either with a constructor/assignment or by using std::vector and letting the vector handle all the memory management for you as someone pointed ... |
67,824,110 | 67,825,415 | fast c++ sign function | In my code I'm doing a sign check on a double numerous times in a loop and that loop is typically run several million times over the duration of the execution.
My sign check is a pretty rudimentary calculation using fabs() so I figured there must be other ways of doing it that are probably quicker since "dividing is sl... | As I worn you your test do not measure anything!
From your quick-bench.com link click godbolt icon and see this disassembly.
Note all of your versions are converted to this assembly code:
movabs rax, -4600370724363619533 # compile time evaluated result move outside measurement loop
.LBB0_3: ... |
67,824,111 | 67,841,526 | Error in #include <sal/main.h> when including in a c++ header | I'm working on a project to read/write to LibreOffice calc sheets in a c++ application. The code I'm writing include the line #include <sal/main.h>
In order to get the component context and so on to read/write to the .ods files.
I'm using Fedora Linux 34 with gnome 40 Wayland and code::blocks 20.03. In the project I ... | From the answer to your other post:
g++ -I${OO_SDK_HOME}/include -DLINUX yoursource.cxx
|
67,824,137 | 67,825,401 | How are static members of templated class constructed when a static function is called? | I'm trying to have a better understanding about the initialization of static members in templated classes / structs.
Let's take the following minimal example (available in Coliru):
#include <iostream>
struct A {
int value;
A(int val) : value{val} { std::cout << "A(" << value << ")\n"; }
};
struct Static {
stati... | Static initialization in C++ is a nightmare... Draft n4659 for C++17 says in 6.6.3 Dynamic initialization of non-local variables[basic.start.dynamic] §1
Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, ... |
67,824,332 | 67,824,431 | How to calculate inputted values using a while loop c++? | How do you use a while loop only to add multiple values with a given point when to exit the loop and display the tallied amounts.
Note the following example. Test your program by entering 7 for the number of items and the following values for the calories: 7 - 120 60 150 600 1200 300 200
If your logic is c... | Logic Explained
Initialize totalCalories to 0 outside the loop. This is required to prevent undefined behaviour. You may refer to (Why) is using an uninitialized variable undefined behavior? and Default variable value.
For every item, add caloriesForItem to totalCalories. You may also use the += operator if you are fa... |
67,824,342 | 67,907,661 | Does C++ static member variable has different instance in a single process? | Let us consider a C++ class with one static member variable and two static methods like :
ABC.h
class ABC
{
private:
static int val;
public:
static void set_val(int v);
static int get_val();
};
ABC.cpp
int ABC::val = 0;
void ABC::set_val(int v) {
val = v;
}
int AB... | I found the root cause...
My makefile are complicated and libabc.a has been linked twice...
After I fixed it, ABC::val only has single instance.
|
67,824,767 | 67,825,699 | MessageBox does not print UNICODE characters | I'm using the following to print a message in a Win32 API MessageBox:
MessageBox(hWnd, TEXT("Já existe um controlador em execução"), TEXT("Erro"), 0);
MessageBox is a macro and is expanding to MessageBoxW. The trouble is that it doesn't print Unicode, whereas the window that calls it prints Unicode without any issue, ... | To avoid source-code encoding based problems in the future, you can use \uxxxx style escape characters for non-ascii characters:
MessageBoxW(nullptr, L"J\u00E1 existe um controlador em execu\u00E7\u00E1o", L"Erro", MB_OK);
|
67,825,154 | 67,826,764 | Can I debug com server in Qt Creator? | I have a clipboard program that implements a COM interface(IDataObject). The com server runs correctly, i.e., the com client can connect to it and retrieve data from it without problem. The problem is the COM server cannot break at breakpoints when a COM client calls it, i.e., when a client pastes the content from clip... | if you cant add breakpoint you can still print debug messages
#include<QDebug>
void SomeClass::SomeMethod(const QString& msg)
{
qDebug() << "Message: " << msg;
}
|
67,825,183 | 67,825,326 | is there a way to use the forwarding of std::less<> and a custom compare at the same time with std::set/std::map? | If I declare std::set<std::string> I get case-sensitive comparison. If I want case-insensitive, I can write my own compare and declare like std::set<std::string,cmpi> and that works fine too.
struct cmpi {
bool operator() (const std::string& a, const std::string& b) const {
return strcasecmp(a.c_str(), b.... |
I can avoid all that by using std::set<std::string,std::less<>>
No, you can avoid all of that by using a comparison function that does asymmetric comparisons, of which std::less<> is one example (and it only works because std::string has a < comparison operator with char const*). You can just write your own in cmpi. ... |
67,825,286 | 67,829,464 | Why is this overloaded std::function parameter ambiguous? | I have the below code, where a class is trying to take one of two std::function signatures through its constructor. I'm able to get the signature that has the double parameter to compile, but the parameter-less signature fails to compile, saying the call is ambiguous.
#include <functional>
class Foo
{
public:
void b... | This question is more about std::bind than std::function.
The result of the expression
std::bind(&Foo::baz, &foo, std::placeholders::_1)
is invocable with one or more arguments, where the first argument is convertible to double.
The result of the expression
std::bind(&Bar::baz, &bar)
is invocable with zero or more ar... |
67,825,338 | 67,826,976 | c++: how to define function that accpets all the sub-class of a speciic class | Let me write the relation that A is a sub-class of B by A < B. Suppose there is a relation A < B < C between three classes.
Now, what I want to do is to define a function/class-method that can take argument of all A, B and C (all the sub-class of A). Is it possible? and if so, how can I do this?
EDIT: MOTIVATION
The mo... | void sample(A& a);
will accept anything that derives from A, but sample will only use a as if it were an A object (without casting).
With templates, you can do this without casting:
template <typename T>
void sample(T& t)
{
static_assert(std::is_base_of<A,T>::value, "T must be derived from A");
// T is whatever sa... |
67,825,433 | 67,837,147 | Remove Pointer Attribute | I have:
template<typename T>
struct is_objective_c_type {
private:
// Removes all pointer indirection.
// object*** => object
// object** => object
// object* => object
template<class U> struct remove_pointer {typedef U type;};
template<class U> struct remove_pointer<U*> ... | I ended up doing:
template<typename T>
struct is_objective_c_type {
private:
template<class U> struct remove_pointer {typedef U type;};
template<class U> struct remove_pointer<U*> {typedef typename remove_pointer<U>::type type;};
template<class U> struct remove_pointer<U* const> ... |
67,825,686 | 67,826,561 | UTF8 to UTF16 conversion using std::filesystem::path | Starting from C++11 one can convert UTF8 to UTF16 wchar_t (at least on Windows, where wchar_t is 16 bit wide) using std::codecvt_utf8_utf16:
std::wstring utf8ToWide( const char* utf8 )
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes( utf8 );
}
Unfortunately in C+... |
What kind of drawbacks can be expected from such converter?
Well, let's get the most obvious drawback out of the way. For a user who doesn't know what you're doing, it makes no sense. Doing UTF-8-to-16 conversion by using a path type is bonkers, and should be seen immediately as a code smell. It's the kind of awful h... |
67,825,840 | 67,825,866 | unknown c++ syntax in leetcode submissions | I have been seeing code like this in submissions at leetcode.com and I don't understand it. My unfamiliarity with the syntax has made it hard to search for an explanation.
static const int _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}()
I gather that the I/O calls are an effort to i... | This is lambda syntax, so what they're doing is creating a c++ lambda which performs the code above and evaluates it, then stores the result as a static const int. More information here: https://en.cppreference.com/w/cpp/language/lambda
My best guess is that this function will be evaluated first before main is called a... |
67,826,104 | 67,826,501 | C++ : the url reader function doesn't work for URL links with \ sign. pls help me | As written in the title, this is a function which returns the HTML source code string of a URL.
It works only with the main page, such as "finance.yahoo.com/". If I try a URL from one of the bookmarks in Yahoo, such as "finance.yahoo.com/quote/BTC-USD/", it doesn't work.
string getHtml() {
HINTERNET hInternet = In... | This is wrong:
HINTERNET hConnection = InternetConnectA(hInternet, " finance.yahoo.com/quote/BTC-USD/", 80, " ", " ", INTERNET_SERVICE_HTTP, 0, 0);
HINTERNET hData = HttpOpenRequestA(hConnection, "GET", "/", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0);
You can't "connect" to a URL like that, only to a hostnam... |
67,826,257 | 67,829,842 | C++ ValueError bitset::_M_copy_from_ptr when string and bitset are correct size | I have a string which should represent a 32 bit integer, so i'm creating a bitset to print the bits:
std::string str = rocksDBSlice.ToString();
std::cout << str.length() << std::endl;
std::bitset<32> bits(str);
std::cout << bits.to_string() << std::endl;
But at run-time I get:
4
ValueError bitset::_M_copy_from_ptr
If... | Constructor of std::bitset with string argument expects the string to contain only 0s and 1s. Probably your string contains values like a instead of 1100001. So if you want the 32 bits of 4 bytes of your input string to be put into a bitset, you have to convert the string to a sequence of 32 ones and zeros first.
|
67,826,517 | 67,826,690 | How to specialize a function template with iterator traits? | template <typename ForwIt>
typename std::iterator_traits<ForwIt>::value_type
foo(ForwIt begin, ForwIt end, double bar)
{
using value_type = typename std::iterator_traits<ForwIt>::value_type;
// value_type is the type of the values the iterator ForIt points to
value_type baz;
// Do stuff with the value... | You can avoid specializations, or writing another overload. Instead, you can use conditional_t to select a specific type according to some condition
// alias for convenience
using T = typename std::iterator_traits<ForwIt>::value_type;
// if T is int, value_type is double, otherwise it's just T
using value_type = std::... |
67,827,059 | 67,827,279 | Why is my function continuing even after I give it wrong input? | I made up a game called password hacker in C++, purpose is to guess the password through given hints, when I input the correct password, it works correct, and moves to the new level as well.
But it does the same even when I input wrong password as well.
#include <iostream>
void Intro(int Level) {
std::cout << "SUP, ... | Seems to me like you need to put your level up code within your win condition statement, otherwise you're telling the game to keep going regardless of the outcome.
So make Lev global, take the ++Lev out of the main function and put it in the else statement of PlayGame.
OR
Have an if statement wrapped around the ++Lev t... |
67,827,149 | 67,827,175 | Storing equal objects in a set | What I'm trying to do: order elements in the set by elem->value, but still recognize that they're distinct elements based on the memory address they're pointing to.
#include <iostream>
#include <set>
using namespace std;
struct Node {
int value;
Node(int v) : value(v) {}
};
int main()
{
Node* a = ne... | You should use the memory address for tie-break.
Example:
auto comparator = [](Node* lhs, Node* rhs) {
return lhs->value < rhs->value ||
(lhs->value == rhs->value && lhs < rhs);
};
|
67,827,203 | 67,828,003 | Computing truncated mean between two forward indicators | I have already computed the truncated mean of a vector via the function truncated_mean(std::vector& v, double trimming fraction). This function takes as inputs the vector v and the fraction that we want to remove to calculate the mean (e.g. 10% so we remove the highest and lowest 10% values and then we compute the mean... | Assuming sequence passed in is sorted you could simply use std::distance to figure out the length and skip the appropriate number of elements at the start and the end:
Edit: Extended code to use std::accumulate for random access iterators; Use concepts instead of distinguishing iterator types vis additional parameter, ... |
67,827,407 | 67,827,772 | How do I control c++ DLL debug symbols loading? | I have an EXE application running in debug mode that loads a DLL at runtime.
When I load the dll it automatically loads the dll's debug symbols for it.
But when I call FreeLibrary() on the dll the symbols won't get unloaded.
That is a problem for me because I use cl.exe to rebuild the DLL while the EXE is running so it... | The symbols are not loaded in the app itself, they are loaded in Visual Studio's debugger. The good news is that what you are trying to do works just fine as long as you are not debugging the application.
Unfortunately, there is no way to unload symbols from a debugging session (as far as I know).
One way to fix this w... |
67,827,425 | 67,827,512 | Initialize a struct from elements of a vector | I was wondering if it was possible to use a vector as the initializer list for a vector. So, if I have
struct somedata{
string str1;
string str2;
}
struct moredata{
string str1;
string str2;
string str3;
}
template<class Dataholder>
Dataholder queryUser(args){
auto vec = get_vector_from_user(a... | For the class in question, write a constructor which accepts a std::vector, or include the logic directly in the function template:
struct somedata{
string str1;
string str2;
somedata(const std::vector& vec) : str1(vec[0]), str2(vec[1]){
}
}
struct moredata{
string str1;
string str2;
... |
67,828,167 | 67,828,955 | Understanding TCMalloc's "Bytes released to OS (aka unmapped)" stat | I have a process that consumes a lot of memory on startup, but frees most of that memory after the process is bootstrapped. I see the following in the TCMalloc stats printed afterwards:
#012MALLOC: 16635888 ( 15.9 MiB) Bytes in use by application
#012MALLOC: + 0 ( 0.0 MiB) Bytes in page heap freel... | What does this value represent?
It represents the amount of memory that TCMalloc has told the system that it does not need and that the system may use for other purposes.
Has my memory been freed or not?
No. The OS has decided that making it free just to have to make it used again when the program needs it is a waste o... |
67,829,194 | 67,829,272 | Why can I use functions not exported by dll loaded at runtime | I have a rather simplistic plugin system that loads and re-loads dlls at runtime. There is no static linking invovled whatsoever.
The .exe consists only of the code necessary to load the dlls. It currently does this under Windows by using the LoadLibrary/GetProcAddress/FreeLibrary functions.
(In VisualStudio) no additi... | The addresses of virtual functions are stored in an object's vtable. You therefore don't need exported symbols to call these functions, just a valid object (or the address of one) and knowledge of the vtable's layout (which is provided by your header files).
The compiler can then index into the vtable to find the addr... |
67,829,275 | 67,829,617 | What does time_since_epoch() actually represent in a std::chrono::local_time? | I'd like to serialize a std::chrono::local_time by sending it's time_since_epoch().count() value. My question is how is a non-C++ receiver supposed to interpret that value? Is it the actual number of ticks since the epoch at local midnight (1970-01-01T00:00:00)? What about daylight saving time changes? Is the time_sinc... | The value in a local_time is the exact same value it would have in a sys_time. For example:
auto lt = local_days{June/3/2021} + 18h + 30min;
lt is a local time with the indicated value. All one has to do change this to a sys_time is change local_days to sys_days:
auto st = sys_days{June/3/2021} + 18h + 30min;
I.e. ... |
67,829,454 | 67,829,675 | Change a function's return type based on size of std::tuple | Problem
The following is a simplified, contrived example of an issue that I'm facing. Essentially, I need an object that can hold an arbitrary number of items, and return those items when needed.
template<typename... Ts>
class Foo {
public:
Foo(Ts... args) :
mArgs{std::forward<Ts>(args)} {
}
std::t... | A different approach: Use sizeof...(T) == 1 to determine whether only a single type is in use. Then use the auto return type and if constexpr to do the rest.
template<typename... T>
class Foo {
public:
Foo(T&&... t)
: mArgs{std::forward<T>(t)...} {
}
auto getArgs() const {
if ... |
67,829,696 | 67,830,147 | Using operator new and placement new to create a dynamic array of non-default constructible objects | I am new to placement new so I wanted to separate allocation from initialization using it along operator new to allocate and construct an array of my user-defined type class Foo.
here is what I've tried:
struct Foo{
Foo(int x) : x_(x){
std::cout << "Foo(int)\n";
}
~Foo(){
std::cout << "~Foo(... |
please guide me if I've missed something.
Seems fine for Foo. But more generally, the approach isn't exception safe. If one of the class constructors throw, then your allocation leaks and the previously constructed objects won't be destroyed.
And is this similar to how class allocator works?
Quite similar. A few di... |
67,829,769 | 67,829,897 | C++ - Proper way to add<T> obiect to std::vector<abstract C> in template method without copy T | A program has an interface called Component:
class Component
{
public:
virtual void Start() = 0;
virtual void Update() = 0;
};
This interface is implemented by MeshComponent:
.h
#include "Component.h"
#include "Mesh.h"
class MeshComponent: public Component
{
public:
Mesh* mesh;
int a = 0; // for test
... | template<typename T, typename std::enable_if<std::is_base_of<Component, T>::value>::type* = nullptr>
void addComponent(T component) {
Component* comp = ((Component*)&component);
// ...
arr.push_back(std::unique_ptr<Component>(comp));
// ...
}
Yeah you cannot do that. The proper way would be to copy it ... |
67,830,056 | 67,849,498 | Correct pattern for nested private class that inherit from outer class | I am trying to implement a pattern in C++ where a nested private class inherits from the outer class and the private class is instantiated via a static factory method in the outer abstract class.
I have this code now, that compiles, but I am not sure whether I did it correctly.
Search.h:
namespace ns_4thex {
class ... | A static factory method always returns a pointer type. So the create function should return a pointer or smart pointers in modern c++.
The declaration:
static std::unique_ptr<Search> create();
The definition:
std::unique_ptr<Search> Search::create() {
return std::make_unique<Search::Implementation>();
}
The complet... |
67,830,612 | 67,830,623 | in C or C++, how can I prevent previous #define in a header file from affecting another header file later included? | I think there may be no way of avoiding this but to change function/macro name, but I ask here just in case.
I have met a strange situation.
I'm trying (just started) to modify a program A (targeted for a dynamic library) so that the program uses a function in program B (this is not relevant for this question, but Prog... | Switch the order of the includes:
#ifdef USED_IN_QEMU
#include "includeB.h"
#endif
#include "includeA.h"
That way the macro in includeA.h doesn't affect anything in includeB.h.
|
67,830,881 | 67,831,207 | Overload operator delete to not delete object - valid or undefined behavior? | Preface: I'm optimizing an old codebase.
I have a class named Token for which I added caching to for a subset of the tokens (but not all). Cached tokens may not be deleted as their pointers are stored in a permanent collection in memory for the whole lifetime of the program.
Unfortunately, the codebase has delete token... | This is not OK. It is not UB to not free memory in operator delete, but it is UB to access anything inside the deleted object. delete token will first call the destructor for token, and then it will call operator delete. Even if you yourself do nothing inside the body of the destructor, once the body returns it will co... |
67,831,377 | 67,831,448 | Why does this C++ loop not run infinitely? | I was watching my friend try to solve a programming challenge and at one point, his code looked like this:
#include <iostream>
#include <string>
using namespace std;
int main(){
//Prompt user to enter string
const string SPACE {" "};
string input;
cout << "Please enter String you would like to see in a pyramid: "... | Note the comparison k < input.length(), where the input.length() returns unsigned string::size. If the k is negative, then the int will be converted and so its negative value will instead become a positive value.
If the k was -1 at that time, then this value will be the biggest value possible for the string::size. Try ... |
67,831,991 | 67,865,388 | How to pass class as a variable | I have class Point, and i'm coding Circle. Then how to pass class as variable
int main() {
Point p1(0, 0), p2(5, 8);
Circle c1(p1, 4), c2(p2, 3);
int sgd = c1.getIntersection(c2);
cout<<"intersection: "<<sgd<<endl;
}
this is class Ponit
class Point {
private:
int _x;
int _y;
public:
Point(... | I found solution for it:
class Point {
public:
int _x;
int _y;
}
and in class Circle
Circle(Point x, int s);
|
67,832,011 | 67,832,083 | Merging 3 files together, works fine when merging the same three files but when mergin 3 different files, it doesnt want to read the 3rd file | So title says it all, im trying to concatenate 3 wordlists together however for some reason it does not want to read the 3rd list,
first wordlist words:
nand
minus
second wordlist words:
nor
negative
third wordlist words:
xor
plus
void merge3(string MFile3)
{
string file1name, file2name,file3name, outfilename, word1, ... | The third file is never read, you are reading the second file again:
ifstream inFileThree(file2name.c_str());
|
67,832,012 | 67,832,069 | Stack vs Heap - Should objects inside *vector be declared as pointers? | If I use this line
std:vector<MyObject>* vec = new std::vector<MyObject>(100);
If I create MyObject's in the stack and add them to the vector, they remain in the stack, right ?
MyObject obj1;
vec->push_back(obj1);
So if it go to the stack, than MyObject's added to the vector will be gone after method ends ? What... | The std:vector as any other Standard Library container copies elements into itself, so it owns them. Thus, if you have a dynamically allocated std::vector the elements that you .push_back() will be copied into the memory managed by the std::vector, thus they will be copied onto the heap.
As a side note, in some cases s... |
67,832,033 | 67,833,290 | How to prevent users writing C++ code in common header files between C and C++ project? | We have two projects. One project is C++ (say SourceA) and other is only C (say SourceB). Both have different repository but few header files are common between them. While compiling SourceB I copy common header files from SourceA.
Since AsourceA is C++ code, I wanted user to prevent writing any C++ code in common head... | Generally if it is libraries shared among multiple project, you can place them in a "company standard" repo of their own. Then the project-specific versions of each file will be local to that project, and in case anyone make changes to the file and commits to the project-specific repo, it won't affect any other project... |
67,832,237 | 67,844,541 | Why am I getting errors when I define this C++ concept? | I'm following Josh Lospinoso's C++ Crash Course and I'm at a part where it's trying to show me an example of how to use concepts to constrain a method's parameters, and also wants me to use type_traits. However, I'm getting errors saying that it's argument list is missing and that it has an invalid combination of type ... | I didn't have C++20 enabled in MVSC. Didn't think that had to be done but it did so everything is good now.
|
67,832,859 | 67,833,157 | OOP can't get value from a class | So I read a file in a function and set values to a class. I would like to read those same values in another function (another .cpp file) and I can't get it to work.
This is the code where I read values from .txt file. This seems to work. I can cout the value that I read.
#include "branjeDatoteke.h"
#include "parametri.... | Assuming your Parametri class is correct, the issue is you are using local variables so they are initialised every time you call the function. They are allocated on the stack, locally for the calling function and can't be used outside of the function that declares them, at least not the way you're doing it. If you call... |
67,833,411 | 67,833,559 | Changing class functionality | I am learning classes and I have a task just to practice for myself, and I need to modify this class:
class Object {
// modify this
};
template <typename Object>
void test(){
Object z, y(2);
if (z.x() == y.y()){
const Object x;
if (x.y() == Object::z())
return;
}
}
int main... | Try this. Turned out somewhat messy (?). Still open to constructive criticism:
class Object {
int foo;
public:
// Both the default constructor and the one that takes an int
Object(const int &i = 1) : foo(i) {}
// Member functions
static int z() { return 1; }
int x() { return 1; }
int y() co... |
67,833,423 | 67,833,462 | error: cannot declare variable ‘t’ to be of abstract type ‘T’ | I'm learning c++ by myself and had problem to find error in class, which I didn't get.
Please help me, to find errors, I will be so glad. I know it maybe easy question.
class Base
{
public:
virtual void g()=0;
};
class T:public Base
{
public:
void func(){T t;}
T* h() const {return this;}
priv... | You have missed the definition part of virtual void g() in class T, which caused the class T to be an abstract class (Defines an abstract type which cannot be instantiated but can be used as a base class.). Add the definition of virtual void g() should work:
class T: public Base
{
public:
void func(){T t;}
... |
67,834,499 | 67,834,958 | How to properly use std::align | Is it correct that I consider std::align as a runtime address calculation to meet the further logic of my program, i.e. if the program logic doesn't take into account any specific alignment, it doesn't make sense to use std::align?
Does using of std::align affect code generation? Is my understanding correct that, unlik... | std::align is an ordinary free function. It's not a compiler hint, no magic involved. It does affect code generation as any other function possibly affect code generation, i.e. it might be inlined, reordered etc., but not in any particular way.
As to what the function does and when it is used (cppreference):
Given a p... |
67,834,814 | 67,835,417 | How to create a class specialization that does different things for floats and ints? | I want to create a struct called Vec2 which looks something like this:
template<typename T>
struct Vec2 {
T x, y;
// Other things are also there like Constructors, Destructors, operator overloads, etc.
};
I want to be able to create an operator overload for the % operator. The overload looks something like this
V... | In this case a simple if constexpr should be enough:
Vec2<T> operator%(const Vec2<T> &other)
{
if constexpr (std::is_floating_point_v<T>)
{
return Vec2<T>(fmod(this->x, other.x), fmod(this->y, other.y));
}
else
{
return Vec2<T>(this-> x % other.x, this->y % other.y);
}
}
Here ... |
67,835,443 | 67,835,513 | Storing constant string literals in a container | I've got a struct foo bar of the form struct foo { const char* s, ... }; and a std::vector<foo> v; and I want to push_back a few foo's with constant values for the s member field, i.e.
bar.push_back({ "1", /*...*/ });
bar.push_back({ "2", /*...*/ });
bar.push_back({ "3", /*...*/ });
//...
Now, if I'm not totally wrong... | This is safe as long as you only ever initialize the const char *s with string literals . They have a lifetime that is identical to the lifetime of your program.
|
67,837,059 | 67,846,097 | How to store the recursive value in my map in dynamic programing | I m trying to find the number of ways you can get from the top-left grid to the bottom right grid using dynamic programing so I m using map<pair<int, int>, int> for memoization.
When I try to insert the k value in the map it doesn't get stored in my map, only my c and r integers get stored. Why is this happening?
#incl... | The way you check for a value in the map with m1[{r,c}] will create the entry if it does not exist. When you try to add the key later with m1.insert, the value will not be added because the key already exists.
You can either replace the insert with
m1[{r,c}] = k;
or use find or lower_bound to check if the key exists. ... |
67,837,455 | 67,837,925 | What is technically a moved-from object? | According to the standard, you can only do certain things with moved-from objects. However, what is technically considered a moved-from objects?
let's say I do this:
int x = 42;
std::move(x);
int y = x; // is this ok?
std::move is just a cast to a rvalue-reference. If this reference is not consumed, does that count as... | Well, std::move(x); is simply casting to r-value reference - it doesn't do anything. But OK, assume you had this:
int x = 42;
int z = std::move(x);
int y = x; // is this ok?
Yes, it is OK and x, y, z will all be 42. Because for trivial types moving is the same as copying.
But what of other more complex classes?
In gen... |
67,838,190 | 67,984,140 | How to handle TLS handshake timeout in QTcpServer? | I'm trying to figure out how to create a timeout for the handshake process in a TLS connection in a QTcpServer.
I tried something like this in the overriden incomingConnection function:
QSslSocket * const tlsSocket = static_cast<QSslSocket*>(socket);
connect(tlsSocket, &QSslSocket::encrypted, this, [this, tlsSocket... | I ended implementing the TLS handshake timeout this way:
// We will have a handshake timeout of 30 seconds (same as firefox today)
QTimer::singleShot(30*1000, this, [this]() {
// we use dynamic_cast because this may be or not an encrypted socket
QSslSocket * const tlsSocket = dynamic_cast<QSslSocket*>(m_socket... |
67,838,245 | 67,838,496 | How to normalise a decimal into a number that is a value within a range | How can I normalise a floating point decimal in the range [0.0, 1.0] to become a number that is set between a range of max and min value? Is normalise the right word? Following what I want to do.
If I input 0.5 and the range is 0 to 10, then the output should be 5.
If I input 0.799999 and the range is 0 to 10, then the... | The term you are looking for is "Interpolation" a.k.a "Linear Interpolation" a.k.a lerp:
You can easily create a template that will do what you want:
template<typename T>
[[nodiscard]] T lerp(const T& a, const T& b, float t) {
return ((1.0f - t) * a) + (t * b);
}
|
67,839,008 | 67,844,737 | Please explain the C++ ABI | The common explanation for not fixing some issues with C++ is that it would break the ABI and require recompilation, but on the other hand I encounter statements like this:
Honestly, this is true for pretty much all C++ non-POD types, not just exceptions. It is possible to use C++ objects across library boundaries but... | Although the C++ Standard doesn't prescribe any ABI, some actual implementations try hard to preserve ABI compatibility between versions of the toolchain. E.g. with GCC 4.x, it was possible to use a library linked against an older version of libstdc++, from a program that's compiled by a newer toolchain with a newer li... |
67,839,052 | 67,839,721 | Import Sets from Excel to CPLEX | I have the following Sets:
{int} Test={1,3,6,8,10};
setof (int) Problem[Test]=[{1,3,5},{8,4},{2,6,7},{2,4},{1}];
Execution works fine. Problem look like this:
enter image description here
As I do not want to insert the numbers manually to CPLEX, I would like to import it from an ExcelFile.
Importing Test via:
{int} T... | You can do that through strings:
.mod
range r=1..4;
string temp[r][1..26]=...;
{int} set[i in r]={ intValue(temp[i][j])| j in 1..26:temp[i][j]!=""};
execute
{
writeln(set);
}
/*
which gives
[{1 2} {6} {7 8 9} {3 4}]
*/
.dat
SheetConnection sh("readarrayofsets.xlsx");
temp from SheetRead(sh,"A1:Z4");
which is... |
67,839,322 | 67,839,550 | Measure execution efficiency for compairing two solutions? | I want to measure the efficiency for two solutions for the same problem.
I don't need to include any environmental "noise" into the calculation, just I want to know which of these below solutions would perform better in a perfect world, ie.: which needs more steps to execute?
string a;
int b;
string c;
//SOLUTION A
c ... | One way is to benchmark both solutions, e.g. with QuickBench. In the chart:
you can see that second solution is faster. However, execution time of your code might also be dependent on the size and the number of the strings you try to concatenate, so take it into account. I would also recommend benchmarking whole solut... |
67,839,623 | 67,839,712 | Virtual variadic template method in interface | One cannot have a virtual template method in C++. I want to have an interface and some classes which implement it. For example:
class Logger {
public:
template<typename... Args>
virtual void Error(const std::string& message, Args... args) const = 0;
};
class ConsoleLogger : public Logger {
pu... | As much as "prefer composition over inheritance" tends to be parroted blindly, it does comes in handy here.
class LoggerImpl {
public:
virtual ~LoggerImpl() {}
virtual void dispatch(const std::string& message, std::vector<std::string> args) = 0;
};
class Logger {
std::unique_ptr<LoggerImpl> _impl;
public:
... |
67,839,925 | 67,847,234 | Could not find a package configuration file provided by "Leptonica" | I am trying to generate a visual studio 2019 C++ project from the tesseract 4.1.1 source code. Ultimately, I want to include a tesseract C++ project in my custom solution that consumes OCR results.
When I follow these steps:
Download and extract tesseract code https://github.com/tesseract-ocr/tesseract/archive/refs/ta... | There are several tutorial how to build tesseract on windows with cmake and VS e.g. https://bucket401.blogspot.com/2021/03/building-tesserocr-on-ms-windows-64bit.html (you can ignore end of tutorial - python module), minimalist tesseract or with clang
|
67,839,957 | 67,840,136 | Macro definition causing error during composition | I am trying to get the macro to print out the file name followed by the line number and then the print message, here is how I do this normally, and it works but it prints out the entire file path to the file:
#define TESTER1(...) printf(ANSI_COLOR_BOLD_GREEN "LOG::" __FILE__ ":" STR(__LINE__) "\t" ANSI_COLOR_RESET ANSI... | You can have more than one consecutive string literals and compiler will see them as one.
Example:
printf("He" "llo" "wo" "rld.");
But in your macro __FILENAME__ expands to the strrchr call + ternary operation and the result of it is not the string literal - thus syntax error.
#define TESTER2(...) printf(ANSI_COLOR_B... |
67,840,889 | 67,853,183 | GMock - Perform an action AFTER Expected calls | I am trying to perform a unit test where I need my mock object to perform an action AFTER a sequence of EXPECT_CALLS, or as an action on one of them while allowing the mocked call to return first.
Here is my non working unit test:
class MockWebSocket : public alert::QWebSocketInterface
{
public:
MOCK_METHOD(void, o... | A socket typically behaves asynchronously (i.e., signals are emitted at some indeterminate time after calling methods), but you are setting up the mock object such that it behaves synchronously (signals are emitted immediately as a result of calling the method). You should be attempting to simulate asynchronous behavi... |
67,841,307 | 67,841,436 | invalid operands to binary expression when push element in a priority queue | I'm new in c++ programming. I've to create a priority queue of a Class named Container. So I've written this way:
In main.cpp:
struct Comp{
bool operator() (const Container& a, const Container& b){
return a<b;
}
};
std::priority_queue<Container, std::list<Container>, Comp> containers;
In Container.cp... | It's telling you that your it can't calculate the difference between two iterators of type list<Container>::interator.
If you look at the requirements for priority_queue on CppReference it says that the iterators for the container "must satisfy the requirements of LegacyRandomAccessIterator."
lists iterators are not ra... |
67,841,758 | 67,841,819 | static_assert expression is not an integral constant expression with __builtin_clz | I have the following code:
typedef unsigned char uchar;
constexpr int leaing_ones(uchar const u8) noexcept {
return __builtin_clz(static_cast<uchar>(~static_cast<unsigned>(u8))) +
sizeof(uchar) * 8 - sizeof(int) * 8;
}
int main() {
static_assert(leaing_ones(0b0000'0000) == 0);
static_assert(leaing_ones... | __builtin_clz is undefined for an argument with value zero, and since you invert all the bits, 0b1111'1111 becomes the pattern of all zeroes. Your function will need to special case 0 to use an appropriate value.
|
67,841,876 | 67,842,120 | Custom comparator to segregate even and odd giving TLE | I am trying to implement the solution for this leetcode problem: https://leetcode.com/problems/sort-array-by-parity/. (i.e. segregate even and odd elements in an array)
I wrote the below solution using custom comparator in C++:
bool custom_cmp(int &l, int &r){
return l%2 == 0;
}
class Solution {
public:
vector... | Your first comparator does not meet the requirements defined by Compare since it doesn't take r's value into account (i.e. it does not properly establish a "strict weak ordering").
For example, one requirement that the first comparator violates is:
For all a, comp(a,a)==false
Which we can easily break with custom_cmp... |
67,841,901 | 67,842,140 | How to store Unicode characters in an array? | I'm writing a C++ wxWidgets calculator application, and I need to store the characters for the operators in an array. I have something like int ops[10] = {'+', '-', '*', '/', '^'};. What if I wanted to also store characters such as √, ÷ and × in said array, in a way so that they are also displayable inside a wxTextCtrl... | This is actually a hairy question, even though it does not look like it at first. Your best option is to use Unicode Control Sequences instead of adding the special characters with your Source Code Editor.
wxString ops[]={L"+", L"-", L"*", L"\u00F7"};
You need to make sure that characters such as √, ÷ and × are being c... |
67,841,907 | 67,851,803 | how to check if std::span has the required layout at compile time? | I want to check at compile time if std::span has a specific layout. The code below is what I've got so far. It doesn't work.
#include<bit>
#include<cassert>
#include<iostream>
#include<span>
#include<type_traits>
#include<vector>
template<typename T>
struct MySpan {
T* data;
std::size_t size;
};
int main() {
... | This:
std::is_layout_compatible_v<std::span<int>, MySpan<int>>;
Should evaluate as true with MSVC's implementation. It does lay out the fields in that order. That fact that it does not is an MSVC bug, which I reported here and then Casey Carter moved to here.
Casey's reduced version of my example from the test case th... |
67,841,980 | 67,842,083 | Can I distinguish touchpad and mouse messages within a low level hook proc? (Win32) | I am working on adding touchpad-specific functionality to a windows desktop application (written in C/C++). Here are my requirements:
The user shall be able to use both a standard windows mouse and touchpad simultaneously.
All touchpad HID events shall be custom-handled by the application as long as it is running. It ... | SetWindowsHookEx() hooks, like WH_MOUSE_LL, do not provide any identifying information about the devices that are generating input events. Raw Input hooks can identify devices, but they can't block input events.
So, you will have to use both kinds of hooks and coordinate them - use a Raw Input hook to identify the tou... |
67,842,004 | 67,842,092 | Resource handle const correctness | I have sometimes problems with understanding const correctness, especially if it is the logical constness of an object. Let's say I have a class that is a handle for some resource. If it is a const handle then I don't want to allow the resource to be modified through it. It doesn't own this resource, it is kinda like a... |
I just assume that if I pass something to a function as const, then somehow I should be able to enforce this logical constness.
This can lead to surprising behaviour or a constness that is un-enforceable. As you noticed, you would just have to copy the handle to have a mutable one.
This is the same problem as const p... |
67,842,385 | 67,842,556 | How to create an stl-like iterator which calls member functions | I want to provide for my API some iterators which automatically call the desired member functions to directly iterate over the returned values. More precisely consider the following struct and main function as MVE:
struct Shape
{
double getArea()
{
return ....//calculate area;
}
double getVolume()
{
ret... | In C++20, the ranges versions of algorithms can take projections on members, which pretty much gets you the ease of use you want, with slightly different syntax
std::ranges::for_each(shapes, [](const auto & area) {
// do something with area
}, &Shape::getArea);
// ^_____________^ projection on member
Here's a demo... |
67,842,444 | 67,843,030 | Modern practice to compare double/float for equality in modern C++ | if (std::abs(double1 - double2) < std::numeric_limits<double>::epsilon())
std::cout<<"Equal";
else
std::cout<<"Not equal";
Is this code with modern C++11/14/17/21 is still the way we should compare float and doubles, or now it's ok just to write
if (double1 == double2)
And compiler will handle the epsilon issue f... |
Is this code with modern C++11/14/17/21 is still the way we should compare float and doubles, or now it's ok just to write if (double1 == double2) And compiler will handle the epsilon issue for us?
Both approaches function the same in modern C++ as they did in early C++.
Both approaches are also flawed.
Using == as... |
67,842,799 | 67,842,814 | Is the destructor of a derived class virtual by-default if the base class destructor is virtual? | I was recently reading about virtual functions and virtual destructors, and the following question aroused.
For instance, I have the following inheritance chain.
class Base
{
public:
virtual ~Base() // note: virtual
{
std::cout << "Calling ~Base()\n";
}
};
class Derived: public Base
{
public:
... |
I thought that the same would apply to the destructors
It does, yes.
I would like to know, if the destructor of the derived class is virtual by-default
In this example, yes it is.
Once something has been marked virtual, all overriding descendants of that something are also virtual, whether they state it explicitly ... |
67,843,016 | 67,843,084 | Why does fstream not write to the file? | My Code:
ifstream studentList;
studentList.open("ListOfStudents.txt");
studentList << firstName << endl;
studentList.close();
Whenever I run my program it says "no match for 'operator<<' ". I have been trying to solve this issue but nothing is working.
Thanks in advance.
| std::ifstream is for INPUT ONLY (the std::ios::in flag is set), so you can't write to it.
You need to use std::ofstream instead (OUTPUT ONLY), or std::fstream with the std::ios::out flag explicitly set.
ofstream studentList;
studentList.open("ListOfStudents.txt");
studentList << firstName << endl;
studentList.close();
... |
67,843,224 | 67,845,620 | C++17 conditional (ternary) operator inconsistency between MSVC and Clang/GCC | The following code compiles under Clang/GCC under the C++17 standard, but does not compile under MSVC with -std:C++17 /Zc:ternary.
struct CStringPtr
{
const char *m_pString = nullptr;
CStringPtr() = default;
CStringPtr( const char *pString ) : m_pString( pString ) { }
operator const char *() const { r... | This is Core issue 1805, which changed ?: to decay arrays and functions to pointers before testing whether the other operand can be converted to it. The example in that issue is basically the one in your question:
struct S {
S(const char *s);
operator const char *();
};
S s;
const char *f(bool b) {
... |
67,843,563 | 67,844,528 | Font size scaling problems | I'm writing a C++ wxWidgets calculator application, and I want the font of my wxTextCtrl's and my custom buttons to scale when I resize the window.
The problems are:
The text in my buttons isn't always precisely in the center, but sometimes slightly off (especially in the green and red buttons)
When I maximize the wi... | I'm really not sure what to do about the second problem. I think setting the font size from the size event when the frame is unmaximized causes something to be done in an unexpected order and temporarily breaks wxWidgets' layout system.
The only way I've found to workaround this so far is to use WinAPI calls to inject... |
67,843,642 | 67,843,694 | Infinite while loop in std::thread raising CPU usage | I have an infinite while loop executing in an std::thread in my C++ program. When doing this, my program uses up 45% op my CPU (according to task manager). When 'throttling' the loop using std::this_thread::sleep_for(std::chrono::milliseconds(1)), the CPU usage goes down to 12%' but, of course, this solution is far fro... | You should make your thread wait for a condition variable (std::condition_variable) and notify it when changing the flag.
|
67,843,734 | 67,843,785 | How does std::unordered_map actually use hash functions? | It is not very clear to me how the standard std::unordered_map container uses hashing.
I am pretty new to hashing, and right now I'm trying to pass my university data structure exams.
I understand that if I have a collection of objects, I have to group their keys as random as possible by a criteria so that they lie as ... | For most standard library containers, the answer would be: However it feels like, it's an implementation detail left up to the writer of the library.
However, unordered_map is a little peculiar in that respect because it not only has to behave in a certain way, but it also has contraints applied to how it's implemented... |
67,844,409 | 67,861,737 | How to Setup Podofo for visual studio? | I'm trying to set up Podofo to Combining two PDF files from a vector std::vector<const wchar_t*> inputfiles;
here are my steps in detail (maybe it's very basic to many people but not to me):
download [podofo-0.9.7]
In vs2019, add #include "..podofo.h" and general/linker to COPYING.LIB settings (I'm not sure this)
buil... | Finally,
I decided to go with the easier solution of wrapping by .net or using aspose.
The problem has been resolved :)
|
67,844,411 | 67,844,572 | What rule governs rounding behavior in applying static_cast<float> to a double? | If we have a double-precision value in C++ and do a static_cast<float> on it, will the returned value always be smaller in absolute value? My intuition behind this says yes for the following reasons.
The set of possible single precision exponents is strictly a subset of double precision exponents
In converting the dou... | The standard says in [conv.double]:
A prvalue of floating-point type can be converted to a prvalue of another floating-point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination v... |
67,844,526 | 67,844,567 | ambiguous reference error for member variable 'name' | I have declared a variable name within my people class which is producing an ambiguity error. I tried renaming the name variable, avoided using using namespace std, imported the required libraries, replaced character array with string type but it throws same error all the time. I referred to other posts on Stack Overfl... | The compiler doesn't know which member 'name' should use in the strcpy function since lecturer inherits from 2 classes which are manager and staff (both have member 'name'), so to tell the compiler who's name should use, to assign manager's name, you can use:
strcpy(manager::name, a);
and for staff's name:
strcpy(sta... |
67,844,586 | 67,844,660 | Changing the Value of a paired item in a Map Data structure having a list of items as a value | I could you some help. I have a unordered map data structure, where each map item (key) is a list of (node,value) pairs. see data structure below.
I am changing the value of a paired item in a list using an iterator, but it's not working.
I am wondering how I can get the value changed.
typedef std::unordered_map< st... | When you use =, and the left-hand-side is not a reference, you are creating a copy of what's on the right side of the =. Thus what is occurring is that you're working on a copy, and not the original item.
Unlike other popular computer languages such as Java, in C++, the = does not automatically use references. If you... |
67,844,706 | 67,844,738 | C++ access control not working for templated objects | Problem
Here's a contrived example of a problem I'm facing. I have a templated object with a map function that creates a new object and operates on private (or protected, it doesn't matter) members within that new object.
template<typename T>
class Foo {
public:
template<typename R>
Foo<R> map(std::function<R(s... | I figured it out.
You need to declare your current class as a friend of itself.
template<typename T>
friend class Foo;
The entire thing looks like this:
template<typename T>
class Foo {
public:
template<typename R>
Foo<R> map(std::function<R(std::optional<T>)> &&function) {
auto mappedValue = function(... |
67,844,829 | 67,844,876 | Declare a variable to be instantiate at a class level, and used inside the class functions | Let's say I have this class. How should I declare/instantiate the image object so that I can use it with all functions without the need to pass it as an argument?
view.h
class AAView : public QGraphicsView {
public:
explicit AAView();
QGraphicsScene* currentScene;
QImage image;
};
view.cpp
AAView::AAView(... | You appear to be trying to call the QImage constructor for image, but that's not the correct syntax.
You can replace it with the following line inside the constructor
image = QImage(sizeX, sizeY, QImage::Format_RGB32);
or preferably construct it in a member initializer list
AAView::AAView() : image(1280, 720, QImage::... |
67,845,312 | 67,845,349 | C++ Cannot print vector of string element | Why I can't print third element of my vector ?
I'm need a words that will be divided to vector and after that, they will be printed.
But my third element of vector isn't showing in the terminal.
#include <iostream>
#include <vector>
using namespace std;
void divideTextCommand(string txt, vector<string> cmd)
{
str... | You are currently not providing a reference to command:
void divideTextCommand(string txt, vector<string> cmd)
// ^ this is a copy, original is not edited
I would suggest you simply return your command:
std::vector<std::string> divideTextCommand(std::string txt) {
std::vector<st... |
67,845,535 | 67,845,675 | Implementation dependent-type | when I start to look the library about boost; I see some typedef as follows:
using size_type = /* implementation-defined */;
or something like
typedef implementation_define iterator;
how can I understand the expression here.
In my basic knowledge the typedef expression should be like this
typedef typeA ... |
how can I understand the expression here
You aren't meant to; that's why the comment is there.
Boost documentation is often written like pages from the C++ standard: not so much documentation as a specification of behavior.
What is specified is how a system behaves. If some behavior of the system is defined to be "im... |
67,846,096 | 67,846,130 | Using variables declared in main within blocks | I am experimenting with an online compiler, but I keep getting errors when I try to run the below program, stating that the variables were not declared in scope. I am declaring them in main() and then using them in a loop, and I don't understand why this error is occurring. I would greatly appreciate any help in unders... | C++ is a strongly-typed language, and requires every variable to be declared with its type before its first use
You are never declaring the variables value and sum in your entire program before using it.
Fix
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int value = 0;
while(valu... |
67,846,191 | 67,846,221 | lvalue required as left operand of assignment when returning a pointer to a private member variable | I'm trying to make a Linked List with an iterator class. I want to set the node in the iterator class to the head of the linked list. Basically, to be able to type something like:
iterator it;
it.currentHead = head;
This works if currentHead is public, however since it's private, I add a function in the iterator class... | returnCurrent() returns currentNode by value, so even if you could assign a new value to the returned pointer (which you can't), it would not update currentNode. For that, returnCurrent() would need to return currentNode by reference instead, eg:
Node<T>*& returnCurrent() { return currentNode; }
Then it.returnCurrent(... |
67,846,943 | 67,846,996 | Derived class nested inside base class - C++ | I am trying to transform the following JAVA code to C++ code. But unable to figure out how.
abstract class Base {
static class Derived extends Base {
// attributes
Derived(/*params list*/) {
// code
}
}
When I try to do something like below, the compiler says Base is not complete until ... | This can be done. Just add a forward declaration to the body of Base and move the definition below the definition of Base:
class Base
{
class Derived;
public:
virtual ~Base() = default;
protected:
Base() = default; // only allow initialization for subclasses to make this "abstract" without introducing a pur... |
67,847,001 | 67,847,096 | unique_ptr array access Segmentation fault | When I access array elements through unique_ptr, a segfault occurs,Through vs debugging, I found that the type and data of std::unique_ptr<T[]> p is strange,I think it should be an array, but it looks like a string,No matter how many elements I push, the data of p points to "to", and other elements cannot be seen.
cod... | Note that p[N] has type std::string& for T = std::string, so what
p[N] = nullptr;
does is call std::string::operator=(const char*) with parameter nullptr. This is not a parameter you're allowed to pass to this assignment operator; it expects a 0-terminated string.
Edit: Improved based on suggestion by @Remy Lebeau
You... |
67,847,187 | 67,847,238 | Runtime Error when using vec.size() in the for loop | While solving a codeforces problem, I had to make a vector of size=1. Also, I needed to iterate back from the second last element of the vector, so I used the following technique to use for loop.
for(int i = vec.size()-2; i > -1; i--){
vec[i] = vec[i] + vec[i+1];
}
This technique throws runtime error at codeforces... | Here, you trying to access vec[-1], which leads to out of range subscript.
Try to run this and look for output:
for(int i = vec.size()-2; i >= -1; i--){
cout << i << endl; // At some point will be -1
vector<int>::size_type j = i; // Then this will be a very large unsigned number
cout << j << endl; // On my ... |
67,847,415 | 67,847,743 | How can I make template codes using member-Function | class A
{
public:
A* m_child;
A* m_brother;
int x;
A(int num) :x{ num } {};
public:
template<typename Pred, typename...Args>
void ForFamily(Pred, Args&&... args) {
if (m_child) Pred(m_child*, std::forward<Args>(args)...);
if (m_brother) m_brother->Pred(std::forward<Args>(args)...... | Use a member function pointer as the first parameter of the member function. Note that I also added default initializations to the pointers to avoid undefined behavior, if those members are not initialized:
class A
{
public:
A* m_child {nullptr};
A* m_brother {nullptr};
int x;
A(int num) :x{ num } {};
p... |
67,847,555 | 67,848,568 | What makes the overload fail between these two function templates? | Below is the pretty short example.
#include <utility>
template<typename T, typename = void>
struct A {};
template<typename T, typename U>
void f(A<std::pair<T,U>>) {}
template<typename U>
void f(A<std::pair<int,U>, std::enable_if_t<std::is_same_v<int,U>>>) {}
int main() {
A<std::pair<int, int>> x;
f(x);
}
The ... | Even though this is language-lawyer, I'm going to provide a layman explanation.
Yes, the second overload fixes the first parameter of pair as int, while the first one doesn't.
But, on the other hand, the first overload fixes the second parameter of A as void, while the second one doesn't.
Your functions are equivalent ... |
67,847,897 | 67,848,265 | segmentation fault when trying to set a button's label inside a lambda function | I've been trying to learn gtkmm4, but I've run into a strange runtime error
My Code:
#include <gtkmm.h>
#include <iostream>
class MyWindow : public Gtk::Window
{
public:
MyWindow();
};
MyWindow::MyWindow()
{
set_title("Basic application");
set_default_size(200, 200);
Gtk::Button button("Hello Wor... | You have a dangling reference to the local Gtk::Button variable, which is deconstructed at the completion of MyWindow's constructor. Try making button a member variable of your MyWindow class.
|
67,848,312 | 67,848,608 | c++: Casting void pointer to shared_ptr | I'm implementing(overriding) the index function in a QAbstractItemModel derived class, qt treeview MV, where a cast to pointer looks like:
TreeItem* parentItem = static_cast<TreeItem*>(parent.internalPointer());
Where internalPointer is void *QModelIndex::internalPointer() const
How should I change the code to cast th... | Since you say shared_ptr is supposed to take ownership of the pointer (delete it automatically), you want this:
std::shared_ptr<TreeItem> parentItem(static_cast<TreeItem *>(parent.internalPointer()));
Or, to assign to an existing shared_ptr:
parentItem = std::shared_ptr<TreeItem>(static_cast<TreeItem *>(parent.interna... |
67,848,348 | 67,860,401 | There is a given element say N. How to modify Binary Search to find greatest element in a sorted vector which smaller than N | For example:
Let us have a sorted vector with elements: [1, 3, 4, 6, 7, 10, 11, 13]
And we have an element N = 5
I want output as:
4
Since 4 is the greatest element smaller than N.
I want to modify Binary Search to get the answer
| What would you want to happen if there is an element that equals N in the vector?
I would use std::lower_bound (or std::upper_bound depending on the answer to the above question). It runs in logarithmic time which means it's probably using binary search under the hood.
std::optional<int> find_first_less_than(int n, std... |
67,848,419 | 67,849,182 | Why does getline reads only the first stroke? | My program should read commands and do them with one number. It should +, -, /, * the number, but it reads only the first stroke.
ifstream fin("file.txt");
string line;
while(getline(fin,line))
{
if(line[0] == '+')
{
for(int i = 1; i < 10; i++)
{
n... | You found out alread by yourself. You must either clear the std::istringstream or define a new one, even with the same name. So you coud write
ss.clear(); // Clear EOF bit
ss.str(std::string()); // Clear buffer
before the next insertion operation, or, you simply define a new variable every time by writing:
... |
67,848,435 | 67,848,612 | Why the element of a Two-dimensional array in range based for loop is T* instead of T (*)[n]? | There is my code
int array[3][4] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (auto line : array)
// something
Why the type of line is int * instead of int (*)[4]?
I have looked for reference about the range-based for loop, and I'm using C++ 11, so the corresponding source code is
{
auto && __range = range_ex... | In your example __begin is of type int(*)[4]
range_declaration is the dereferenced value of __begin, therefore in your example range_declaration is of type int*.
In your example, the line variable is the range_declaration.
If we remove the syntactic sugar, your code looks like this:
int array[3][4] = {{1, 2, 3, 0}, {4,... |
67,848,525 | 67,848,564 | Correct way to override what() from std::exception | I have the following custom exception:
#ifndef BLATT4_OUTSIDESEABOUNDS_H
#define BLATT4_OUTSIDESEABOUNDS_H
#include <exception>
namespace GameObjects {
class OutsideSeaBounds : public std::exception {
public:
[[nodiscard]] const char * what() const noexcept override;
};
}
#endif
#include "Outsid... | The code is fine, your IDE is being silly.
A style note: [[nodiscard]] seems quite out of place here, even if not technically wrong it is not going to help anyone.
|
67,848,579 | 67,848,684 | Packing multiple values into a “key” | I was reading an article on draw call buffers in game engines: https://realtimecollisiondetection.net/blog/?p=86
Such a buffer holds the draw calls before they are submitted to the GPU and the buffer is usually sorted before submitting according to multiple values (depth, material, viewport, etc.).
The approach in the ... |
how this is implemented in practice
The article mentions bitfields, which are like this:
struct S {
unsigned viewport : 2;
unsigned depth : 24;
unsigned material : 10;
unsigned unused : 28; // always some fixed value like zero
};
Then when you want to compare two of them, just use memcmp(&s1, &s2, 8)... |
67,848,884 | 68,595,582 | C++ compiler support for std::execution (parallel STL algorithms) | I wanted to use the parallel version of std::sort where I can specify an execution policy like std::execution::par_unseq.
I'm currently using clang++-10 and g++ 7.5.0 under Ubuntu Linux, but both don't find the required include file execution, so apparently the parallel algorithm is not yet supported in these compiler ... | C++17 execution policies are supported by GCC 10 and Clang 11.
Here is a demo example https://gcc.godbolt.org/z/xahs5x1Kx
#include <execution>
int main()
{
int a[] = {2,1};
std::sort(std::execution::par_unseq, std::begin(a), std::end(a) );
return a[0];
}
|
67,849,288 | 67,851,540 | Converting JavaScript function to C++ | I was working on a Dynamic Programming Problem and was able to code up a Javascript solution:
function howSum(targetSum,numbers,memo = {}){
//if the targetSum key already in hashmap,return its value
if(targetSum in memo) return memo[targetSum];
if(targetSum == 0) return [];
if(targetSum < 0) return nu... | Here is my take at it:
#include <optional>
#include <vector>
#include <unordered_map>
using Nums = std::vector<int>;
using OptNums = std::optional<Nums>;
namespace detail {
using Memo = std::unordered_map<int, OptNum>>;
OptNums const & howSum(int targetSum, Nums const & numbers, Memo & memo) {
if (auto iter = m... |
67,849,326 | 67,849,430 | Why is there inaccuracy in the following intermediate type conversion? | The following example is from the page 14 of the book Discovering Modern C++, Peter Gottschling. The author states:
To illustrate this conversion behavior, let us look at the following example:
long l = 1234567890123;
long l2 = l + 1.0f - 1.0; // imprecise
long l3 = l + (1.0f - 1.0); // precise
This leads on the autho... | A float is typically 32 bits. How do you think it achieves greater range (max value ~3.4e38) compared to the same-sized int, for which the max value is ~2.1e9?
The only possible answer is that it can't store some of the integers on the way to the max value. And the gaps between representable numbers increase as the abs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.