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,069,928 | 62,070,102 | Copy vector of shared_ptr to derived classes of abstract base | I'm trying to copy the object instances of derived classes from a vector<shared_ptr<base>> to a new vector<shared_ptr<base>> where the base class is abstract. I want the new vector to contain shared_ptr to copies of the objects, not the original objects.
I've tried this:
class base
{
public:
base(){}
virtual vo... | One way to solve this is to make a pure virtual clone method on the base class which returns a pointer - subclasses override this to allocate a copy of themselves.
class base
{
public:
virtual std::shared_ptr<base> clone() const = 0;
};
class derived1 : public base
{
public:
virtual std::shared_ptr<base> clone... |
62,070,041 | 62,070,085 | Boolean dynamic memory allocation cannot be delete | include <iostream>
int main()
{
bool a=new bool;
delete a;
return 0;
}
I try to delete the boolean malloc, but so far it keeps giving me the error that bool type expression cant be deleted
| You can't perform delete on bool, you should delete the pointer instead.
bool* a=new bool;
delete a;
In your code, a is a variable with type bool, it's initialized from the pointer created by new bool, which could convert to bool implicitly; false for null pointer, true for non-null pointer.
|
62,070,189 | 62,070,792 | CMake can't find protobuf when compiling Google's protobuf example | I am trying to solve this problem for 2 days now with no luck. I've read an endless number of threads allover the web and tried a lot of suggestions but so far with no luck.
I'm doing this on Windows 10 with VS2017 and most recent VS Code installed. I installed protobuf with vcpkg install protobuf:
The package protobu... | Fair warning I am no expert.
I ran in to a similar problem in my own build trying to get Boost working and I think it has to do with your environment variables and how you have your Visual Studio setup. While you are setting crucial things such as
SET(PROTOBUF_INCLUDE_DIR "d:/vcpkg/packages/protobuf_x64-windows/include... |
62,070,473 | 62,070,864 | Check if two arrays are equal or not ?? eg: {1,2,3,4,5} == {4,5,3,2,1} | Is there any problem with this approach ? or is it fine? we have to tell whether 2 arrays are equal
as in the digits in them and their frequencies must be same irrespective of their order.
#include<bits/stdc++.h>
using namespace std;
main(){
int t,n,i,in;
vector<int> x;
cin>>t;
while(t--){
unordered_map<int,int... | I don't know how new you are to C++, so here is a possible solution with a few explanations.
#include <map>
#include <vector>
#include <iostream>
//Avoid using namespace std as it can cause problems with conflicts of names
//and other sorts of nasty issues
using std::cout;
using std::cin;
using std::map;
using std::v... |
62,070,643 | 62,071,087 | How do I run specific functions based on tags in C++? | I am writing a test framework that will run hundreds of tests. Each of these tests has been written as an independent function. Currently, I have my main function run each of these tests one-by-one. What I would like to make is a system that uses tags. For example, I want to be able to run all the tests with the 'W... | The reason your research has gone badly is that "tag" is a very broad, general term that doesn't really describe what you're doing.
Fundamentally, you're trying to map two pieces of data together; that's it really. Doesn't matter whether one of those pieces (your "tag") is an integer, an enum member, a string, a class ... |
62,070,705 | 62,070,870 | Is there a way to get a complete string with spaces in c++? | So, i have a piece of code (c++) that gets the users name (in windows) and with the retrieved string the code creates respective directories...
BOOL DirectoryExists(const char* dirName) {
TCHAR nameu[UNLEN + 1];
DWORD size = UNLEN + 1;
if (GetUserName((TCHAR*)nameu, &size))
{
TCHAR* t = nameu;
... | You have a lot of redundant and unnecessary string copies.
I'm fairly certain this is what you want to have:
wchar_t nameu[UNLEN + 1];
DWORD size = UNLEN + 1;
if (GetUserNameW(nameu, &size))
{
dir[0] = L"C:\\Users\\" + std::wstring(nameu) + L"\\Documents\\Folder";
}
Ideally dir[0] is of type wstring, not string. ... |
62,070,997 | 62,073,037 | CMake Package Support - Includes and Libraries not found | I am currently developing a software package, for which I'd like to provide the cmake package support (so users can find it with find_package(...)). The Problem is, the package is found but FOO_INCLUDE_DIR and FOO_LIBRARIES is empty.
Within my package I have several modules, each with a CMakeLists file which installs t... | Why would FOO_INCLUDE_DIR or FOO_LIBRARIES be set? This may be how old find modules worked, but not how config files work. Even newer find modules expose targets instead of directory variables.
When generating an XYZConfig.cmake file, informations about targets will be exported, not informations on the directory.
With ... |
62,071,269 | 62,085,363 | Function call inside OpenMP for loop | I have the following for loop, which contains a private function call inside of it:
for (i = 0; i < N; ++i)
dates[i] = to_time_t(&string_dates[i][0]);
to_time_t simply converts a string (e.g.: "18/03/2007") into a timestamp, and it does so with the help of mktime(), which is really slow. In fact, that for loop alo... | The problem is in mktime() which has a process-wide side effect. From the manual page:
Calling mktime() also sets the external variable tzname with information about the current timezone.
mktime() calls internally tzset(). The latter is serialised via a mutex lock, but what really slows it down in the multithreaded c... |
62,071,498 | 62,071,531 | Is vector.push_back(vector.back()+1) undefined behavior? | I want to append a new value to a c++ std::vector and this new value is relative to the last value in the vector. Can this code result in undefined behaviour?
std::vector<int> vector;
vector.push_back(1);
vector.push_back(vector.back() + 1);
| The vector isn't empty, so you're not invoking undefined behavior because of that.
The parameter to push_back is fully evaluated before the call is made, so that's not undefined behavior either.
|
62,072,005 | 73,369,870 | How to pass comma-separated options to the g++ linker with VSCode? | I need to pass the arg -Wl,-Bstatic,--whole-archive to g++.
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "shell: g++.exe build active file",
"command": "C:\\MinGW\\x86\\bin\\g++.exe",
"args": [
"-g",
"${file}",
... | I originally answered this question (like a dumb dumb) as if you were using Linux, so I deleted that answer and included a new one for PowerShell.
This is sort of a common problem when dev's use GCC with Powershell. The problem is that PowerShell is very programmatic in the way it implements its interface, and the way ... |
62,072,134 | 62,073,596 | Using future<> and promise<> for message passing? | I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work. The intent is to pass 10 objects from the produce to the consumer. Unfortunately, I'm running into compilation issues. Does anyone know where I have gone wrong?
Thank you!
Update solution.
#include <iostream... | The error is due to future being only movable but not copyable
for (auto p : futv) - this is an attempt to copy elements fro vector.
Use the following loops to have reference to vector element instead:
for (auto& p : futv)
or
for (decltype(auto) p : futv)
Generally the idea may work as an exercise, but promises/future... |
62,072,423 | 62,072,507 | I need better understanding on for loops | can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5 int main(){
6 int n, a , b , ma=0,mb=1000000001;
7 cin >> n ;
8 cin >> ... | This code smells a lot. If you give to n the value 10,it gives
9 (first time into loop, exectues n--)
every other iteration it executes --n till when n!=0 (which is the condition n
|
62,072,516 | 62,072,703 | Retrive Values From Enum | How can i recieve a specific value from an enum from a given index.
enum genre { Pop, Jazz, Classic}; //enum
struct album
{
string album_name;
genre kind;
int track_number;
string tracks[5];
string tracklocation;
};
void main()
{
album x1;
cout<<"Enter genre 0->pop, 1->Jazz, 2->Classic\n"... | You can't put the identifiers (names) of an enum to cout. For example, the value of the name Pi in enum, suppose it's set to 3.14. You directly wants the user would type that value, it'll show the string Pi in output stream, but no, it's only within supposed within the code. Enumeration just holds the constants.
By def... |
62,072,563 | 62,073,047 | C++ library related queries | What does the inside of a library look like?
Are the different function codes just stored in there in different blocks one after another like in a C++ program as follows?
function1_name (argument_1, argument_2)
{
//function_1 code
}
function2_name (argument_1)
{
//function_2 code
}
.
.
.
.
| An executable is something that can be run directly and it can contain many functions in it, but one of them is the "entry point". We can see the entry point as the function that it is first run (there are a few things that can run before - read this for more info). In C/C++ the entry point is the main function.
On the... |
62,072,588 | 62,072,657 | Include header file or cpp file | I have a class.h file and a class.cpp file that has the implementations of methods in class.h.
The class.cpp has an #include < class.h> statement. In my main.cpp, should I include < class.h> or < class.cpp>?
| You should include the ".h" file (Header file).
A header file is a file which contains the function declarations and macro definitions to be shared between the source files ".cpp".
|
62,072,654 | 62,072,772 | static_assert type of a private class member, with no instance | I would like to statically assert whether a private class member type outside of the class:
class Human
{
public:
int getInt() const {return myInt;}
private:
int myInt{0};
};
However, I don't have an instance of the object at the location i'd like to assert.
I tried:
static_assert(std::is_same<... | There is std::declval which helps in such cases:
static_assert(std::is_same<decltype(std::declval<Human>().getInt()), int>::value);
|
62,072,774 | 62,072,879 | Why there is no supported iterators for some STL containers (Stack, Queue, Priority Queue)? | Across all types of iterators, why there is no supported pattern for stack, queue and priority_queue STL containers ?
#include <iostream>
#include <stack>
#include <algorithm>
int main(){
std::stack<int> values;
std::stack<int> valuesCopy;
values.push(98);
values.push(11);
values.push(14);
v... | The three are not classic containers, but rather container adaptors. They do not need to support the iteration. A quote from the "C++ Programming Language" book:
Container adaptors provide specialized access to underlying
containers.
They are:
intended to be used only through their specialized interfaces. In parti... |
62,072,866 | 62,079,847 | C++ insertion operator for class method | In C++ is there a way to use the insertion operator for a class method?
This operator<< overload is working:
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
Complex() {};
~Complex() {};
};
I can d... | One easy way to pick a different << overload is to use a different type.
#include <iostream>
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
struct extra_info {
const Complex& parent;
ex... |
62,073,117 | 62,165,748 | Scatter/Gather like Numpy in ArrayFire | I want to scatter and gather elements from an array X at specific indices along one axis.
So given an array of indices idx, I want to select the idx(0)th element along the 0th column, the idx(1)th element along the 1st column, etc..
In Numpy, the following statement:
X = np.array([[1, 2, 3], [4, 5, 6]])
print(X[[0, 1, ... | X
[3 2 1 1]
1.0000 4.0000
2.0000 5.0000
3.0000 6.0000
idx
[3 1 1 1]
0
1
1
ArrayFire does Cartesian product when af::array are involved. Hence, the output.
Please see the below indices because of that.
Col\Row 0 1 1 from array
0 (0, 0) (... |
62,073,193 | 62,074,958 | How can my class be provided some information about its environment? | Here's a code sample I wrote with encapsulation and composition in mind:
class Bullet {
private:
Vector2 position;
Vector2 speed;
public:
void move(float time_delta) {
position += speed * time_delta;
}
};
Basically, there's just a projectile moving in nowhere. However, a bullet can actually e. g. ricoch... | From a design point of view, it is probably best if your bullet doesn't know how to detect when it's ... passing_through an obstacle (scnr). So it might be better to turn your Bullet class in to a struct, i.e. have it behave like a thing that is acted upon instead of a thing that acts.
You can still add your convenienc... |
62,073,288 | 62,073,750 | Does holding a C++ reference prevents variable of being destroyed? | Coming from a Java/C# background I am trying to implement kinda a null safety check object. The following code tries to check if there is indeed a color on the object. If there is, I want be able to do some stuff (like drawing the color on a shape). I want to be able to set this color back to null (noneColor), preventi... | Given that
MyShape::color is declared as a Color&
... the code is a bit problematic.
The thing to know about C++ references is that you can't re-seat them -- that is, unlike a C++ pointer, once a C++ reference is declared, it will always reference the object it was declared to reference, and cannot be re-directed to... |
62,073,698 | 62,074,356 | Does using string_view lead to an unnecessary string copy in this scenario? | What I'm trying to do is have my class accept a string during construction. I read that string_view was a replacement for const string& so naturally I wrote a constructor like this. This allows me to accept c++ and c strings.
Url::Url(boost::string_view raw_url)
: url_(static_cast<std::string>(raw_url)) {
The prob... | Note: I'll write the answer considering std::string_view, but boost::string_view should be similar.
I read that string_view was a replacement for const string&
It is useful to understand the reason why std::string_view was added in the first place.
What is the problem with const string&?
It is certainly efficient ... |
62,073,998 | 62,074,125 | std::stoi only converts first few characters | I am using stoi in one of my functions with the intent of converting a string of numbers into an integer. I was about halfway through a homework problem but then I ran into this. Oddly, if the number has an even number of characters, stoi only converts the first half. Any help would be greatly appreciated!
Code:
#inclu... | Your code has undefined behavior because in this line
temp.push_back(temp[i]);
you are accessing temp out-of-bounds. You can see this by adding a line
std::cout << "check " << i << " " << temp.size() << "\n";
just before that line.
Output will be (see here):
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
check 1 1
check 0 2
1... |
62,074,229 | 62,076,472 | Float distance for 80 bit long double | For float, double, and __float128, we have the following code which computes the number of representables between them:
int32_t float_distance(float x, float y) {
static_assert(sizeof(float) == sizeof(int32_t), "float is incorrect size.");
int32_t xi = *reinterpret_cast<int32_t*>(&x);
int32_t yi = *reinterp... | You can do it using the properties of the floating-point representation provided in the numeric_limits template of the <numeric> header and routines in <cmath>. No examination of the bits representing the values is required. Here is sample code in C++.
#include <cmath>
#include <cstdint>
#include <numeric>
/* Retur... |
62,074,285 | 62,074,574 | packaged_task example problem? Stroustrup example modification | I'm trying to modify the example given in Stroustrup C++ 4th Ed Page 122 to call the accumulator() function directly with iterators. Specifically remove use of *double and use iterators.
So far, I have this, however it has compilation problems which I don't understand.
Does anyone have any pointers on accomplishing th... | std::accumulate is not a function, it's a function template. To construct the packaged_task, you need to pass it a concrete function, like this:
packaged_task<Task_type> pt0 {accumulate<vector<double>::iterator, double>};
packaged_task<Task_type> pt1 {accumulate<vector<double>::iterator, double>};
You should also make... |
62,074,532 | 62,074,571 | Errors because of vector<string>? | Sorry for the spaghetti code, I don't have much experience with C++ (or coding in general for that matter) but here is my code... Also first time posting on stack overflow so apologies for improper formatting.
I have been scouring the internet for the last 4 hours. Please tell me this is a simple fix.
I have tried usin... | Your using namespace std comes after your inclusion of Program_2.h, so the SandwichMaker class is defined without using namespace std being in effect.
You thus need to write std::vector, not vector, and std::string, not string.
Note: Do not try to "fix" this by applying using namespace std earlier - that's a bad idea a... |
62,074,730 | 62,075,360 | What is this "fixing the build scripts" for compiling x264? | I am trying to compile an all static build of source-customized ffmpeg libraries with the additional codecs from VideoLAN, such as their x264 codec. I am ultimately building for use in Windows with Visual Studio 2015 C++, so I am comparing a few compiling guides for my instructions.
In the guide linked below (I locate... | All this manipulations with "config.guess" and "configure" are only needed because later on they run simple "msys2_shell.cmd" i.e. in MSYS-mode. Correct/supported way in x264 is to run shell in MINGW32 or MINGW64 mode with "-mingw32" and "-mingw64" options like you do (or run mingw32.exe / mingw64.exe instead of msys2_... |
62,074,778 | 62,074,837 | Why is my C++ program always throwing exception even if the user's input is ok? | What am I trying to achieve?
My goal is to make a program which will throw an exception and end the program everytime when input of type char is not either a, b or c and it should give following exception message: "You can't enter nothing else except a,b,c".
Where am I stuck at?
Even though user's input is a, b or c ex... | if (odgovor1 != 'a' || odgovor1 != 'b' || odgovor1 != 'c')
Those should be && operators. Think of what happens when you enter a. You will get:
false || true || true
which is true. In fact, you'll get true for every character since a single character cannot ever be all of a, b, and c at the same time.
However, there'... |
62,075,258 | 62,075,444 | How does enable_if help select specializations of a class template? | I have a basic grasp of SFINAE, and I think I understand many of the examples of how std::enable_if exploits it to select function template specializations, but I'm having a hard time wrapping my head around how it works for class templates.
The following example is from cppreference.com's explanation of std::enable_if... | From the reference on partial specialization of class templates:
When a class or variable (since C++14) template is instantiated, and there are partial specializations available, the compiler has to decide if the primary template is going to be used or one of its partial specializations.
If only one specialization ma... |
62,075,326 | 62,076,051 | Delete vs Delete[] in a custom operator in C++ (different than common delete vs delete[] questions) | I define a class called MyNewDeleteAllocator and define custom new and delete operators for the class. This code has no bugs whatsoever and works perfectly fine. However, I have a question about line 29 of my code. It seems that changing "delete[]" to "delete" does not change anything in my code results.
I am aware of... | First of all, this is not an allocator, or your name convention is wrong. In C++, an allocator allocates memory for a given type, not for raw bytes. More on that - https://en.cppreference.com/w/cpp/memory/allocator
Second, don't mix malloc()/delete and new/free(). malloc() should be used with free(), new with delete, n... |
62,075,362 | 62,075,450 | Is it possible to pass parameters into a function using a switch statement in c++? | Is there any way to pass parameters into functions using switch statements in c++? What I am trying to achieve is turning a series of if statements into one switch statement.
As an example, I'd like to turn this:
if (function(a)) {
//code
}
if (function(b)) {
//code
}
if (function(c)) {
//code
}
into this:
sw... | That is not how a switch is used. It would need to look more like this instead:
switch (someValue)
{
case value1:
function(a);
break;
case value2:
function(b);
break;
case value3:
function(c);
break;
}
If that is not what you are looking for, then the ?: operator may work for you, depending on what your i... |
62,075,469 | 62,075,747 | How to find seg fault which doesn't occur when using tools | I ask this because the seg fault doesn't occur in my C++ program if I run it with Valgrind or GDB. But it's easily reproducible once I run it stand-alone as it will seg fault without fail. I have commented out sections of code to the point of making it run, but I have still been unable to find the exact cause. I fear i... | Make sure you're not disabling core dumps (ulimit -c unlimited, though there are other config options that are relevant), then when your program crashes, you should get a core dump file.
Run gdb program core to analyze the core dump -- gdb will look like you've used it to run your program and it hit the signal that sto... |
62,075,973 | 62,076,231 | How do I determine what a function will be called if it's virtual and when it is not? | Look at this excerpt of a program.
I see that cout << obj->foo(); call is not polymorphic. Actually, it is obvious, because it has no virtual specificator.
But I am confused with cout << ((B*)obj)->foo(); Why the program does not use the B's definition of virtual function and will call the third version of foo()?
#in... | Because ((B*)obj)->foo(); behaves by design like B* b = (B*)obj; b->foo() and calls C::foo. You may call the base's method explicitly like ((B*)obj)->B::foo();.
#include <iostream>
using namespace std;
class A{
public:
int foo(){ return 1; }
};
class B: public A{
public:
virtual int foo(){ retu... |
62,075,974 | 62,076,050 | static_cast seems to work when it can't possibly work | In the following code I use static_cast<B*> on a void*, which points to an A object.
A and B are not related in any way. I understand the compiler cannot raise an error against this. But what I don't understand is, how come this actually seems to work when run...? I would expect a segfault or an error of some kind.
#in... | The code causes undefined behaviour (because it dereferences a B * which does not point to a B object), which means anything can happen. You should not expect any particular subset of consequences.
To find out what your compiler did, you could inspect the assembly. My guess would be that the compiler generated assembl... |
62,076,035 | 62,191,775 | Measure actual runtime of a procedure using Qt | I want to measure the runtime of a procedure that will last multiple days. This means the executing process will be interrupted many times since the Linux PC will be suspended to standby repeatedly. I don't want to include those sleep phases in my time measurement so I can't use simple time stamps.
Is there a better wa... | As G.M. proposed, I used boost::timer::cpu_timer time to solve my issue. It returns the summed up computation time and the run time of the entire process which is fine for my purpose. Boost is not Qt but it is cross-platform anyway.
|
62,076,358 | 62,077,317 | Is .thenValue() blocking? | In a lot of places I find something like :
std::move(A).thenValue(B)
Is thenValue() blocking on the future "A". I read through Folly documentation but couldn't understand it.
https://github.com/facebook/folly/blob/master/folly/docs/Futures.md
| No, it is not blocking. Conceptually, you can think of the signature like this (though this is not the actual signature):
template <typename T>
template <typename TResult>
Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
The basic idea is that if the future represented by std::move(A... |
62,076,620 | 62,076,670 | What does a C++ preprocessor do when there's just a single `#` in a line - and nothing else? | Is this a valid line of C++? What is it supposed to mean?
#
What about this one:
# // a comment
Recent compilers seem to ignore it without errors nor warnings.
Does it "do nothing"? I have a header file where a "compatibility" section bombs out when compiled with g++ 7.4.0 in presence of such lines. It doesn't seem t... | Both examples are valid, and they do nothing.
For the second example, first the comments are removed in translation phase 3:
... Each comment is replaced by one space character. New-line characters are retained. ...
which results in the first case, which is a preprocessor directive that is expanded in translation pha... |
62,077,391 | 62,312,694 | What is the c++ equivalent to BP's Class Reference? | I am converting BP to C++ and the variable in question is a Class Reference;
What is the C++ equivalent?
TSubclassOf? Type* -> StaticClass()?
I know I am overthinking this.
| The equivelent would be TSubclassOf however to get a reference to a specific class you would use ClassName::StaticClass() so for example if you wanted a drop down that allowed for all Pawn types but defaulted to MyGameCharacter the code would be:
UPROPERTY(BlueprintReadWrite, EditAnywhere)
TSubclassOf<APawn> PawnType;
... |
62,077,429 | 62,077,459 | Executing function pointer from a in std::vector iterator | I'm trying to write an application that adds function pointers to a vector based on some external event, then iterates through the list. For some reason, I can't seem to get the functions to actually execute despite the fact that they are added to the vector.
What am I missing?
main.cpp
#include "GameLogic.h"
GameLogi... | You are dereferencing the vector iterators to access the stored std::function objects, but you are not actually calling their operator() to execute your class methods. You need to add an extra set of parenthesis for those calls, eg:
(*it)(*this);
This is made clearer if you store the std::functions to a local variabl... |
62,077,486 | 62,079,554 | What does creating a Solution using a template in Visual Studio actually do versus an empty project? | I am following the Intro to C tutorial by Molly Rocket but am running into an issue running the following code in the Debugger in VisualStudio 2019 while using the Empty Project option.
I am using the Empty Project option instead of loading a template because that is what Molly used, while I could just load a template ... | When you create an Empty Project, the value of SubSystem defaults to Console.
According to the Doc
An application that uses /SUBSYSTEM:CONSOLE; calls main (or wmain)
An application that uses /SUBSYSTEM:WINDOWS; calls WinMain (or
wWinMain), which must be defined to use __stdcall
As far as I'm concerned you should S... |
62,077,564 | 62,078,773 | How i can change the top of my stack in C++? | Whats is wrong in this code, i need to change the top of my stack.
That's is my code and i need to change the top of my stack
Also, i need to change my function imprime to print from the bottom to the top.
Something like 10 15 20, in the function pilha_imprime will print 20 15 10.
I need to understand how do that i'm ... | Some functions are easier to write recursive, printing the stack backwards is one of them;
void imprime(No* no) {
if (no != NULL) {
imprime(no->prox);
printf("%0.2lf\n", no->info);
}
}
/* vai imprimir da base para o topo usando uma funções já definidas*/
void imprime(pilha* p)
{
imprime(p->... |
62,077,775 | 62,077,991 | How to determine payload size from header? | I want to send() body and header which has body size from the Side A.
On the Side B, in the first recv() header to determine the size of payload. The second, recv() body.
I tried to use recv() twice but could not through the second recv() function.
Side A
struct CommandHeader_t {
int BodySizeByte;
};
void Send()
... | There are some mistakes in your code:
On the sending side, you are not doing pointer arithmetic correctly when assigning the body_ptr pointer. As header_ptr is declared as CommandHeader_t*, doing (header_ptr + sizeof(CommandHeader_t)) will calculate a memory address that is sizeof(CommandHeader_t) number of CommandHea... |
62,077,786 | 62,082,638 | C++ Thread does not detect global variable change | I have 2 threads monitoring the same global state, if the state.shutdown becomes false, the thread run() should return. The code is below.
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
using namespace std;
struct State {
bool shutdown = false;
~State() {
shutdown = true;
... | You have a data race on shutdown.
When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race [...]
In shut() you set the shutdown flag using a mu... |
62,077,796 | 62,078,121 | Is an init-declarator a prvalue expression | int c = 0;
Consider the above code,thereof,c = 0 is an init-declarator and it's also an expression,Becuase of these rules:
init-declarator:
declarator initializer(opt)
A full-expression is:
[...]
an init-declarator or a mem-initializer, including the constituent expressions of the initializer,
As long as a... |
Consider the above code,thereof,c = 0 is an init-declarator and it's also an expression
That's not how C++ parsing works. c = 0 by itself may be an expression (if it is within a context where expressions are allowed), but that's not how int c = 0; gets parsed. You have to follow the actual C++ grammar rules.
int c = ... |
62,077,945 | 62,082,974 | VS2013: fatal error C1001: An internal error has occurred in the compiler | The code is quite simple:
int main(void){
return 0;
}
and the compile error goes:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\userdata\zdck\documents\visual studio 2013\projects\project1\project1\source.cpp : fatal error C1001: An internal error has occurred in ... | The error C1001 related to compiler file p0io.c is mainly caused by enabling Use Unicode UTF-8 for worldwide language supportin Region Settings. You could see the link about the concrete reason. You could click Time &Language -> Region-> Additional date, time, ®ional settings-> Region-> Administrative->Change system... |
62,078,438 | 62,225,063 | How to remove transformations from a matrix | I have a Transfromation matrix , which is combination of three other transformation matrixes.
glm::mat4 Matrix1 = position * rotation * scaling;
glm::mat4 Matrix2 = position * rotation * scaling;
glm::mat4 Matrix3 = position * rotation * scaling;
glm::mat4 transMatrix = Matrix1 * Matrix2 * Matrix3;
if sometime later... | In short you may simply multiply by the inverse of Matrix1:
glm::mat4 Matrix2And3 = glm::inverse(Matrix1) * transMatrix;
Order of operation is important, if you wanted to remove Matrix3, you would need make transMatrix * inverse(Matrix3) instead. If it was Matrix2, you would need to remove matrix1 (or 3) and then matr... |
62,078,935 | 62,078,968 | Data not insert in MySQL databae | I'm Try to connect with MySQL database with qt by using this code. I'm successfully Build the MySQL plugin for Qt. But when I try insert data QT it display message box data not inserted. Is any problem with query or something?
This is register.h
#ifndef REGISTER_H
#define REGISTER_H
#include <QDialog>
#include <QtSq... | You are using the wrong names to bind to
qry.prepare("INSERT INTO user_reg_elec (username, password, fullname, address, teli)"
"VALUES (:username, :password, :fullname, :adress, :telephone)");
qry.bindValue(":lineEdit", username);
should be
qry.prepare("INSERT INTO user_reg_elec (username, pas... |
62,079,212 | 62,079,265 | C ++ How to change the value of 4 bits in a 32 bit number | I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.
I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.
How can I do this in C++?
Here is an example code I have been trying.
#include <iostream>
#include <bitset>
using namesp... | First, mask the original bits out to make sure they are zeroed and won't interfere with the value, you are going to "or" there:
x & 0xffff0fff
Then "or" the new bits into place:
(x & 0xffff0fff) | (0x2 << 12)
|
62,079,369 | 62,082,200 | Top Down Approach for this dynamic programming problem | Here is the problem-
You are given array B of size n. You have to construct array A such that 1<=A[i]<=B[i] and sum of the absolute difference of consecutive pairs of A is maximized ,that is, summation of abs(A[i]-A[i-1]) is maximised.You have to return this cost.
Example B=[1,2,3] A can be [1,2,1],[1,1,3],[1,2,3] In a... | Actually I found the solution using only two states idx and flag
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll n,k;
ll dp[100002][2];
ll b[100005];
ll solve(ll idx,ll flag)
{
if(idx>=n-1)
return 0;
if(dp[idx][flag]!=-1)
return dp[idx][flag];
ll val=(flag==1)?b[... |
62,079,517 | 62,104,443 | why dynamic initialization occur before static initialization in gcc | #include <iostream>
struct NonConstant{
NonConstant(int v):v_(v){
std::cout<<"NonConstant\n";
}
int v_;
};
struct Constant{
constexpr Constant(int v):v_(v){
if(v_==0){
std::cout<<"Constant\n";
}
}
int v_;
};
NonConstant a = 2; //#1
Constant b = 0; //#2
int m... | b has dynamic initialization, not static initialization.
As already explained by your quote of [basic.start.static]/2, b has static initialization only if the full-expression of its initializer, which is the execution of the Constant(int) constructor, is a constant expression.
In [expr.const]/2, we read:
An expression... |
62,080,481 | 62,080,667 | The compiler doesnt show errors but I get no output. Whats wrong? | I'm supposed to write a small code that generates a random number between 2 and 100 and then checks if its a perfect number. I don't get any bugs from the compiler but the output doesn't show my cout lines like " x is a perfect number". Can someone help me with finding the reason?
#include <iostream>
#include <ctime>
#... | There are three problems in your PerfectCheck function. First, you don't initialize the sum variable, so it can start off with any value whatsoever; you should set it to zero explicitly in the declaration.
Second, your for loop starts with t as zero, and you check x % t. The modulo operator implicitly involves a divisi... |
62,081,156 | 62,083,853 | How to change the color of a QGraphicsRectItem | I can't find where I'm doing wrong. I want to change the color of my item (a QGraphicsRectItem) when a particular event occurs. The fact is that it seems that once the override paint method is called, the color won't change no matter what. This is a simplyfied code of what I've done:
item.h
class Item : public QGraphic... | If I understand properly your question, the problem is that after item->setBrush(Qt::red), your circle is not being painter red. If this is the case, the problem is that you are forcing a specific pen (Qt::NoPen) and brush (Qt::red) in your paint function, and you are not using Item::pen() and Item::brush() to retrieve... |
62,081,665 | 62,081,751 | runtime polymorphism and dynamic_cast need clarification | Might answered some where else, but could not found right phrase to ask
so hear it goes.
I have base class A, with child B and C; (completely for training purpose)
#include <iostream>
class A
{
public:
virtual void print () { std::cout<< "A::print()" << std::endl; }
};
class B: public A
{
publi... | This behaviour has nothing to do with dynamic_cast.
The behaviour of a virtual call will always depend on the actual runtime type of the value. In your second example, the only thing actually constructed is a C, so all calls will resolve to C, whether you call it an A: A * a = bPtr or a B: B * b = bPtr, it will resolve... |
62,082,049 | 62,082,218 | Avoiding undefined behaviour: temporary objects | I've written a class for using it as a convenient view e.g. in range-based fors. Overall, it is just a pair of iterators with bound checking:
template<typename I> class Range {
private:
I begin;
I end;
public:
Range(I const begin, I const end)
: begin(begin), end(end)
{}
Range<I>& skip(int const amount)... | In ranged-based for loop the range-expression is bound to reference as (prototype code)
auto && __range = whole(vector).skip(1) ;
The problem is the temporary created by whole(vector) is destroyed immediately after the full expression, the reference __range (which binds to the returned reference from skip, i.e. the te... |
62,082,103 | 62,327,682 | SFML massive performance loss when sf::Window is not created | I am writing an app drawing multiple figures and comparing images (counting pixels values). Drawing and counting thread doesn't display any image. Gui is implemented in another thread.
Currently, I have found very strange anomaly. My drawing and comparing thread works very slow, but when I add before main loop sf::Wind... | I have opened an issue on SFML github and found out that it was caused by activating and deactivating context, so in this case instead of:
sf::Window window(sf::VideoMode(200, 200), "SFML");
should be
sf::Context some_context;.
Original issue link:
https://github.com/SFML/SFML/issues/1672
Full answer:
"When sf::Rende... |
62,082,104 | 62,082,491 | How to extend the functionality of vector class as well as its iterator C++ | I would like to find a clean way to slightly change the way std::vector operates.
Problem background
I need to be able to have index in the vector where the pointer would essentially slip one back, so for example; if my vector contains {0,1,2,3,4,5} and index [3] needs to slip, when iterating through the vector it shou... | I would never inherit from std::vector publicly. It is just too easy to be used wrong and you have no control over misuse. std::vector has no virtual destructor!
Iterators seems to be the appropriate customization point. Much more is needed to get a fully compliant iterator, but this is enough for a working example:
#i... |
62,082,192 | 62,082,569 | Make a ping function with QTcpSocket | I want to make a ping function with Qt (and don't like the QProcess execution system ping way).
Here's the demo code,
void SimmplePing(const QString& sAddress, int port=80)
{
QTcpSocket messenger;
messenger.connectToHost(sAddress, port);
if (!messenger.waitForConnected(3000))
{
qDebug() << messe... | The main difference here is that the ping command as it's normally used, uses the ICMP protocol which doesn't use TCP for communication. Trying to connect to a host via websockets using TCP is handled in a different way. If the TCP socket of the host you're trying to connect to doesn't listen on the specified port, in ... |
62,082,381 | 62,085,239 | How to debug C++/C programs on VsCode | I am using the gcc/g++ compiler using msys64 and mingw64 with VsCode. I've attached the bash.exe of mingw64 to my VsCode terminal. I can run my programs on the bash terminal using g++ file_name.cpp && ./a.exe.
But how do I debug my programs?
| Actually debugging in VScode is a bit tricky. Have you followed the methods here-
https://code.visualstudio.com/docs/cpp/cpp-debug
|
62,082,814 | 62,146,554 | How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server | I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors.... | Instead of this:
try
{
boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
acceptor.bind(ep);
acceptor.listen();
auto sock = acceptor.accept();
std::thread t([&sock]() {
hearbeatSender(sock);
});
process(sock);
t.join();
}
Use... |
62,082,836 | 62,083,277 | How can I reduce the function template specializations? | I'm trying to write a property validator to be used in UE4, using their reflection system.
I first came up with this:
class FDataValidator
{
public:
FDataValidator( UObject & object, TArray< FText > & validation_errors ) :
Object( object ),
ValidationResult( validation_errors.Num() == 0 ? EDataVali... | UFloatProperty and other numeric types seem to inherit from TProperty_Numeric<T>.
So something like this might be a solution:
template <typename T>
FDataValidator& FDataValidator::GreaterThan<T>(const FName property_name, const T value)
{
return CompareProperty<TProperty_Numeric<T>, T, std::greater<T>>(property_nam... |
62,083,151 | 62,083,192 | `Vector.erase()` does not work for vector of classes | I've made a class of gym pass that has expiration date (int expiration), price for the pass (float price) and name of its' holder (string data). It also has services (char services), where 0 is basic, 1 is with free showers and 2 is VIP room.
Here's the definition of class:
class GymPass
{
int expiratio... | std::vector::erase takes an iterator not an index as the argument.
Stali_Klienci.erase(Stali_Klienci.begin() + i);
is a reasonable hack. Stali_Klienci.begin() is the iterator to the first element, the + i increments the iterator to the ith element.
If you want to remove every element from a std::vector then clear does... |
62,083,469 | 62,095,362 | How to produce a sectional view of 3d-mesh by CGAL | I am running CGAL's 3d mesh examples and modifying them in my own way. But I want to have cut views of those generated meshes just like what CGAL website displays, but CGAL doesn't seem to have given any suggestion of software or code examples to do so. Any ideas to help me out?
| I'd just write the mesh out to a file and use ParaView. They have the crinkle clip feature you're looking for.
|
62,083,483 | 62,085,327 | C++ menu sfml center all things | enter code sf::FloatRect textRect = text.getLocalBounds();
//Font
if(!font.loadFromFile("arial.ttf")){}
//Tło - trzeba załadować
if(!texture.loadFromFile("bg_menu.png")){}
//play
mainMenu[0].setFont(font);
mainMenu[0].setFillColor(sf::Color::Blue);
mainMenu[0].setString("Play");
mainMenu[0].setCharacterSize(40);
main... | If you want to center any image or text then
sf::Vector2f position;
position.x = ((windowSize.x - imageSize.x) / 2.0f);
position.y = ((windowSize.y - imageSize.y) / 2.0f);
This works for images whose origin to the topleft of the image
|
62,083,518 | 62,083,953 | Is there a STL algorithm that finds last but that it also works on pointers? | I have existing code where I can not switch to iterators.
Still I would like to use STL if possible to find the last item(or first if you consider we are iterating from end).
Is that possible?
std::find_end beside being worst named algorithm ever seems quite ugly to use(I would need a fake 1 element sequence and bina... | The correct way to find the index of the last element in a container (including c arrays) is using std::find with reverse_iterators (For bidirectional containers) just like you have tried but with less UB (&arr[6] is UB).
using std::begin;
using std::rbegin;
using std::rend;
bool arr[6] = {...};
auto it = std::find(rb... |
62,083,735 | 62,084,256 | Difference between Game Engine vs Physics Engine vs Geometric modeling kernel | "The rendering engine generates animated 3D graphics by any of a number of methods (rasterization, ray-tracing etc.).
Instead of being programmed and compiled to be executed on the CPU or GPU directly, most often rendering engines are built upon one or multiple rendering application programming interfaces (APIs), such ... | Geometric modeling kernel is a modeling kernel, it allows constructing or modifying geometry and has nothing to do with displaying this geometry on the screen. It also differs from model sculpturing applications, because the latter ones are used by artists, while modeling kernels are used by engineers, and hence, has v... |
62,083,818 | 62,084,037 | How to call parent non virtual function in c++ multi inheritance? | class VA {
public:
virtual void print() = 0;
};
class VB : public VA {
public:
virtual void bprint() = 0;
};
class SA : public VA {
public:
void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
public:
virtual void bprint() { std::cout << "SB" << std::endl; };
};
in... | It looks like you are trying to make VA an interface in Java sense: no data, only some methods which have to be implemented only once in the hierarchy.
Short version: use virtual inheritance for VA: : public virtual VA.
Long version follows.
Multiple inheritance in C++ by default creates independent paths to all base o... |
62,084,342 | 62,084,788 | How to find the highest number of passenger of all round? | im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.
#include <iostream>
#include<cstring>
#include<algorithm>
usin... | You can initiate stops as an array I guess(int stops[turn]) as C++ now offers to allocate memory this way even inside any function. That may solve your problem.
Alongside you will have to check corner cases as your highest_total variable may provide garbage value. So while declaring the variable assign a value to it. ... |
62,084,838 | 62,085,385 | Invert a Eigen::VectorXd and assign to another Eigen::VectorXd | so I stumbled upon this compilation issue with Eigen. I'm using Eigen 3.3.4 and compiling on Linux with gcc 8.4.0.
Basically I have a defined class inheriting from Eigen::VectorXd which looks like this
class dVector : public Eigen::VectorXd {
public:
dVector() : Eigen::VectorXd() { setZero(); }
dVector(int ... | operator-(dVector) doesn't exist but Eigen::VectorXd is a public base of dVector and therefore Eigen::operator-(Eigen::VectorXd) is chosen for -a.
This operator does not return an Eigen::VectorXd but a wrapper type convertible
to Eigen::VectorXd. This wrapper type is not convertible to dVector as it is needed to be con... |
62,086,328 | 62,094,244 | How to build boost with correct paths | I tried to build boost in a separate path on my Ubuntu 18 Linux system. I cloned the GIT repository since I want to have the latest version available (the package repositories provide an old version only). The library I want to use is boost::timer.
This is what I did:
git clone --recursive https://github.com/boostorg/b... | Ok, when reading the build output carefully even a fool like me could notice that the actual path is boost/stage/lib. All built libs can be found there.
|
62,086,472 | 62,103,017 | Error in comparing two std::chrono::time_point instances | I have two std::chrono::time_point instances in variables exp and time. exp has a time in the future and time is the current time. But when I compare them as in this snippet:
std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std:... |
t_exp is -4243023785
This value of time_t corresponds to 1835-07-18 22:16:55 (assuming the Unix epoch and a precision of seconds, neither of which are specified by the standard, but are common).
Apparently the implementation of ctime on your platform can't handle dates this far in the past, which is a little surprisi... |
62,086,516 | 62,087,716 | Fast method to access random image pixels and at most once | I'm learning OpenCV (C++) and as a simple practice, I designed a simple effect which makes some of image pixels black or white. I want each pixel to be edited at most once; so I added address of all pixels to a vector. But it made my code very slow; specially for large images or high amounts of effect. Here is my code:... | This answer assumes you have a random bit generator function, since std::random_shuffle requires that. I don't know how xor128 works, so I'll use the functionality of the <random> library.
If we have a population of N items, and we want to select groups of size j and k randomly from that population with no overlap, we ... |
62,086,918 | 62,088,127 | std::time_point from and to std::string | Am trying to replace some boost::gregorian code using c++20 std::chrono, hoping to remove the boost build depedency. Code is reading and writing to json (using nlohmann) so ability to convert dates to and from std::string is critical.
Using g++ 9.3.0 on Ubuntu 20.04. 2 compile-time erorrs, one on std::chrono::pars... | C++20 <chrono> is still under construction for gcc. I've seen no public ETA's for it.
Your syntax for std::chrono::parse looks correct. If you're willing to use a free, open-source, header-only preview of C++20 <chrono> then you can get it to work by adding #include "date/date.h" and using date::parse instead.
Note t... |
62,086,976 | 62,087,379 | For loop crashes program while trying to read array c++ | Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.
Lets say s = 4 and A =... | Passing variable as array size is not valid you need to use constant const int n or create dinamic array int* arr = new int[n];, that array will be created in runtime, and you can pass variable as it size. Dont forget to delete that array whet it goes out of scope delete[] arr;
|
62,087,533 | 62,087,789 | Clang analyzer potential memory leak - false positive | I have an implementation of static function in my codebase, and while running clang-tidy on it, I noticed that the static analyzer points towards a possible memory leak when I am pretty sure the code is correct. (I have verified it with sanitizers). I think this is most likely due to static analyzers missing some branc... | The reporting from clang-tidy is definitely a bit weird and could use some clarification.
It's upset about the placement-new of Inner<T> without seeing a matching explicit destructor call. You have this strange destroy() method that isn't even necessary since the Base destructor is virtual and the implicit Inner destr... |
62,087,590 | 62,087,868 | faster arithmetic operations in C++ | In a function containing expensive operations such as floating-point division, sqrt or cbrt, are there any ways to specify the accuracy of the result in order reduce computation time? I.e. if I am happy to have a result that is within +/- 0.01 of the correct answer, or within 5%, is there a way to specify this?
| There is no standard way to control accuracy in c++.
The best way might be to roll your own implementation based on the accuracy needs of your project. For example it is possible to use a look-up table instead of trigonometric functions, or other functions if the range of input is small. It is also possible to use a le... |
62,088,106 | 62,088,464 | Overload of a nested template function | I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.
I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:
template<typename T>
void print(T const& ... | You can also use SFINAE (or C++ Concepts, if you live in the future) to get the result you want without having to know how many template params your incoming container has. Here's an example using trailing return types to do SFINAE:
#include <iostream>
#include <vector>
template<typename T>
auto print( const T& cont )... |
62,088,208 | 62,088,503 | imageLoad glsl always return 0 in compute shader OpenGL 4.3 | I know that there is another question with exactly the same title here however the solution provided over there does not work for my case.
I am trying to access pixel value from my compute shader. But the imageLoad function always returns 0.
Here is how I load the image:
void setTexture(GLuint texture_input, const char... | Either the internal format of the texture does not match the format which is specified at glBindImageTexture or the format argument is not a valid enumerator constant, when the two-dimensional texture image is specified, because format is used twice, for the internal format and the format (see glTexImage2D):
glTexImag... |
62,088,236 | 62,130,039 | how do I register an invisible window class in a Win32 console application? | I am trying to register an invisible window in a Win32 console application. My goal is to listen for Raw Input in the WindowProc to (1) display it on the console, and (2) perform additional computation e.g. sending information over a Web socket. I followed this CodeProject article, but my WNDCLASSEX registration seems ... | In approach 1:
You need to initialize wndclass:
WNDCLASSEX wndclass = { 0 };
Otherwise, the uninitialized part defaults to random values(Undefined behavior, usually like 0xcccccccc), and RegisterClassEx will failed with error code: 87.
In approach 2:
You initialized all the members in wndclass, so the RegisterClassEx ... |
62,088,651 | 62,089,026 | Call member function of non-active union member | Does calling foo in the following code leads to UB?
using vec = std::array<int, 1>;
struct field0 {
vec data;
operator int() {
return data[0];
}
};
union a {
struct {
vec data;
} data;
field0 x;
};
void foo() {
a bar;
std::cin >> bar.data.data[0];
std::cout << bar.x... | Your code has undefined behavior. The initial common sequence rule wont help you here since you are not accessing a common member but instead you are accessing the entire object in order to call the member function1.
What I am trying to achieve is well-defined version of common approach to name array field like uni... |
62,088,946 | 62,091,768 | Send a user-defined Windows-message through JNA | I want a simple but hard thing: to send a specific user-defined Windows-message from the JNA side in order this message to be catched by a message-loop (GetMessage()/DispatchMessage()) on the C++ side and that message loop will be then interrupted. Actually it should be performed by the button click in Swing GUI. My qu... | When mapping WINAPI functions with JNA, you must take care to exactly match the Windows API definitions with appropriate Java/JNA types. Some of your mappings are wrong. The last two arguments to SendMessage are a WPARAM and LPARAM, which you appear to be using in your sendInterruptMessage() mapping. These are calli... |
62,089,006 | 62,097,718 | unable to call a function on an object in a vector of objects | I have a class called AI which has a save function:
void save(string name) {
string fileName = "AIs/"+name+".AI";
ofstream mySave;
mySave.open(fileName);
mySave << "id\n" << id << "\n";
mySave << "pid\n" << pid << "\n";
mySave << "numInpNds\n" << numInpNds << "\n";
mySa... | I managed to fix the error by moving my vector definition beneath my class definition.
|
62,089,110 | 62,089,290 | Get a line of space-separated integers from stdio without knowing how much they are (C++) | I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:
int n; // nu... | std::vector<int> is basically a dynamically-sized array of ints. You can keep adding stuff to it and it will grow as necessary. If you are given a number of elements as the first input, you can do something like:
std::vector<int> items;
int count;
std::cin >> count;
// Preallocates room for the items. This is not ne... |
62,089,162 | 62,169,312 | Langford Sequence - Utilize symmetry / Remove symmetry | i've written a Programm that can calculate the Number of Possible Langford sequences (https://en.wikipedia.org/wiki/Langford_pairing).
TL;DR Langfordsequences are defined by L(s,n) where s is the amount of occurences of a certain number
and n is the amount of possible numbers/colors
the numbers define how many positio... | L(s, n) is "up to reversal of the order" see e.g. https://oeis.org/A014552 .
This means e.g. that for |L(2, 4)| we have
4 1 3 1 2 4 3 2
and
2 3 4 2 1 3 1 4
are both satisfying the property, but one is just the reverse of the other so |L(2, 4)| = 1.
To take this into account in your algorithm, you can check e.g. at th... |
62,089,698 | 62,089,907 | Value of -faligned-new in GCC | I had an issue similar to this one
gcc over-aligned new support (alignas )
so I added -faligned-new compiler flag.
This fixed a compiler warning. However, when the compiler is run with --verbose flag, I get this output https://pastebin.com/X2QZAtSb, in which the most important line is
COLLECT_GCC_OPTIONS='-o' 'main' '... |
What does -faligned-new=1 mean?
Apparently, it means that -faligned-new was used without explicit threshold.
As per documentation, the threshold defaults to alignment of std::max_align_t in this case.
|
62,090,390 | 62,090,426 | c++ standard library header not recognized | I'm working on a multithreaded project in c++ and am trying to use a semaphore, from what I read in the documentation c++ has a semaphore, but when I try to include the header
#include <semaphore>
It does not autocomplete and I get a compiler error saying the header file is not recognized.
According to the documentat... | As can be seen here, none of the listed compilers have currently implemented this c++20 feature.
|
62,090,629 | 62,097,277 | How to make C++ debug statements appear in the gdb console | I am trying to debug an application in gdb running on Ubuntu 18.04.
In some parts of the code, I can set breakpoints and successfully debug problems.
But in other parts, triggering a breakpoint causes the process to exit.
Is there some way I can get debut statements to appear in the gdb console?
I currently use gdb to ... |
I have code (std::cout) that sends statements to standard out but they are not showing up in the gdb console.
Nor should you expect them to.
When an application is started, its std::cout messages are going to file descriptor 1 (stdout). This can be the terminal window in which the app was started, or a file if the o... |
62,090,665 | 62,091,086 | Sorting a vector with pointer at object C++ | If anyone can help I would be very grateful.
How do i sort this vector:
vector<Person*>person
by this criterium:
Surname
I have already tried it using set but it removes object if there is more than 2 objects with same Surname
there are lot of string variables, and I need to sort it by
Surname
and then if surnames ar... | Here's a complete example
#include <vector>
#include <iostream>
#include <algorithm>
class Person
{
public:
std::string s1, s2, s3;
Person(std::string S1, std::string S2, std::string S3) : s1(S1), s2(S2), s3(S3) {}
};
struct less_than_key
{
inline bool operator() (const Person* const p1, const Person* co... |
62,090,991 | 62,091,224 | Best way to remove non uniques values from an array, keep the order, and not use vectors? | I apologize if this has been asked, but I ran into a coding question, which was supposed to be simple but I struggled on. Please provide a link if already answered (I may just be bad at searching).
Question: Given the sample code fill in the function to return only unique values in the array. Values must keep order.
Ex... | Admittedly, this problem would be easier if you could use external libraries, but if you are certain you cannot, it is still solvable.
I read the question incorrectly the first time. Here is a link to as similar question.
#include<iostream>
using namespace std;
int removeDuplicates(int arr[], int n)
{
int j = 0;
... |
62,091,079 | 62,101,687 | Throughput of trivially concurrent code does not increase with the number of threads | I am trying to use OpenMP to benchmark the speed of data structure that I implemented. However, I seem to make a fundamental mistake: the throughput decreases instead of increasing with the number of threads no matter what operation I try to benchmark.
Below you can see the code that tries to benchmark the speed of a f... | I'm not sure why you are defining performance as the total number of operations per total CPU time and then get surprised by the decreasing function of the number of threads. This will almost always and universally be the case except for when cache effects kick in. The true performance metric is the number of operation... |
62,091,353 | 62,091,467 | Can't understand how to get rid of goto | This question probably is kind of silly, but I really need help.
I'm pretty new in programming and as far as I know, goto is a thing that I should avoid in my code. And a couple of days ago I wrote this for my school task:
bool create_way(int start_index) {
if (start_index == members.get_size() - 1) {
flowToDrain.p... | This should work, though you should test it:
while(1) {
int max_index = INT_MIN;
int max_bandwidth = INT_MIN;
for (int i = 0; i < network[start_index].routes.get_size(); i++) {
int index = network[start_index].routes.find(i);
int bandwidth = network[index].bandwidth.find(start_index);
... |
62,091,391 | 62,093,668 | Read only the last 3 characters from the end of a file and save them as an int | I am trying to write a function which should read the last three characters from a certain .txt file and return me the value as int.
example of what the file contains:"***** ***** 505" .
when I run the code the function returns me "505" but also gives me "/377? below.
I noticed a similar existing post yet I was not ab... | You are printing out the value of ch immediately after reading it and before you check it for EOF. You need to do the check first.
do {
ch = fgetc(fp);
if (ch == EOF) break;
cout << ch;
} while (true);
Or:
while ((ch = fgetc(fp)) != EOF) {
cout << ch;
}
Whether a char is signed or unsigned is unspeci... |
62,091,419 | 62,091,558 | C++ compile problem with strlen and strcpy | #include<iostream>
using namespace std;
int main()
{
char a[5],b[5];
cout<<strlen(a)<<endl;
strcpy(a,b);
}
when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!
based on cplusplus.com, I am the one who sh... | strlen and strcpy are declared in the <cstring> header. Some standard library implementations might include that in <iostream>, some might not. This explains why it may compile with some setups and not others.
|
62,091,548 | 62,094,892 | atomicCAS for bool implementation | I'm trying to figure out is there a bug in the answer (now deleted) about the implementation of Cuda-like atomicCAS for bools. The code from the answer (reformatted):
static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
unsigned long long addr = (unsigned long long)address;
unsig... | Many many thanks to @RobertCrovella; the first code sample does contain a bug, the second does fix it, but is not thread-safe (see question comments for details). The thread-safe fix:
static __inline__ __device__ bool atomicCAS(bool *address, bool compare, bool val)
{
unsigned long long addr = (unsigned long long)a... |
62,091,607 | 62,096,370 | Cyclic splitting of execution into several threads (1-N-1-N-1...) | Consider this case:
for (...)
{
const size_t count = ...
for (size_t i = 0; i < count; ++i)
{
calculate(i); // thread-safe function
}
}
What is the most elegant solution to maximize performance using C++17 and/or boost?
Cyclic "create + join" threads makes no sense because of huge overhead (wh... | In the past, you'd use OpenMP, GNU Parallel, Intel TBB.¹
If you have c++17², I'd suggest using execution policies with standard algorithms.
It's really better than you can expect to do things yourself, although it
requires some fore-thought to choose your types to be amenable to standard algorithms
still helps if you ... |
62,092,223 | 62,092,267 | Is it possible to hold multiple types of enums in a variable in C++? | Is it possible to do something like this in C++:
enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
eg1,
eg2,
eg3,
...
}
enum B {//Same structure as enum A
e1,
e2,
e3,
...
}
some_data_type e = eg1;//No errors here
e = e2;//No errors here
I think it cou... | If you're ok losing the distinction between the original types, then an integer would work. If you want to be a little more restrictive and only allow assignment from and comparison against "compatible" enums, then a user-defined type with implicit conversion from both A and B is probably wanted. Unfortunately you ca... |
62,092,242 | 62,092,476 | How to write multi-threaded functions inside a big function? | I have a function like this that is working fine:
void BigFunction()
{
void FunctionA(std::shared_ptr<ClassC> c);
}
now I want to add another function inside BigFunction()
void FunctionB(std::shared_ptr<ClassC> c);
which also take std::shared_ptr<ClassC> c as the input.
How do I do it correctly and safely so that... | You can use std::thread or std::future/std::async. For these "task"'s it is better/easier to use std::assync/future since the thread management is done for you.
bool func1(int a) {...}
bool func2(int a) {...}
void some_func()
{
std::future<bool> f1 = std::async(std::launch::async, func1, 1);
std::future<bool> ... |
62,092,522 | 62,093,508 | List C++ Move to front; | Hello i need to find the earliest note in one-Way listy
Unfortunately i can`t use list container.
Here some code
Struct
struct Sterminarz
{
Sterminarz *next=NULL;
int year;
int month;
int day;
int hour;
string note;
};
Function which look for earliest note
void findEarliest(Sterminar... | Try something like this:
struct Sterminarz
{
Sterminarz *next = NULL;
int year;
int month;
int day;
int hour;
string note;
bool operator<(const Sterminarz &rhs) const {
if (year < rhs.year) return true;
if (year > rhs.year) return false;
if (month < rhs.month) retur... |
62,093,255 | 62,093,382 | How to manage resources that cannot be deep-copied in C++ | I am creating a class that manages a resource that should not be "deep copied", that is, there can only ever be one instance of the underlying resource, even if multiple objects have access this same resource.
However, allowing multiple objects to access this resource is also dangerous, as one object could go out of sc... | I think that you are looking for std::shared_ptr or parallel solution; std::shared_ptr is used to share pointers to a single object, which is destroyed only after all of the shared pointers are cleared. Thus, while we still have a reference to the object, it remains valid.
Even if you are not looking to use shared_ptr,... |
62,093,388 | 62,093,525 | Is there a more concise way to pass function result as shown here | I'd like to call my function that creates the object to be passed to a method on the same line, but if I do I get an initial value of reference to non-const must be an lvalue compile-time error. To get it to compile I need to declare a temporary holder variable and set it equal to the factory method resul.
I realize th... | Change the signature to:
Baz add(Bar bar) { /* .... */ }
Since you need to retain the value (to put it in a vector) you must have ownership of the object. You've declared that you take a reference to avoid making a copy, but you do make a copy -- when you put it in the vector!
Instead, take the object by value, and ... |
62,093,402 | 62,866,125 | How to retrieve multiple NDJSON objects from the same file using ArduinoJson? | I am trying to use ArduinoJson to parse Google's quickdraw dataset, which contains .ndjson files with multiple objects inside. I figured how to retrieve the first of the objects in the file using the following simple code:
DeserializationError deserialization_error = ArduinoJson::deserializeJson(doc, as_cstr);
if (dese... | I found it.
just call multiple times:
DeserializationError error = deserializeJson(doc, sceneFile);
or:
deserializeJson(docline1, sceneFile);
deserializeJson(docline2, sceneFile);
deserializeJson(docline3, sceneFile);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.