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 |
|---|---|---|---|---|
66,597,260 | 66,606,080 | Does C++ guarantee identical binary layout for "trivial" structs with a single trivial member? | We have some strictly typed integer types in our project:
struct FooIdentifier {
int raw_id; // the only data member
// ... more shenanigans, but it stays a "trivial" type.
};
struct BarIdentifier {
int raw_id; // the only data member
// ... more shenanigans, but it stays a "trivial" type.
};
Basically some... | Challenging eerorika's answer, I believe you are guaranteed binary compatibility. I'll reference the C++11 spec for this.
Key pieces:
[class/7] This defines a standard-layout class. It's pretty clear we all agree that these are standard layout.
[intro.object/5] and [intro.object/6]
An object of trivially copyable o... |
66,597,641 | 66,598,556 | It's possible suppress output about of one function? | In my program I use an external function which generates output to me and I don't want it not to be generated by that function alone,
it's possible?
int main()
{
int a;
//I don't want the output of this function
a = function();
//now i want output
cout << "the result is : " << a;
}
Is it pos... | Using only standard C++ where no dup-like functions exist, you could open a temporary std::FILE and std::swap with stdout.
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
// extern "C" int function(); // an assumpti... |
66,598,261 | 66,598,484 | Remove items from linked list after a certain value | I have this problem, where user inputs n and my program needs to remove any elements form a linked list that come after n and are not equal to n. For example, if my list is 1,2,4,8,4,6,1 and user inputs 4 it should output 1,2,4,4.
So far I only have this code (if list is 1,2,4,8,4,6,1 it outputs 4 8 4 6 1):
#include <i... | Your problem needs to be broken down into two parts
Find the first instance of the target value.
If found, advance to the node past it, and delete every node not the target value.
This is made trivial with a pointer to pointer approach. The code to do that is shown below, and I did my best to document how it works in... |
66,598,270 | 66,598,401 | Is it Undefined Behavior to write `return {data, uninitialized_copy(b, e, data)};` in C++ | Hi i am reading an example of how to define our own vector like class without using templates from one of the books. Now here there is one function which is defined as follows:
pair<string *, string*> StrVec::alloc_n_copy(const string *b, const string *e)
{
auto data = alloc.allocate(e - b);
return {data, uniniti... | The issue with std::cout << i << ++i << std::endl; is that i is used twice in the same expression and once it is modified. There are numerous questions and answers around this topic, so I just refer to them.
In your code
return {data, uninitialized_copy(b, e, data)};
data is not modified. It doesn't matter if you take... |
66,598,639 | 66,598,922 | Solving Segmentation Fault(core dumping) error | This program doubles the every second integer for the account number given and if the number is greater than 10 it is subtracted by 9. Then output whether the number entered is correct or not. Assuming that the account number is off 5 numbers. I wrote this program but does not get the answer for few number but got a co... | The issue here is that you never allocate p. Look at your constructor:
AccountNumber()
{
int *p = new(std::nothrow) int[size];
}
Here you are defining a new pointer variable p, which will be used instead of the member pointer variable p you defined in the private fields. What happens here is that you are allocati... |
66,598,681 | 66,639,352 | ESP8266 WiFi Manager and Modem Sleep | Noob question, I'm very knew here, I'm trying tu use wifi manager and modem sleep, but once I turn off the wifi I can't reconnect again. I know what I'm missing is the configuration to connect to the wifi after it has been turned off but I don't know how to do it if I'm using WiFi Manager.
These are the steps:
Power o... | if I've understood the question right. This could be of great help:
https://github.com/tzapu/WiFiManager/issues/272
If not, my bad.
|
66,598,738 | 66,599,297 | Why does std::equality_comparable not work for std::vector | https://godbolt.org/z/P97MaK
I'm playing with concepts and expected std::is_equality_comparable to work for vector but it does not.
#include <type_traits>
#include <vector>
#include <concepts>
struct X {};
template<std::equality_comparable T>
bool foo( T v){
return v == v;
}
int main()
{
foo(10);
foo(st... | A concepts only checks that the declaration is well formed, it doesn't check the definition.
The comparison operators for std::vector are not SFINAE friendly, i.e. they are unconditionally declared, meaning that operator==(vector<T>, vector<T>) always exists, even if operator==(T, T) doesn't exists. That's why equality... |
66,598,826 | 66,598,969 | How to atomically check if mutex is locked? | Consider this:
// Somewhere
std::mutex mutex;
std::unique_lock lock{mutex};
std::condition_variable condition;
// Thread01
condition.wait(lock);
// Thread02
while (lock.owns_lock());
So I got a situation like this where the loop at Thread02 never ends, regardless of the fact that Thread01 is waiting for the conditio... | You can momentarily lock the lock and get the desired Thread02:
// Thread02
std::unique_lock{mutex};
// mutex isnβt locked
|
66,600,404 | 66,600,549 | How to make algorithm or lambda to not construct new object | I have this code to find ID of object in vector<Object*> list
int objID = ...
auto it = std::lower_bound(objectPtrList.begin(), objectPtrList.end(), objID,
[](const Object* obj, const Object& id)
{
return obj->worldMoveID < id.worldMoveID;
});
The question is, that const Object* obj... | you object creation is not from const Object* obj but from
const Object& id (from objID which is not an Object).
You might do instead:
auto it = std::lower_bound(objectPtrList.begin(), objectPtrList.end(),
objID,
[](const Object* obj, int id) { return obj->worldMove... |
66,600,533 | 66,600,615 | How do is resolve conversion error from Point<T> to non scalar Point<U> | I've stumbled upon a problem and I can't seem to find any information on SO on how to solve it. I've created a generic Point class and I'd like to convert from one to another. However, the compiler is always giving me the same error.
template<typename T>class Point
{ ... | Often confused: Pointd pd = pi; is not calling the assignment operator! It is initialisation not assignment. You can add a constructor like this to make your code compile:
template <class U>
Point(const Point<U>& other) : m_x(other.getX()),m_y(other.getY()) {}
Live Demo
|
66,600,790 | 66,609,731 | Can't read cyrillic from .txt file | I want to read this cyrillic text from a .txt file: Π°Π°Π°Π°Π°Π°Π°Π°Π°Π°Π°Π°
std::wstring str;
std::wifstream in(path);
std::getline(in, str);
in.close();
But the content of str is: ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ°ΓΒ° (file encoding - UTF-8) (Watched string content in debug, not in console)
I tried to change file encoding to UTF-16 (LE and ... | In Windows you have to open the file in binary, then apply the UTF16 facet, otherwise system will assume default code page. See example below.
Note that it is common to use UTF8 for storing data, even in Windows applications. Your Windows program expects UTF16 for the APIs, so you can read/write the file in UTF8, then ... |
66,601,580 | 66,604,768 | Can't build OMNeT++ Project | I can't build the basic project configuration and I am always getting this message in the console. I have set PREFER_CLANG=no as well and still getting this error.
16:09:44 **** Build of configuration debug for project Ihab Project ****
make MODE=debug all
Computer.cc
Creating executable: out/gcc-debug//Ihab
g++.exe: ... | I have discovered the problem, you can't put Spaces when you name your Project. I have renamed it to be IhabTest instead of Ihab Project.
19:44:44 **** Build of configuration debug for project IhabTest ****
make MODE=debug all
Computer.cc
Creating executable: out/clang-debug//IhabTest_dbg.exe
19:44:47 Build Finished.... |
66,601,673 | 66,601,785 | Including a template type parameter for my class | I am trying to write a class for rational numbers. So far it looks as follows:
#include <iostream>
template <typename T>
class Rational {
public:
Rational();
Rational(T a);
Rational(T a, T b);
std::string to_string();
private:
T num_;
T denom_;
};
Rational::Rat... | As the compiler tries to tell you Rational is not a class. Hence this is wrong:
Rational::Rational(){
num_ = 0;
denom_ = 1;
}
If you want to define a method of a class template you need to declare that it is a method of a class template:
template <typename T>
Rational<T>::Rational(){
num_ = 0;
denom_ = 1;
... |
66,601,778 | 67,100,135 | Errors link libraries firebase - "_OBJC_CLASS_$_FIRAnalytics", referenced from | I write crossplatform application using QT Creator(4.1.1) and Qt Framework(5.14.1). I want enable firebase, so I download firebase C++ sdk (latest release) : link
Then i try connect it the my project in *.pro - file. Option one - with help frameworks:
QMAKE_LFLAGS += -F$$PWD/fr_universal/ -ObjC \
-framework StoreKit \
... | The most important note is that the C++ SDK does not stand on its own, it is reliant on the iOS SDK to run. You can see a breakdown of the needed frameworks at this page or you can look in the readme.md file to see the required dependencies the binary C++ SDK and the ios_pod/Podfile to see required versions.
With the F... |
66,602,157 | 66,602,616 | How do I calculate the time complexity of the following function? | Here is a recursive function. Which traverses a map of strings(multimap<string, string> graph). Checks the itr -> second (s_tmp) if the s_tmp is equal to the desired string(Exp), prints it (itr -> first) and the function is executed for that itr -> first again.
string findOriginalExp(string Exp){
cout<<"*****findOr... | I am not going to analyse your function but instead try to answer in a more general way. It seems like you are looking for an simple expression such as O(n) or O(n^2) for the complexity for your function. However, not always complexity is that simple to estimate.
In your case it strongly depends on what are the content... |
66,602,327 | 66,602,493 | CMake: Own Shared libray in Windows: error while loading shared libraries | I have a CMake project with the next structure:
βββ CMakeLists.txt
βββ app
βΒ Β βββ CMakeLists.txt
βΒ Β βββ main.cpp
β
βββ theLib
βββ CMakeLists.txt
βββ internal
βΒ Β βββ internal.cpp
βΒ Β βββ internal.h
βββ myprint.cpp
βββ myprint.h
And the output tree is:
βββ app
βΒ Β βββ app.exe
βββ theLib
βΒ Β ββ... | You need to make sure that the application can find your dll. To do this you have to:
Put the exe and the dlll into the same folder
Add the folder where the dll can be found to your PATH-environment variable.
Here you can learn more about the dll-loading How dll get loaded
|
66,602,865 | 66,642,607 | Visual Studio doesn't recognize boost::asio |
I download the last version of boost.
I built binaries by executing "bootstrap" and "./b23
I added the include directory "$(SolutionDir)lib\boost_1_75_0" and linked the binary one "$(SolutionDir)lib\boost_1_75_0\stage\lib"
Everything compiles and works fine. I have a problem that prevents me from being productive: VS... | I fixed it by upgrading to Visual Studio 2019.
Thanks.
|
66,602,986 | 66,603,356 | Getting first word of each line in file | I have problem while getting first word of each line in my file. My txt file is:
GB LONDON 1 9 3 0 4 5
D BERLIN 2 5 6 1 4
E MADRYT 1 2 3 4 5
And I want only to put first word each line of file to array like [GB,D,E];
I tried this:
ifstream plik("galerie.txt");
if(!plik){
cout<<"no... | You can try this code works fine for me can check on your side. You just need to push in vector instead of output in another file.
#include<iostream>
#include<fstream>
#include <sstream>
#include<string>
using namespace std;
int main()
{
ifstream fin("input.txt");
vector<std::string> v;
string line;
st... |
66,603,053 | 66,607,896 | How to compile and link a minimal .NET C++ program using mingw | I'm trying to compile a minimal example of .NET C++ code (just calling CLRCreateInstance and starting a CLR runtime host). I'm not using Visual Studio, but mingw. I installed the Windows 10 SDK with .NET goodies, and I have the header and lib files correctly installed in Program Files. However, I cannot get g++ to link... | I finally made it work with the following two corrections:
I switched from vanilla MinGW to an msys2 packaged one. This solved the undefined reference to CLRCreateInstance, which I don't know why was failing with the vanilla MinGW. This basically consisted in downloading msys2 and running pacman -S mingw-w64-x86_64-gc... |
66,603,528 | 66,604,275 | how to read/write sequnce of bits bit by bit in c++ | I have implemented the Huffman coding algorithm in C++, and it's working fine. I want to create a text compression algorithm.
behind every file or data in the digital world, there is 0/1.
I want to persist the sequence of bits(0/1) that are generated by the Huffman encoding algorithm in the file.
my goal is to save the... | "Binary mode" means only that you have requested that the actual bytes you write are not corrupted by end-of-line conversions. (This is only a problem on Windows. No other system has the need to deliberately corrupt your data.)
You are still writing a byte at a time in binary mode.
To write bits, you accumulate them in... |
66,603,543 | 66,603,874 | Why those two std::string find() functions are declared as noexcept? | According to [string.find#1.2] and [string.find#1.3]:
Each member function of the form
constexpr size_type F(const charT* s, size_type pos) const;
has effects equivalent to: return F(basic_Βstring_Βview<charT, traits>(s), pos);
Each member function of the form
constexpr size_type F(const charT* s, size_type pos, ... | This is the so-called Lakos rule. See N3248. The rule is that if a function has a precondition, it should not be marked noexcept because it prevents an implementation from checking the precondition and throwing an exception on validation, if the implementation would choose to do that.
In this case, find(s, pos, n) is e... |
66,603,683 | 66,603,787 | How to put variable as argument in system() | I am trying to include the sleep 1 command in bash in my .cpp file
While system("sleep 1") works fine, I would like to change 1 into a const int or string
const string t = "1";
string c = "sleep " + t;
system(c);
However, it seems like the system(c) is treated as a call to function as the following error occurs:
err... | The system function takes a const char* pointer as its argument. However, there is no implicit conversion from a std::string object to a const char* (representing its contained string data) provided by the Standard Library. Instead, you can call the c_str() member function on that object, like so:
system(c.c_str());
|
66,603,718 | 66,603,769 | "free(): double free detected in tcache 2" in dynamic array class in C++ | I want to write a dynamic array class in C++. I get this message: free(): double free detected in tcache 2 when I run the code.
This is part of my code:
if(num_of_items >= size)
{
int new_size = size < 5 ? 2 * size : (int)(3/2 * size);
int * temp = new int[new_size];
... | Your pointer temp is the new, larger array, which your object needs to hold. You delete it, leaving your object in a bad state.
The remedy is easy, delete this line: delete [] temp;
|
66,604,152 | 66,604,187 | Inheritance default access modifier in C++ | I have an interface in C++ that looks something like this:
// A.h
#pragma once
class A
{
public:
//Some declarations.
private:
//Some declarations.
protected:
//Some declarations.
};
The specific form is not important. Since this is an interface, there will be a class B that inherits from A. In th... | The ONLY difference between struct and class is that in a struct, everything is public until declared otherwise, and in a class, everything is private until declared otherwise. That includes inheritance. So class B : A will default to private inheritance, and struct B : A will default to public inheritance.
|
66,604,456 | 66,636,127 | Declare an object as abstract class | Edit this question as originally posted was a simplified version of what I had and as such did not contain the problem which was causing the error. I have updated to be more like my problem, and will post an answer in case someone else has a similar issue.
In C++ is it possible to declare an object as an abstract class... | The issue was that not all of the virtual functions defined by the abstract class were implemented in the derived classes.
I needed
// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
int getNumOfSides() {
return 4;
}
};
class T... |
66,605,046 | 66,630,862 | Mocking elements of an array in turtle mock | I need to mock elements of an array in turtle mock. Unfortunately, because the turtle mock macro MOCK_BASE_CLASS adds extra "gunk", e.g. mock::object, mock::detail::base<> etc, the sizes of the base and mock types are no longer identical. Therefore, and pointer indexing fails when a pointer to a base class points to an... | My suspicions were confirmed: a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type (source). Accordingly I created a wrapper/adapter which I call indexer to manage the indexing of the correct type, as shown below.
struct Foo
{
int value = 42;
in... |
66,605,075 | 66,652,192 | UE4 UserWidget Button bind with spawning actor in PlayerController | Hello my fellow coders -
I am in need of an assistance for this problem
I have MyPlayerController.c (.h), MyGameHUD.c (.h) and MainUIWidget.c (.h)
MyGameHUD is custom class default HUD for MyPlayerController in MyGameMode
MainUIWidget is custom class - simple widget with few buttons
MyPlayerController is custom class
I... | Thanks for answers all.
Problem solved by :
Moving
PlayerControllerPtr = Cast<AMyPlayerController>(this->GetOwningPlayer());
from widget's constructor to widget's BeginPlay() event.
|
66,605,156 | 66,607,635 | How can I link libc++ on macOS? | I'm trying to learn C++ on macOS 11.2 (x86-64), and I'm having trouble compiling and linking my code. My simple program is listed below.
#include <algorithm>
#include <vector>
template<class I>
void pancake_sort(I first, I last)
{
for (; first != last; first++){
std::reverse(std::min_element(first, last), ... | Per Konrad Rudolph, the solution is to use clang++ instead of clang to compile C++ code.
|
66,605,230 | 66,605,310 | problem when I separate code to header file | this program works correctly but when I separate that "Class StudentsName" and put it on the header file it doesn't work correctly. I add the header file in my project by right click on the header folder and choosing the new item and the choosing header, but it doesn't work correctly .please help me!
main file:
#inclu... | The using directive
using namespace std;
is placed after including the header "Student.h"
#include "iostream"
#include "string"
#include "Students.h"
using namespace std;
So the name string is undefined within the header "Students.h".
Place the directive before the inclusion of the header.
#include "iostream"
#includ... |
66,605,706 | 66,606,185 | template instantiation depth exceeds maximum - how to stop particular case? | I have a following function:
template<unsigned fromLine, unsigned toLine = fromLine>
void stateChanged()
{
// onStateChangeHandler[fromLine]();
if (fromLine < toLine)
stateChanged<fromLine + 1, toLine>();
}
which I call it in a following way:
stateChanged<0>();
stateChanged<1>();
stateChanged<2>();
st... | Without the ability to use if constexpr in the template definition, you need to change how you do the looping in order to introduce a way for the compiler to reach a terminal state and stop the template instantiation.
We can do this with a helper class that, rather than going from start to finish, processes a number of... |
66,606,143 | 66,606,683 | Can you use explicit constructors with designated initializers? | In the code below, is the initialization of member b legal?
class B {
public:
explicit B(int) {}
};
struct A {
B b;
};
class C {
public:
C() : a{.b{33}} {}
A a;
};
Compiling with the latest version of gcc gives this error (wandbox)
prog.cc: In constructor 'C::C()':
prog.cc:12:11: error: con... | This is a gcc bug (submitted 99566).
The rule, from [dcl.init.aggr]/4.2, is:
Otherwise, the element is copy-initialized from the corresponding initializer-clause or is initialized with the brace-or-equal-initializer of the corresponding designated-initializer-clause.
The element (b) should be initialized from the bra... |
66,606,202 | 66,606,609 | Gcc misoptimises sse function | I'm converting a project to compile with gcc from clang and I've ran into a issue with a function that uses sse functions:
void dodgy_function(
const short* lows,
const short* highs,
short* mins,
short* maxs,
int its
)
{
__m128i v00[2] = { _mm_setzero_si128(), _mm_setzero_si128() };
__m128i... | The problem is that you're using short* to access the elements of a __m128i* object. That violates the strict-aliasing rule. It's only safe to go the other way, using __m128i* dereference or more normally _mm_load_si128( (const __m128i*)ptr ).
__m128i* is exactly like char* - you can point it at anything, but not vic... |
66,606,526 | 66,607,053 | inet_ntoa() in Winsock2 is deprecated? | I was experimenting with Winsock2 at the moment, and got a warning that inet_ntoa() is deprecated and that I should use inet_pton(). I tried it, but it was little endian, so the whole string that was saved in the buffer was "wrong". I'm guessing inet_ntoa() is big endian?
And I could only use inet_pton() with #include ... | inet_pton() is NOT the successor for inet_ntoa(), but for inet_addr() instead. You want inet_ntop() instead.
inet_ntoa()/inet_ntop() convert an IP address from binary form to string form. inet_addr()/inet_pton() do the opposite conversion.
However, there are actually several functions that you can use instead of inet... |
66,606,616 | 66,606,791 | C++ Bitset algorithm | I am given a nxn grid with filled with 1 or 0. I want to count the number of subgrids where the corner tiles are all 1s. My solution goes through all pairs of rows and counts the number of matching 1s then it uses the formula numOf1s * (numOf1s-1)/2 and adds to the result. However, when I submit my solution on https://... | This solution will cause a time limit exceeded. bitset::count() is O(n) in worst case. The total complexity of your code is O(n^3). In the worst-case the number of operations would be 3000^3 > 10^10 which is too large.
|
66,606,687 | 66,607,916 | C++ uni task to show the cheapest ticket for the farthest city | I am a newcomer cs student, I have a uni task
shown here
Plane ticket to go far far away
A travel agency stores the prices of the plane tickets to cities being different distances away.
Write a program that gives the price of the plane ticket to the farthest city.
Input
The first line of the standard input contains th... | Since you indicated in the comments that you already solved it, for posterity's sake, here's how I would solve the problem using Modern C++. The algorithms header makes the problem trivial:
#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
#include <utility>
int main() {
//Get the number... |
66,607,527 | 66,607,645 | Invalid operands to binary expression "`const Foo` and `const Foo`, no matching call to sort | I am trying to sort a vector of a class, Foo. In my Foo class, I have overriden the < operator. I pass in iterators to the sort function of a vector<Foo> foo_vec like so: sort(foo_vec.begin(), foo_vec.end()), and I have using namespace std;. What could be causing this error?
More details:
The override, in Foo.cpp
bool ... | std::sort() is internally dereferencing the iterators and passing the Foo objects to a comparator (likely std::less) that is taking the Foo objects by const reference. However, your operator< is not marked as const, so it can't be called on const Foo objects, only on non-const Foo objects. You need to mark it as cons... |
66,607,716 | 66,621,129 | How to extract surface triangles from a tetrahedral mesh? | I want to render a tetrahedral mesh using some 3D software. However, I cannot directly load the tetrahedral mesh in the software of my choice (e.g. Blender) as the file format that I have for tetrahedral meshes is not supported. So I should somehow extract the faces with corresponding vertex indices myself.
For a cube,... | here is a simplistic brute force method. For each tetrahedron, for example look at the third one, t: 1 2 4 7, by removing each vertex, generate all four combination of three vertices out of the four tetrahedral vertices, i.e.
face[t][0]: 1 2 4, face[t][1]: 1 2 7, face[t][2]: 1 4 7, face[t][3]: 2 4 7
and sort each tr... |
66,607,745 | 66,608,115 | Character array adds random characters at outputting | cin.get(a, 256);
for(int i = 0; i < strlen(a); i++){
if(strchr("aeiou", a[i])){
s = 0;
strcpy(substr, empty);
isubstr = 0;
}
else{
s++;
substr[isubstr++] = a[i];
if(s > maax || s == maax){
maax = s;
memset(show, 0, 256);
... | For starters you should write a function that finds such a longest sequence of consonants.
You provided an incomplete code so it is difficult to analyze it. For example it is not seen where and how variables substr and empty used in this call
strcpy(substr, empty);
are defined and what are their meanings.
Also there a... |
66,608,215 | 66,608,393 | Why is std::rotate faster than this way of doing it? | void rotate(vector <int> &a)
{
int lastElem = a[a.size()-1];
for(int i=a.size()-1;i>0;i--){
a[i] = a[i-1];
}
a[0] = lastElem;
}
Versus
rotate(a.begin(),a.end()-1,a.end());
As far as I can see the algorithm above is O(n) so why is STL way faster(I thought it was linear time as well).
| The standard library implementation of std::rotate is likely using a call to memmove() for bulk data copying. That would be one reason that it's faster than your hand-written loop.
Since you are only rotating a single element you can replace your loop with a call to std::copy_backward. That will also compile to memmove... |
66,608,276 | 66,608,707 | Several Error with Implementing of Threads in QT [C++] | I'm new to implementing Threads in QT and even after reading the Documentation several times and watching Videos, I get some Error which not even Google can help me with.
thread.cpp:14: error: C2440: "Initialisierung": "QFuture" kann nicht in "QFuture" konvertiert werden
Error Codes are in German, tried to change QT La... | Thread::GenerateTable() is a member function. It needs an object to work on. You are calling it (er .. passing it to QtConcurrent::run()) from the (static) Thread::start() and there's no Thread object to speak of.
Although you've tagged Qt6, I'll point at the Qt5 documentation for calling member functions: you can pass... |
66,608,357 | 66,608,444 | 'Redefinition of class' error in cpp file | I've got error "redefinition of class Book". Thats my code:
Book.cpp
#include "Book.h"
using namespace std;
class Book {
string author, title;
public:
Book()
{
cout<<"Book()"<<endl;
author = "-";
title = "-";
}
Book(const string& autor, const string& tytul)
{
cout<... | The preprocessor which handles header files and the #include directive basically copy-pastes the header file into the place of the #include directive.
That means the compiler will see this in your source file:
class Book { ... };
class Book { ... };
You can't define a class multiple times like this.
Instead only defi... |
66,608,441 | 66,616,322 | Maximize The Cut Segments using top down approach? | Given an integer N denoting the Length of a line segment. You need to cut the line segment in such a way that the cut length of a line segment each time is either x , y or z. Here x, y, and z are integers.
After performing all the cut operations, your total number of cut segments must be maximum.
Example 1
Input:
N = 4... | You'd need to ensure that max_seg is never called with a negative n, or else that, if called with negative n, it returns a value that won't be taken as the best solution. β @IgorTandetnik
fix
int max_seg(int M[], int n, int x, int y, int z)
{
if( (n<0) )
return INT_MIN;
else if( (n>=0) && M[n] != -1)
... |
66,608,574 | 68,259,351 | protobuf_generate grpc_cpp_plugin fails with status code 1 | I'm trying to generate grpc cpp files but the generator plugin fails when I call it in cmake
find_package(protoc CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)
get_target_property(grpc_cpp_plugin_location gRPC::grpc_cpp_plugin LOCATION) #get plugin location
get_target_property(protoc_location protobuf::protoc LOCA... | The issue is probably that cmake uses an outdated protobuf config, or rather the FindProtobuf.cmake that comes with cmake rather than ProtobufConfig.cmake that comes with the protobuf package.
To fix this, compile gRPC yourself and use the -DgRPC_PROTOBUF_PACKAGE_TYPE=CONFIG flag when you run cmake for gRPC.
The proble... |
66,608,760 | 66,609,035 | using stoi when creating a stack data structure results in errors | I've created a stack data structure and am implementing it. I've been using the function below,
void Stack::solution(const char *input_path, const char *output_path)
{
string line;
Stack tempStack;
ifstream myfile(input_path);
ofstream outfile(output_path);
while (getline(myfile, line)) {
... | You did not show what your input actually looks like, but if it is anything like the input shown in this question, then the o case does not have an integer value associated with it, so the call to line.substr(1,1) will not return a string that std::stoi() can convert to an int, hence why a std::invalid_argument excepti... |
66,608,918 | 66,609,144 | Call to member function is ambigous when overloading both vector of chars and string c++ | I want to overload a function the following way:
void f(string s){
cout << "String case" << endl;
}
void f(vector<char> v){
cout << "Vector case" << endl;
}
For the case I insert a string object or a vector object, everything is fine:
int main()
{
string s = "hello";
f(s); // Prints "String case"
... | If you provide a initializer_list<char> overload, calling f with a brace-initialized list such as {'a', 'b'} will select that overload as the best match.
You can just call the vector<char> overload explicitly from there.
void f(std::initializer_list<char> v)
{
f(std::vector<char>{v}); // call the vector version
}... |
66,608,982 | 66,609,080 | NtQuerySystemInformation returns back negative result for a specific core - What does that mean | I am trying to output the performance of each processor on my machine.
I have two groups with 36 processors on each. I am doing something like this
PVOID WLAlloc(DWORD dwSize)
{
PVOID pMem = nullptr;
pMem = HeapAlloc(GetProcessHeap(),NULL,dwSize);
return pMem;
}
void test()
{
int numofGroups = 2;
D... | You are allocating only room for 2 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, but then you are trying to iterate up to index 72, which is Undefined Behavior for indexes 2 and higher.
You need to fix your loop to only iterate over items you have pre-allocated, or else query for the actual size first and retry the call wi... |
66,609,320 | 66,609,463 | C++ template instantiation, error: member of non-class type 'int' | I am trying to implement a binary search tree in C++.
I have run into a problem while recursively calling function Node<T>::append in its own definition.
Here is a minimum reproducible example:
#include <iostream>
#include <string>
#include <memory> // std::unique_ptr<>
using namespace::std;
template<class T> class N... | left_child and right_child do not point Node. The compiler explains this pretty clearly: which is of non-class type 'int' left_child, left_child is of type int, not class. The declarations
unique_ptr<T> value, left_child, right_child;
should be
unique_ptr<T> value;
unique_ptr<Node<T>> left_child, right_child;
The fur... |
66,609,347 | 66,609,370 | Why do strings still work sometimes even when you don't include the string library in c++? | I'm learning to code using C++. I learned that to use the string datatype you need to include the <string> library, but how does this code still work when I haven't included the <string> library?
#include <iostream>
int main() {
std::cout << "Hello World!\n";
return 0;
}
It outputs a string to the console without... | There is a difference between a std::string object (that comes from the <string> header file) and a C-style string. You do not need to include the <string> header file in order to use C-style strings, as they are built-in to the language. This is mainly due to the fact that a C-style string is just an array of characte... |
66,609,349 | 66,609,374 | Print 5 line at a time | I got a simple cout statement below. And I want to print 5 lines at a time (the output below). I am new to C++. The 3 dots just a symbol to see the output
int count = 0;
cout << "Print line:" << endl;
for (int i = 0; i < 10; i++){
cout << i << endl;
count++;
if (count > 6){ ... | #include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i % 5 == 0)
cout << "Print Line\n";
cout << i << endl;
}
}
|
66,609,753 | 66,609,803 | What type do vector strings deduce to? | I'm becoming familiar with using vectors (reading An introduction to std::vector), and it displays the following code as an example:
// as with std::array, the type can be omitted since C++17
std::vector array4 { 9, 7, 5, 3, 1 }; // deduced to std::vector<int>
If I use this C++17 style vector initialization with strin... |
(i.e. std::string
No, string literals are not related to the class std::string. Technically this could happen if vector had a special deduction guide for this, but it doesn't.
... char*
No, string literals are const.
The contained type will be deduced as const char*.
|
66,610,262 | 66,610,780 | Does cross-platform C++ require building separately on every single platform? | My question actually has two variants, but for some context, I have a C++ *.DLL that I use with Unity using P/Invoke. It's built on Windows 10 with MSBuild (platform toolset: ClangCL).
And now for my questions,
Does the size of a particular type stay constant after the DLL has been built? Or does it need to be rebuilt... | Each platform usually has a different ABI. For example, long on Windows is 32-bit (from memory), but long on Linux is 64-bit. In your example, wchar_t on Windows is 16-bit, but on Linux it is 32-bit. The way that C++ names are mangled is also platform-specific.
Both Windows and Linux have different syscalls (standard l... |
66,610,708 | 66,611,066 | How would I make my code run when I press a button? | So I'm fairly new to c++ and coding in general, and I tried making a test code that would run when I press a button.
I tried changing for loop to a while loop, but that doesn't help.
Here's what I came up with:
#include <iostream>
#include <Windows.h>
int main() {
int i{ 0 };
bool condition = false;
if (... | Your solution, modified to use proper loops.
#include <iostream>
#include <Windows.h>
int main() {
while (!GetAsyncKeyState(VK_HOME))
;
for (size_t i {0}; !GetAsyncKeyState(VK_END); ++i)
std::cout << i << std::endl;
}
|
66,610,772 | 66,611,355 | Delete whole binary tree C++ | Hi I having problem when I try to implement my delete tree function in my Bst class. This is what i have implemented. Currently only have the insert and deletetree functions.
struct nodeType
{
int data;
nodeType * LeftLink;
nodeType * RightLink;
};
class Bst
{
public:
/**
* Default construc... | Please edit as follows:
while(current != nullptr)
{
trailCurrent = current;
if(current->data == insertItem)
{
cout << "item already inserted, No duplicates allowed." << endl;
return;
}
else if(current->data > insertItem)
{
current = current->RightLink;
}
else
... |
66,610,798 | 66,610,881 | How to convert lower case string to uppercase string in C++ | Hi I want to create a program where I will input different names and I will output it in UPPERCASE FORM. However there's a bug in my code, can you help me to figure it out?
It said "[Error] no match for 'operator>=' (operand types are 'std::string {aka std::basic_string}' and 'int')"
int times;
string name [1... | You should pass a const char* to the strlen() function. Refer: https://www.programiz.com/cpp-programming/library-function/cstring/strlen
But the 'name' is an string type array. Therefore the compiler returns an error.
Also the data type of name[j] is std::string. Therefore you cannot compare name[j] with an integer.
If... |
66,610,861 | 66,612,739 | Copies of QSqlQuery share the same bound values | When I try to copy prepared QSqlQuery with assign or copy constructor and bind to them different values with bindValue they both will have the same bound value, one which was bound last. Is it the case of implicit sharing? Though this class is not listed as implicitly shared. I wasn't able to find anything in docs. Wha... | Turns out it's a bug, I was suggested to report it, which I did. For now it is suggested to use two distinct queries and prepare both.
|
66,610,873 | 66,610,928 | I want my code to repeat 3 times but the loop does not end. Does anyone know how I could fix this issue? | Here is the code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <iostream>
#define repeat(n)
#define endrepeat
int main()
{
int login;
char Username [4];
char Password [4];
printf("\t\tPlease enter your user name: ");
scanf("%s", Username)... | Increment the repeat variable like this:
repeat = repeat + 1;
or
repeat += 1;
or
repeat++;
Use brackets inside the if statement to separate logic and avoid getting wrong results, like this:
if ((strcmp(Username,"Jane") == 0 && strcmp(Password,"1234") == 0) ||
(strcmp(Username,"Arin") == 0 && strcmp(Password,"3201")... |
66,610,982 | 66,622,466 | why some triangles are becoming black after I add lighting? | I am trying to add specular lighting to my opengl es program which loads 3d model. Its working normally. But whenever I add lighting this happens:
some triangles are becoming black and some are staying white.
here is my Vertex and fragment shader code:
"attribute vec4 position;\n"
"attribute vec4 normal;\n"
... | I have enabled depth testing and the problem solved.
glEnable(GL_DEPTH_TEST);
|
66,611,051 | 66,613,384 | Qt Creator crashes on creating or opening .ui files. How can it be diagnosed? | Suddenly my Qt Creator started crashing when I try to open or create .ui file.
I've already tried complete uninstall and reinstall with no effect.
Where can I look for some logs to understand what is happening?
Windows 10
Qt Creator 4.14.1
Qt 5.15.2
MinGW 8.1.0
CMake 3.19.2
| Found it. It was corrupted templates.xml file in $HOME/.designer/ directory.
|
66,611,132 | 69,509,655 | `regex_match` returns both 'not found' and `match_results` | In the following code (gcc 10.2.1), the call to regex_match returns 'no match', which I believe is correct.
sm.size() returns 0, but when iterating from sm.begin() to end(), it finds 3 occurrences (all empty strings).
If this is correct, what do these 3 finds mean ?
But since size()==0, shouldn't begin() == end() ?
Edi... | In GCC's implementation of match_results the prefix, suffix, and unmatched string are stored at the end of the sequence managed by the match_results object (which is implemented as a private std::vector base class). Those extra elements should not be visible when iterating from begin() to end(), but the end() function ... |
66,611,418 | 66,873,666 | What are clang's compiled module pcm files for? | I'm looking at the driver test cases for clang modules:
https://github.com/llvm-mirror/clang/blob/master/test/Driver/modules.cpp
It includes steps to produce .pcm.o files. I'm wondering what they are for.
Given a c++20 module
// a-m.cc
module;
#include <iostream>
export module a;
export void do_a() { std::cout << "A\n"... | The pcm-files contains "half baked" information about a module. The file extension does not have to be pcm and i think Visual Studio for example uses .ifc as extension. (And a difference with Visual Studio is that it outputs the ifc-file and compiles the object file (.obj) at the same time, while clang does this in two... |
66,612,929 | 66,612,991 | Program not working for some reason, could someone pls help me fix it | Could someone please help me fix my program and explain why it s not working?
It's supposed to generate n points with 2 coordinates, which are both random numbers. The values themselves are random but have to scale the interval from 0 to some chosen value k. All the points have to be apart from each other by some radiu... | The first time through your code i and j will both be zero, this means a[i][1] - a[j][1] and a[i][0] - a[j][0] are zero, this resets i to 0, breaks the loop and starts again resulting in an infinite loop.
Checking i != j fixes the problem:
if (i != j && sqrt(pow((a[i][1] - a[j][1]), 2) + pow((a[i][0] - a[j][0]), 2)) <=... |
66,613,751 | 66,613,790 | Passing an 'auto' declared std::shared_ptr<Derived> to std::shared_ptr<Base>& | Compiling with g++ -std=c++11 -pedantic-errors -Wall -Wextra -g
void foo(std::shared_ptr<Base>& ptr) {
std::cout << "foo()\n";
std::cout << "count = " << ptr.use_count() << "\n";
}
int main(int argc, char* argv[]) {
auto d = std::make_shared<Derived>(5);
foo(d);
return 0;
}
I get the followi... |
do all type declarations with auto generate an r-value ?
No. And it's irrelevant here.
d is a std::shared_ptr<Derive>, but foo acceptes std::shared_ptr<Base>, then it needs to be converted to std::shared_ptr<Base>, which is a temporary object (an rvalue) and can't be bound to lvalue-reference to non-const, i.e. std::... |
66,613,918 | 66,614,124 | How can I add line breaks in a wchar_t array? | I'm working on a console game. It uses a screen buffer to refresh the console window after updating the map.
Here's the main while loop.
while (true) {
//player.doStuff(_kbhit());
//map.update();
WriteConsoleOutputCharacter(
console.getScreenBuffer(),
(LPWSTR)map.getScreen(),
map.get... | In short
There are two independent problems here:
The first one is that your newline characters get overwritten.
The second, once you've corrected the first, is that the windows console API does not handle newlines
More details
The problem with the overwriting
I assume that the width does not include the trailing new... |
66,614,003 | 66,614,301 | Segmentation fault error while attempting to create a particle system with OpenGL | I'm trying to create a simple particle system but I'm facing the segmentation fault error. My problem seems to be related to the number of vertex attributes I'm passing. One vertex has 3 floats, corresponding to x, y and z coordinates, so if I want to create 1 million particles, I'll have an array of 3 million floats c... | As per the comment, the use of...
float particleData[NP * 3];
is, potentially, causing a stack overflow. Rather than allocate such a large array on the stack you should consider using std::vector instead. The following is your code with (hopefully) the minimal necessary modifications (look for @G.M. )...
#define NP ... |
66,614,024 | 66,614,071 | glm::rotation doesn't work properly OpenGL C++ | I'm learning OpenGL and now I'm learning more from matrix and I wanted to rotate my texture, but when I'm doing that, it's rotating wrong (idk, only one triangle? I don't know how to explain that). You can see my code and picture with problem below. Thanks for any help. My loop code:
/* My Vertex Array with Struct */
s... | The mesh is clipped by the near and far plane of the orthographic projection. Increase the distance to the near and far plane:
glm::mat4 proj = glm::ortho(0.f, 800.f, 600.f, 0.f, 0.f, 1.f);
glm::mat4 proj = glm::ortho(0.f, 800.f, 600.f, 0.f, -1000.f, 1000.f);
The projection matrix defines the area (volume) with respec... |
66,614,699 | 66,614,923 | Best container for search and insert operation for few elements | I need to chose a container which will store only a few elements and also no duplicates. I will need later to search after the elements. I thought about set and unordered_set, which will be the best option ?
The set will get its elements one by one.
| Just use std::vector. and std::find(...) before inserting. If it's already there, don't. If you need it to be sorted, call std::sort after successful insert.
|
66,614,964 | 66,615,033 | user defined constructor not called when i used parenthesis after the object name | #include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"inside constructor\n";
}
};
int main()
{
A object1;
A object2();
}
Running above code gave below output
$./class.out
inside constructor
Here, only for object1 creation user defined constructor called and not for o... | A object2(); declares a function called object2 that takes no arguments and returns an A. It doesn't create an A object called object2.
You can either use A object2; like you did with object1, or A object2{}; to do what you want.
|
66,615,004 | 66,615,349 | How to save stl container in disk? | I have a stl container, which save a lot of data.
for example, the definition is:
std::unordered_map<std::string, std::vector<int32_t> > m; // there are 10 million data in this container
what i want is to save it in a file, then next time, i can read this file to recover it quickly.
i think the normal way, like:
writ... | Given you're not keen to use boost, the lowest-effort lowest-reusability option is something like:
// some support macros for easy error detection/handling...
#define FATAL(MSG) \
do { \
std::cerr << "FATAL ERROR at line " << __LINE__ << ":\n" \
" " << MSG << '\n'; \
exit(EXIT_FAI... |
66,615,553 | 66,617,313 | Stb_image creates weird artifacts | Hello I am making a image and texture class for my openGL project and when I added stb_image some textures just start adding noise at the edge of the image.
Image class:
Image::Image() {
width = 0;
height = 0;
channels = 0;
data = NULL;
}
Image::Image(const Image& image) {
... | You should read stbi documentation more carefully. It's right there at the start:
int x,y,n;
unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
... replace '0' with '1'..'4' to force that many components per pixel
... but 'n' will always be the number that it would have been if you said 0
Therefore if y... |
66,615,668 | 66,615,669 | Practical example for Dependency Injection and mocking with Googlemock | I'm looking for a simple complete cut and paste example for Dependency Injection and mocking using Googlemock. I have found several theoretical discussion about the issue with code snippets that explains how it works but wasn't able to find a complete running example to cut and paste and try. Is there something availab... | To understand how it works with Googlemock I have made this complete example that I would like to share with other beginners to the topic. According to other Q&A theoretical background is assumed. I run it on a Debian Bullseye system.
There is a class Mylib in a fictional library that method just returns 123. Under tes... |
66,615,688 | 66,615,940 | How to correctly read inputs into a dynamically allocated array of objects | I am currently working on a project which is a ticket storage system that stores each ticket holder as an object.
To input the values, I am using a parameterized constructor. In the main function I have declared a dynamic memory block for an array of these objects.
The main issue I face is that in the for loop that ini... | That is a fine example why malloc is not used in C++, when you allocate memory for your nodes, the elements are not initialized.
Allocation in C++ is done with new wich guards against the aforementioned problem:
node *arr= new node[count];
In this case you'll also need to add a default constructor to your class
node()... |
66,616,002 | 66,616,141 | Is there a preprocessor macro to prevent others include a private header in C++? | I have a private.hpp header that should be used only for 2 classes, this header performs some operations that those classes use, however, other software engineers of my team started to use it in the same module, I had to fix those includes and add more methods to those classes. I want to know if there is a way to throw... | As @S.M. mentionned, you can define a preprocessor variable in the files where you need your secret.hpp :
#define INTERNAL_OPERATIONS_ALLOWED // top of file
#include "secret.hpp"
// ...
#undef INTERNAL_OPERATIONS_ALLOWED // end of file
and add a condition on top of your private.hpp :
#if !defined(INTERNAL_OPERATIONS... |
66,616,844 | 66,617,397 | C++ Boot serialization cause a segmentation fault | I have those two classes and I'm trying to deserialize them using boost
class WorldItem
{
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar &foreground;
ar &background;
ar &breakLevel;
... | Looks like you never return a value from generateWorld.
My compiler warns about this. Try enabling your compiler's diagnostics. I usually have -Wall -Wextra -pedantic enabled
Also in deserialize you never initialize items to anything. That is going to lead to UB.
This, too, could be diagnosed by most compilers (-fsa... |
66,616,848 | 66,616,907 | Why does std::localtime give varying offset from UTC? | I am in the UK, so my timezone is currently the same as UTC. In the following code, if I pass different timestamps to localtime, I get different offsets from UTC (via gmtime). Why is this? My timezone isn't changing from call to call, so I didn't expect the offset to be affected by the timestamp given.
#include <ctime>... | The UK observes daylight savings time, switching to British Summer Time in the summer. Hence, if you pass in a timestamp that falls within the part of the year when British Summer Time is in effect, you will see that your local time is one hour ahead of UTC.
|
66,616,868 | 66,617,585 | Setting/understanding how #define is used in a header file (setting from cmakelist) | I am writing a simple logging library and I am trying to set a compile time definition on the logging level. If I put the #define LOG_COMPILE_MIN_LEVEL in the header file it is not being set at compile time, however if the #define LOG_COMPILE_MIN_LEVEL is in the c file it does work.
Here are snippets of the relevant se... | What could be wrong
Although the example is not proper for reproduction, and the definition of the INFO is not provided, based on the explanation that the token is defined as enum, I have strong filling that this is the problem. The enum types do not mix well with the macros, since enum are constructed in the compile t... |
66,616,951 | 66,617,227 | Put each variadic template argument into container | Is there a way in modern C++ to put each of the variadic template arguments into a container within a std::tuple? For example:
template<class ... T>
class MyClass {
private:
std::tuple<T...> myTuple;
};
int main() {
MyClass<int, char, float> test; //inner class stores an std::tuple<int, char, float>
//is there a way t... |
is there a way to make the inner class store std::tuple<std::vector<int>, std::vector<char>, std::vector<float>
You have simply to unpack the T variadic list inside std::tuple<std::vector<...>>.
I mean
template<class ... T>
class MyClass {
private:
std::tuple<std::vector<T>...> myTuple;
}; // ...........^^^^... |
66,617,103 | 66,618,100 | Requires clause with pure abstract class type parameter? | Consider the following simple concept:
template <typename T>
concept C = requires(T a) { a.f(); };
What should happens if we take an abstract class type as the requires expressions's argument?
struct B { virtual void f() = 0; };
static_assert(C<B>);
gcc-trunk and msvc-trunk pass the assertion, however, clang-trunk, ... | GCC-trunk and MSVC-trunk are correct. The restrictions on the use of abstract types have changed between C++17 and C++20 thanks to P0929. Consequently, even ordinary function declarations with abstract parameter types are now allowed:
void foo(B b); // ill-formed in C++17, well-formed in C++20
void foo(B b) { /* ... *... |
66,617,181 | 66,620,381 | gcc accepts and clang rejects this code with nested generic lambdas, why? | According to Godbolt's Compiler Explorer (see demo), the following code compiles with GCC (both 10.2 and trunk) and outputs 3628800, but fails to compile with Clang (both 11.0.1 and trunk). In both cases, -std=c++17 is used. It also compiles with MSVC 19, but not with other compilers. Why is that and whose behavior is ... | This program is ill-formed, no diagnostic required, so both implementations (indeed, any implementation) are correct. The rule violated is [temp.res.general]/6.4:
a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template p... |
66,617,259 | 66,617,312 | How to check type of container using template struct instead of function? | In this post check type of element in stl container - c++ user UncleBens showed how to check the type of a container using a struct same_type and a function containers_of_same_type
Im trying to do the same thing, except, instead of using a function for checking the containers, I want to use a struct. I have the follow... | std::vector<int>() is a function which returns a std::vector<int>. You need to remove the ().
int main() {
std::cout << SameType<int, int>::result << std::endl;; // 1
std::cout << SameType<int, double>::result << std::endl;; // 0
std::cout << SameContainerType<std::vector<int>, std::list<int>>::value; ... |
66,617,894 | 66,618,157 | C++ syntax understanding issue for 'using' | I read technical documentation for some projects which are created with C++. I found a line of code that contains syntax I don't understand:
using c = char (& (cClass::* [1]) (cClass(*)[2]) &)[3];
I see the using keyword here. That means we deal with an alias, but what does this line do? How can I understand it? I thi... | Here's how your type is read, step by step.
For the sake of clarity, below we declare a variable x.
T x[1]
x is an array (length 1) of type T
cClass::* x[1]
x is an array (length 1) of pointer-to-member inside cClass.
V (cClass::* x[1]) (U)
x is an array (length 1) of pointer-to-member-function inside cClass. Said m... |
66,618,936 | 66,619,030 | Generate a random number depending on input in a defined interval | I want to generate random numbers that deppend on input from user.
For example if user inputs 8, I want to generate number from 5 to 7,
(8 - 3) to (8 - 1)
My code:
#include <iostream>
#include <time.h>
int main()
{
int x1;
int x2;
std::srand(time(0));
while (true)
{
std::cout << "input :... | Addressing your problem
With the expression:
x2 = std::rand() % (x1 - 1) + (x1 - 3);
Using your sample input, rand % (x1 - 1) will be rand % 7, this will render you values from 0 to 6, adding 5 to that you'll have values from 5 to 11.
If you are adamant in using rand you can use something like this:
x2 = rand() / (RA... |
66,619,236 | 66,619,317 | How do I make header files? | I have gotten to a point in my course where they use Code::Blocks to automatically make a header file. However, I don't think it's necessary to download Code::Blocks specifically for this reason, and so I am looking for a way to make my own header files.
And so, I started my search online to find out exactly how to do... | #ifndef FOO
#define FOO
struct foo {};
#endif
The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.
There really isn't any "ma... |
66,619,580 | 66,619,667 | Write multidimensional vectors (tensors) of scalars to file in C++ | The description of the object I have
I have several N-dimensional containers in my code, representing tensors, whose types are defined as
std::vector<std::vector<std::vector<...<double>...>>>
These type of data structures occur in several different sizes and dimensions and they only contain scalar numbers. The number ... | The only way to iterate over something in C++ is a loop, in some sort of shape, matter, or form. So no matter what you're going to have loops. There are no workarounds or alternatives, but it doesn't mean you actually have to write all these loops yourself, one at a time. This is why we have templates in C++. What you ... |
66,619,623 | 66,619,748 | When calling a c function using ctypes.CDLL in Python, the function always gets 0 passed along as argument | The c function I am trying to call:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
long long int n = atoll(argv[1]);
printf("main(%lld)\n", n);
int m = 0;
while (n > 1) {
m++;
if (n % 2 == 0) { //... | TLDR for comment thread:
You should split it into 2 funcs, main and collatz (int collatz(long long n)) and make main just pass atoll(argv[1]) to collatz, so you can run it normally as an executable and also from your python script file as a shared library. You also need to set the argtype in ctypes to long long(I think... |
66,619,882 | 66,620,394 | How to read and display extended ASCII symbols with Windows.h | I'm working on a console game, which uses ASCII symbols as pixels. The map for this game is stored in a .txt file:
ββββββββββββββββ
β β
β β
β β
β β
β β
β β
β β
β β
β β
β β
β β
β... | From a comment:
File is encoded in UTF-8.
That makes a huge difference. Not only are you not dealing with ASCII characters (values up to 127), but you are not even dealing with extended ASCII characters (values up to 255). You are dealing with Unicode, in particular character number 9608 (a.k.a. U+2588). That goes we... |
66,620,254 | 66,620,546 | Do You Have to Virtualize Wrapper Functions? | Suppose I have a class BST and a child class RBT. The class BST has a wrapper function as follows:
void BST::walk(ostream& to)
{
inorder_walk(root, to);
}
Where inorder_walk is a virtual function. When I have a new virtualized inorder_walk function in my RBT class, do I need to make walk virtual as well, even thou... | No, you do not need to make it virtual.
|
66,620,566 | 66,620,882 | Manually calling a function from VTable using pointers creates segmentation fault | When manually calling the second() function I get a segmentation error. I think the problem is that along the way the program loses info dealing with where the first() function is in the memory for the constructed D class when moving the adress forward with +1 in int (*pfunSecond)(int) = (int (*)(int)) *(((void***)pb)[... | Your problems are:
Everything you are doing with the vtable is undefined behaviour. But I suppose you know that, and are willing to accept it.
I assume your layout of the virtual function table is correct; lacking a specific compiler I have no choice. The unary * seems iffy, but I don't know how vtables are laid ou... |
66,620,732 | 66,621,577 | Can't use uint64_t with rdrand as it expects unsigned long long, but uint64_t is defined as unsigned long | I've run into the following annoyance when trying to use rdrand intrinsic.
With my current compiler unsigned long and unsigned long long are both 64-bits. However, uint64_t is defined as unsigned long while _rdrand64_step expects a pointer to unsigned long long.
On Intel's website the function is defined as int _rdrand... | Use unsigned long long n; You can still return it as a uint64_t.
It works fine on the Godbolt compiler explorer with current versions of all 4 major x86 compilers (GCC, clang, ICC, MSVC). Note that _rdrand64_step will only ever work on x86-64 C++ implementations, so that limits the scope of portability concerns a lot... |
66,620,784 | 66,620,960 | C++ - Stream/cout for a variant of the form <int, pair<char,char>> | I have tried every snippet I can find on streaming the contents of a variant but nothing seems to work in my particular use case:
Given a variant of the form std::variant<int,std::pair<char, char>> myVar how can one go about streaming the contents of myVar without explicitly knowing what myVar contains.
For example:
#i... | Your code is (almost) fine, but is not const-correct. A stream output operator should accept the value as a const reference. Yours is not.
While the error messages for template type mismatches can be difficult to read, they do generally tell you the problem. In this case, you'll see it's trying to match const types,... |
66,620,809 | 66,621,715 | C++ runtime polymorphism with templates | My program has observables and observers. Here is the observable.
template <typename E>
class Observable {
private:
std::list<E> observers;
public:
void addObserver(E observer) {
observers.push_back(observer);
}
void notifyAll() {
for (auto & observer: observers) {
obse... | The only issue is this: You must store a pointer to the base class AnimalObserver in your Observable class. You can do this in a number of ways. unique_ptr<> comes to mind.
Here's an implementation with some hints along the way. godbolt: https://godbolt.org/z/1Gq35G
#include <list>
#include <iostream>
#include <memory>... |
66,621,767 | 66,642,562 | Configure Boost.Log v2 | I'm using Boost.Log V2 1.75.0 and setting up my environment from configuration file by using boost::log::init_from_stream(config);
Is it possible to declare colored console sink trough configuration file or is there any way add colored output to the console?
Now, I add as many Console sink as many log level available i... | Creating a formatter with coloring support is described in another answer, here I will focus on how to incorporate that formatter into a settings file.
Boost.Log supports extending its settings file parser by registering sink factories, which you can leverage in your case. Since you can reuse the text_ostream_backend f... |
66,621,806 | 66,621,828 | Where does the control return after calling a function within a | class x{
public:
int A(){
B();//function call
}
int B(){
//print stuff
}
so i am trying to figure out after B() is called where does the control returns after that this program is showing "Compile time exceeds" and if put return after printing would controol go back to the A() or main();
| Control will return back to the A() function since the B() is having int return type it will return with a Int value.
class x{
public:
int A(){
val = B();//function call
//If B() was initialised in a variable value of
// Val will become the return value of B()
}
int B(){
//print stuff
// After Print it will go... |
66,622,086 | 66,622,128 | Why this code is returning wrong value? inputs= 5 ,{ -1,4,-6,7,-4} | #include<iostream>
#include<climits>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i){
cin>>a[n];
} //array instillisation
int cursum=0;
int maxsum=INT_MIN;
for(int i=0;i<n;++i){
cursum+=a[i];
... | In cin you are doing incorrect operation it should be
cin>> a[i];
what you are doing is taking the value of a[n]
|
66,622,435 | 66,622,572 | Why does Code Blocks give me this error after ">>" and "=" overloading? | I'm learning oop and i was working at a small project, but Code Blocks gives my an error i can't explain. The "=" overloading seems to look fine, but if i read an integer after that i get (0xC0000005) error. The project is about creating a class named "Vector" (more like an array) and create some constructors/destructo... | There is a bug in your code.
Vector& Vector::operator = (const Vector &v)
{
if (this !=&v)
{
this->dim=v.dim;
this->p=new int[this->dim];
for(int i=0; i<=this->dim; i++) // your bug here. i should not reach to this -> dim. Change to : i < this->dim
{
(this->p)[i]... |
66,622,628 | 66,622,868 | Is it possible to never use header guards in C/C++? If so, does this approach have any advantage? | I have recently gotten into a project where the usage of header guards is forbidden as it is "bad design". Custom types are forward declared and headers are only included in cpp files.
This is the first project I have seen doing this and I find it quite uncomfortable to work with and if it were up to me I'd introduce t... | Header guards are not "bad design". Refering to Bjarne Stroustrup and Herb Sutter:
SF.8: Use #include guards for all .h files
I would love to see the people behind your new project to argue with Stroustrup and Sutter over what is "bad design" in C++.
Forward declarations are a great tool, yes. But certainly not an an... |
66,622,655 | 66,622,705 | Converting wchar_t to wstring | I always convert wchar_t* to wstring with std::wstring x(y)
But it is not working in this code:
wchar_t f = ctoupper(*cp);
std::wstring cc(f);
cp is a wchar_t*
Error in the std::wstring cc(f) line:
E0289 no instance of constructor "std::basic_string<_Elem, _Traits, _Alloc>::basic_string [with _Elem=... | There is no wstring constructor for a single wchar_t value. You can achieve your intent with the following:
std::wstring cc(1,f);
You can also directly construct a wstring out of a c-style null-terminated wchar_t array:
std::wstring cc(1,f); // wstring made with a wchar_t f repeated 1 time
std::wstrin... |
66,622,763 | 66,625,004 | How to create a time point from milliseconds since Unix epoch? | To create a time point for the current time, you can use: std::chrono::system_clock::now().
I cannot figure out, however, how to create a time point given milliseconds since the UNIX epoch?
Also, is std::chrono::time_point even the recommended way to represent "instants" in time? Or should std::time_t be preferred?
| This is easier/simpler:
std::chrono::system_clock::time_point tp{std::chrono::milliseconds{m}};
The above has a precision of system_clock::precision (microseconds on macOS, nanoseconds on Linux systems, and 1/10 microseconds on Windows). You could also create a time_point with a precision of milliseconds if desired:
... |
66,622,796 | 66,623,212 | Deleting elements from vector inside unordered_map | In my class, I have an unordered map of vectors, like this:
std::unordered_map<State, std::vector<std::shared_ptr<const City>>> citiesByState;
My class also has these two methods:
void addCity(State state, const std::shared_ptr<const City>& city);
void removeCity(State state, const std::shared_ptr<const City>& cit... | TL;DR
You are removing elements from a copy of the vector, not from the std::vector that exists in the found location of the std::unordered_map.
Long story
When you call auto vector = location->second; in Manager::removeCity you're making a copy of that vector inside the scope of the if statement. Therefore, your chang... |
66,622,852 | 66,622,969 | Calling the override function in a vector (C++) | I'm having trouble trying to call the override function of an object that was appended to a vector. I'm not quite sure if I just don't completely understand pointers and references, so I'm not quite sure what to look for when debugging this issue.
Here is my code:
#include <iostream>
#include <vector>
class Task {
... | Try store the base pointer in the vector instead like this. @Christophe asked me to remind that we store pointers which means the Task object
must remain alive. See also also @Quimby's note about using unique_ptr instead of Task *.
#include <iostream>
#include <vector>
class Task {
public:
Task(std::vect... |
66,622,910 | 66,625,303 | Parsing JsonDocument the best way with Qt | I am new to Qt and I have a JSON document received from my home theater kodi and i want to parse it the best way. Can you help me with some code snippet?
Here is my JSON file
{
"id":12345,
"jsonrpc":"2.0",
"result":{
"item":{
"fanart":"",
"id":999,
"label":"xyz",
"thum... | When I need to serialize/deserialize a lot, I like to use the meta type system. I therefore wrote some lines to do this here: https://github.com/carlonluca/lqobjectserializer.
For your case, deserialization could be done by declaring each object as a QGadget or QObject first (this syntax comes from my other project, ht... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.