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 |
|---|---|---|---|---|
71,709,896 | 71,710,020 | Taking Input to Arrays Issue | I'm creating a console timetable application in which you can create a timetable, change it, and delete it. I'm on the stage of taking the input for the calculator. However, when I run the code, as soon as I finish taking the input, the window just closes. Here is the code:
int input()
{
int numberOfElements;
c... | In Standard C++ the size of an array must be a compile time constant. So take for example the following statements in your program:
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};//not standard C++
The statement char* item... |
71,709,962 | 71,711,109 | bucket_count of libc++'s unordered_set.reserve | When I call reserve(n) on a libc++'s empty unordered_set, libc++ find the next prime number as bucket_count if n is not a power of two, otherwise they just use n. This also makes reserve(15) have a bigger bucket_count than reserve(16).
libc++ source:
if (__n == 1)
__n = 2;
else if (__n & (__n - 1))
... | The original commit message sheds some light on this. In short, libc++ originally used just prime numbers. This commit introduces an optimization for power-of-2 numbers in case the user explicitly requests them.
Also note that the new function __constrain_hash() in that commit checks if it is a power-of-2 and then does... |
71,710,026 | 71,710,712 | qt: slot not called guarantee after disconnect of an auto direct connection | I have a single-thread gui application and I do not choose a type of connection, so according to documentation the connection will be a direct one. According to documentation then: "The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread."
For my understanding, this obv... | If you use only direct connections then you can't "receive" any further signals after you disconnected from getting them. Direct connection is just a callback call, nothing more.
|
71,710,274 | 71,728,275 | Why C++ throws an out of range error here? | I really cannot find the reason why here a "cannot seek vector iterator after end" error occurs. I cannot show the whole code but I think that this part should be enough:
qDebug() << Pun.size() << ", " << 2*pos - counter;
Pun.erase(Pun.begin() + 2*pos - counter); //the error seems to happen here
qDebug() << "B";
Pun.er... | Operator precedence problems -- + and - are the same precedence (and are left-recursive), so your erase call is really
Pun.erase((Pun.begin() + 2*pos) - counter);
which probably tries to advance well past the end of Pun, causing it to throw an exception. I'm assuming here Pun is some custom sequence type that does bo... |
71,710,337 | 71,710,475 | How to make clang-format not align parameters to function call? | I want to make clang-format not align call parameters to the '(' symbol. I had tried setting PenaltyBreakBeforeFirstCallParameter to 0, but it didn't help.
How I want it to be:
veeeeeeeryLongFunctionName(
longParameter1, longParameter2,
longParameter3, longParameter4
)
// or
veeeeeeeryLongFunctionName(
lo... | You can use
AlignAfterOpenBracket : BlockIndent
Always break after an open bracket, if the parameters don’t fit on a single line. Closing brackets will be placed on a new line. E.g.:
someLongFunction(
argument1, argument2
)
Reference
|
71,710,357 | 71,710,486 | Why "operator<" for std::vector<int>::iterator seems to compare absolute values when out of range (before .begin())? | cppreference on std::vector doesn't seem to have any links for std::vector<T>::iterator type. Since it is a bidirectional iterator on a contigious memory, I supposed that it can be "negative".
std::distance(vec.begin(), std::prev(vec.begin()) yields -1, and I ended up using std::distance to compare iterators for a loop... | std::distance can yield negative values if applied to valid iterators to the same range and operator< can be used to compare the ordering of valid iterators into the same range. And it does this comparison in the expected way. iterLeft < iterRight will be equivalent to std::distance(iterLeft, iterRight) > 0.
However th... |
71,710,476 | 71,710,752 | How to get the sum of numbers in a vector with two string variables? | How would I get the total of the numbers in the vector of MAXARR?
The code below only sort the vector but I want to know how to the sum of the left part of each array by getting the sum. But I have no clue where to even begin.
This is the code to used to sort vector:
#include <iostream>
#include <string>
#include <ioma... |
How would I get the total of the numbers in the vector of MAXARR?
Use std::accumulate to add up the values.
Use std::stoi to convert the string version of the number to an integer.
#include <numeric>
//...
int32_t total = std::accumulate(arr, arr + MAXARR, 0L,
[&](int32_t total, NameAn... |
71,710,626 | 71,915,383 | Thread 1 "my_app" received signal SIGSEGV, Segmentation fault when accessing API from another library | From my C++ application my_app compiled using G++, I am invoking several API's from another shared library tool.so (tool.so also developed using C++). Each reference of API call from tool.so I am getting the below segmentation fault from the GDB.
Thread 1 "my_app" received signal SIGSEGV, Segmentation fault.
0x00007fff... | it worked by adding this option,
target_link_options(my_app PUBLIC "LINKER:/home/fkamalmu/toollib_1_7_8/lib/linux/tool.so") instead of below way of
linking
add_library(tool SHARED IMPORTED)
set_target_properties(tool PROPERTIES IMPORTED_LOCATION ${TOOL_LIB_DIR}/tool.so)
target_link_libraries(my_app PRIVATE tool)
|
71,710,930 | 71,712,158 | C++: Parse decimal from stream into uint8_t | Is there a way to do the following directly using stream operators?
uint8_t actual;
uint32_t temporary;
std::cin >> std::dec >> temporary;
if (temporary > UINT8_MAX) {
// error
}
actual = static_cast<uint8_t>(temporary);
In particular, I would like to parse a sufficiently small decimal number into a uint8_t without ... | No, I don't think there is a way to read a number directly into unsigned char with a std::istream (std::num_get::get doesn't support unsigned char)
You could encapsulate it into a function:
inline std::uint8_t read_uint8(std::istream& is) {
unsigned short temporary;
is >> temporary;
if (!is) return -1;
... |
71,711,051 | 71,711,236 | C++ operators overload, rules for spaces in expression | I want to learn the rules (if any) about usage of spaces for writing correct operator overloads.
I've seen different forms:
T operator+(T t1, T t2) /* etc. */
T operator+ (T t1, T t2) /* etc. */
T operator +(T t1, T t2) /* etc. */
T operator + (T t1, T t2) /* etc. */
I'm talking about the space(s) between the oper... | Other than in character and string literals, the only place in C++ code where whitespace is significant is to separate tokens that would be (or could be) otherwise merged.
In your case, there is a clear separation between the three tokens, operator, + and (, so the added space characters make no difference whatsoever t... |
71,711,185 | 71,719,783 | How to pass a variable to python script from c++ | There are similar questions & answers to this kind of problem but I still can't find a satisfying answer to my specific problem:
I need to pass a variable (should be a global variable to this python script) to a python script from c++ code. I run this python script using following line in c++:
PyRun_SimpleString ( "exe... | Based on @mbostic 's comment, I did the following and it works:
add this line PyRun_SimpleString("var='From c++' ");
before this PyRun_SimpleString("exec(f.read())");.
This way f is able to access variable var.
|
71,711,736 | 71,713,155 | cURL write_callback does not pass userdata argument | I am trying to collect some data from a URL. If I do not define any CURLOPT_WRITEFUNCTION and CURLOPT_WRITEDATA I can obviously see the output on console. Then I tried to write that data to memory by copiying the example code, however userdata argument of my callback function returned NULL and I got following exceptio... | Since libcurl is a C library, it does not know anything about C++ member functions or objects. You can overcome this "limitation" with relative ease using for example a static member function that is passed a pointer to the class.
See this example (from the everything curl book).
// f is the pointer to your object.
sta... |
71,711,830 | 71,711,909 | CRTP base private constructor and derived friend class cause compilation error using C++17 and uniform initialization | I've got the following code:
struct B
{
B(int) {}
};
template <typename T>
class Base : public B
{
friend T;
Base() : B(1) {}
};
class Derived : public Base<Derived>
{
public:
void do_sth() const {}
};
int main()
{
auto x = Derived{}; //Compiles only when using C++11
auto x1 = Derived(); //Compiles usi... | Apparently Derived is an aggregate since C++17, so Derived{} is an aggregate initialization. (Base classes weren't allowed in aggregates pre-C++17, now public non-virtual bases are allowed.)
Meaning Base::Base() is invoked directly by the caller (main()), rather than Derived.
The solution is to add Derived() {} to Deri... |
71,712,198 | 71,712,809 | Is it possible to create a `map_error` function that takes a lambda? | I am trying to create a map_error method attached to a std::expected type, or something similar. I can't seem to figure out the template meta programming. Is this possible to do something similar to this:
expect<int, fmt_err, io_err> square(int num) {
if (num % 1)
return fmt_err{};
else if (num < 5)
... | You are missing three constructors, here is a working version of your code: https://godbolt.org/z/cxY8Yzzq1
#include <memory>
#include <type_traits>
template <class...>
struct types {
using type = types;
};
template <class Sig>
struct args;
template <class R, class... Args>
struct args<R(Args...)> : types<Args...... |
71,712,249 | 71,712,758 | why only the index 0 changes him value to "" | I'll be directly
Context: I'm making a hangman game
Script "bug" area:
while(lifes > 0){
cout << "word: ";
for(int i=0; i<size; i++){
cout << secret[i];
}
cout << endl;
cout << "lifes: " << lifes << endl;
cout << endl << "choose a letter..." << endl;
cin >> letter;
check=false;
for(int i=0; i<size; ... | ok, given you are trying to learn, and you are not limited by rule of any sort typical of homeworks, you can follow these first steps to do things correctly.
first:
replace those char[] with std::strings.
In c++ you have classes already built to do various stuff, managing strings is one of those, and std::string are th... |
71,712,855 | 71,712,888 | Can anyone explain why does this recursive function crash? | Why does this recursive (i'm not sure about it, the site i found this code said it was "recursive") code crash (i found this weird approach on Internet, but i'm honestly not understanding how it works) entering values >4000 (sometimes >4023, sometimes >4015, i really don't understand...)...
#include <iostream>
unsigned... | The recursive version uses a little bit of stack space every time it calls itself, so it is limited by the size of the stack and will crash if it calls itself too many times. It's a classic stack overflow error.
The iterative second version doesn't have that problem.
|
71,713,077 | 71,713,396 | Strip modifiers from decltype(*this) for use in trailing return type | Let's say I have Base and Derived classes:
class Base {
public:
virtual auto DoSomething(const Base&) const -> decltype(*this) = 0;
};
class Derived : public Base {
public:
const Derived& DoSomething(const Base&) const override; // OK, but not what I want
// Derived DoSomething(const Base&) const overr... | As you noticed, you can make make Base::DoSomething return type Base with std::remove_cvref_t:
class Base {
public:
virtual auto DoSomething(const Base&) const -> std::_remove_cvref_t<decltype(*this)> = 0;
};
However, a function that overrides another function must return either the same type as overridden funct... |
71,713,099 | 71,713,223 | Change base class fields in derived class with base class method | I am not sure where I am wrong here, but there seems to be some miss conception from my side.
I have a base class and a derived class and some methods like in this example.
class Base {
public:
int curr_loc;
Base(int curr_loc):curr_loc(curr_loc)
void reset(int curr_loc){
curr_loc = curr_loc;
... | This code snippet
class Base {
public:
int curr_loc;
Base(int curr_loc):curr_loc(curr_loc)
void reset(int curr_loc){
curr_loc = curr_loc;
}
}
class Derived: public Base{
public:
Derived(int curr_loc):Base(curr_loc)
}
has syntactic errors.
You need to write
class Base {
public:
... |
71,713,307 | 71,714,123 | Why is std::ranges::views::take using templated type for difference? | Signature of take is
template< ranges::viewable_range R, class DifferenceType >
requires /* ... */
constexpr ranges::view auto take( R&& r, DifferenceType&& count );
It is a minor thing but I wonder why DifferenceType is not some ssize type(practically int64_t on modern machines).
Is this just to avoid warnings ... |
It is a minor thing but I wonder why DifferenceType is not some ssize
type(practically int64_t on modern machines). Is this just to avoid
warnings on comparisons of integers of different signednes, or is
there some other design reason I am missing.
Iterators for different range adaptors have different difference_type... |
71,713,596 | 71,713,638 | "Undefined symbols for architecture arm64" - What does this mean? | I'm unable to get my code to run, and the internet doesn't seem to know why. I'm not sure what I need to let you know, but I am using CLion if that helps.
This is my plant.h file:
#ifndef COURSEWORK_PLANT_H
#define COURSEWORK_PLANT_H
using namespace std;
class Plant {
public:
void addGrowth();
int getSize();
... | Undefined symbol means that the symbols is declared but not defined.
For example in the class definition you have the following member function without parameters
void addGrowth();
But then you defined a function with the same name but now with one parameter
void Plant::addGrowth(int x) {
plantSize += x;
cout ... |
71,714,086 | 71,714,122 | Error: Type 'Classname' does not provide a call operator | Working on a program involving matrices and hit with an error involving Multiply and Transpose methods. I'm not sure how to proceed
//Header file
class Matrix
{
public:
Matrix(); // constructor
void initIdentity(int n); // initialize as an identity matrix of size n... | As noted in comments, you have:
ans(i, j) = matrix_[i][j] * A;
Which is trying to call operator() on ans. But you haven't defined this operator for this type of object.
You'd either need to define that operator so this code works, or just use the existing setVal:
ans.setVal(i, j, matrix_[i][j] * A);
|
71,714,560 | 71,714,935 | curl PUT JSON body having issues processing array's | I'm developing a library that communicates with a REST API. The method I wrote for PUT calls has worked up until this point.
void Command::put(const std::string url, const std::string body)
{
CURLcode ret;
struct curl_slist *slist1;
slist1 = NULL;
// slist1 = curl_slist_append(slist1, "Content-Type: multipart... | You need to change this line:
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)12);
To this instead:
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)body.size());
Or, simply omit CURLOPT_POSTFIELDSIZE_LARGE completely, since body.c_str() is a pointer to a null-terminated string in this ... |
71,714,972 | 71,715,183 | How can i adding more nodes in first.cc in ns3? | I've just learned about first.cc and I want to change the number of nodes in first.cc from 2 to 3 or 4 5, but changing only nodes.Create(2) ==> nodes.Create(3) causes me some errors like this
assert failed.cond="c.GetN () ==2" , +0.00000000s -1 file=../src/point-to-point/helper/point-to-point-helper.cc, line=224
termin... | I want to start by encouraging you to use gdb (or lldb) to debug the program. If you did this, you would have found that this line in first.cc is causing the error:
devices = pointToPoint.Install (nodes);
Why would this happen? Well, if we go to the definition of the function being called, we find:
NetDeviceContainer ... |
71,715,505 | 71,715,932 | How to create Mouse right click menu option using eventFilter in Qt? | I have a QGraphicsView which contains many QGraphicsItem. If I click mouse right click on any QGraphicsItem, the item should get select and right menu options should appear and then I will choose one of the options among them.To do that I have installed eventFilter and through it, I am using ContextMenu to create right... | In your approach you show a context menu when you have no information if any item is selected. It is rather bad idea. You don't want to show the context menu in any location of view. You have to check if a cursor mouse is over an item.
Why not to derive from QGraphicsItem and just overload mousePressEvent method. Insid... |
71,715,630 | 71,715,789 | C++ Max Heap not sorting correctly after remove max | I'm attempting to remove the max by swapping the first and last element of the vector and then using pop_back. When I remove max I output max but the reordering process is not working correctly and I cannot figure out why.
I have attempted changing the way I am testing multiple times and the results do not change. Can ... | Your math is completely wrong. You're confusing stored values with index calculations. In some places you are calculating values by multiplying indexes, in other you are calculating indexes by multiplying stored values. That's never going to work.
void remove_max()
{
if (heap.empty())
return;
std::swap... |
71,716,106 | 71,716,256 | Can't execute program from the source code even though the compiling process had no error and warnings(Dev C++) | Source Code :
#include <stdio.h>
#include <conio.h>
using namespace std;
int main () {
char huruf;
char nama[]="Muhammad Juan Syarin";
int usia, berat, tinggi;
int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}
huruf='M';usia=19;berat=68;tinggi=170;
printf("Huruf depan : %s", huruf);
printf("Nama Lengk... | You missed a semicolon while defining the array. Also the format specifier in the first printf statement is for strings, not characters. Replace the %s there with %c. So in change line 10 to int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; and replace %s in line 13 to %c
|
71,716,181 | 71,727,052 | embedded python using pybind11 in c++ class: how to call member function of c++ class from python | I've a class with a method (MyClass::methodWithPy) that can be customized by some python script using embedded pybind11, which so far works.
Inside the python script I need to somehow call methods of the c++ class. Is this possible somehow?
This is what I have so far, but I do not know how to call the class method from... | Thanks @unddoch for the link. That got me to the answer.
PYBIND11_EMBEDDED_MODULE was the part I was missing.
First you need to define an embedded python module containing the class and the methos:
PYBIND11_EMBEDDED_MODULE(myModule, m)
{
py::class_<MyClass>(m, "MyClass")
.def("pureCMethod", &MyClass::pureCM... |
71,716,400 | 71,716,416 | error with vector, unique_ptr, and push_back | I am learning smart pointers, with the following example test.cpp
#include<iostream>
#include<vector>
#include<memory>
struct abstractShape
{
virtual void Print() const=0;
};
struct Square: public abstractShape
{
void Print() const override{
std::cout<<"Square\n";
}
};
int main(){
std::vector... | push_back expects an std::unique_ptr, when passing raw pointer like new Square, which is considered as copy-initialization, the raw pointer needs to be converted to std::unique_ptr implicitly. The implicit conversion fails because std::unique_ptr's conversion constructor from raw pointer is marked as explicit.
emplace_... |
71,717,145 | 71,717,178 | C++ class properties not updating properly | I have a custom galaxy class which has a custom property pos.
pos is an instance of another custom class Vector3D.
A Vector3D has properties x, y, z. The arithmetic operations for Vector3D is basic vector math, the relevant ones below:
Vector3D Vector3D::operator+(const Vector3D& vec) {
return Vector3D(x + vec.x, y... | auto returns a copy of the object, so the original one is copied, not modified. You're then altering a copy of the original object.
Using & will make you reference the original one, so that you can alter it.
for (auto & g : galaxies) {
Vector3D accel = Vector3D();
for (auto & g2 : galaxies) {
if (g != g... |
71,717,211 | 71,717,237 | C++ Single line If-Else within Loop | I read Why I don't need brackets for loop and if statement, but I don't have enough reputation points to reply with a follow-up question.
I know it's bad practice, but I have been challenged to minimise the lines of code I use.
Can you do this in any version of C++?
a_loop()
if ( condition ) statement else statemen... | Yes, syntactically you can do that.
if/else block is a selection-statement, which is a kind of statement.
N3337 6.4 Selection statements says:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
|
71,717,523 | 71,717,625 | Is it legal to use struct itself as template argument? | According to Template parameters and template arguments on cppreference.com:
A template argument for a type template parameter must be a type-id,
which may name an incomplete type
That means that this example (copied from that page) is legal:
// Example 0
template <typename T>
struct X {};
struct A;
int main() {
... | This is CWG issue 287.
You can look at the reasoning there, but my understanding from it is that the consensus is that the standard technically currently doesn't allow either your last or second-to-last example, since the point of instantiation of X<A> will be before the definition of A, where typename T::type cannot b... |
71,717,779 | 71,717,992 | How do I refer to a class with multiple template types by only one of the types? | Let's say I have a class Shape with the declaration:
template <typename T, typename U, typename V>
class Shape {
T value;
U input;
V input2;
...
}
As it is, if I create a Shape object, its type will be something like Shape<int, float, double> - for example.
But what if I want to be able to create a Shape... | It seems like you are looking for CTAD (class template argument deduction). It only works when the caller does not specify any template argument, hence a layer of indirection has to be added:
template <typename T>
struct ShapeWrap {
template <typename U,typename V>
struct Shape {
T value;
U inpu... |
71,718,036 | 71,718,136 | Program only allows login if the email matches the last registered user. C++ | So, I've been trying to make this program this entire day and I got stuck at this big problem where I cannot it to log into the account by verifying with the previously existing data in my txt file of registered users.
NOTE: userEmail is inheritted from another class and is defined.
This is my login function:
void logI... | Break out of the while loop immediately after you set verifyEmail = true. There is no need to check additional email addresses if you have already found a match. As it is, your code goes on to check non-matching email addresses, setting verifyEmail back to false.
For example:
while(checkEmail>>userEmail && loginEmail.f... |
71,718,142 | 71,718,912 | Race condition when increase a variable value in c++ | I was asked this question in an interview recently. The question is if we have a function that takes a reference of int i as parameter and only does i++. There is no any thread synchronizations. Now in main function, we initialize variable i with 0, then we create 7 new threads to run the same function and pass the sam... | The specific instructions used to increment the variable depends on the instruction set, but unless using some kind of atomic increment, it will break down into load/add/store operations as you are describing. On x86 that might be done with a single inc instruction, but without locking it will still break down to inte... |
71,718,249 | 71,718,895 | STL-style algorithm: returning via OutputIterator | I am trying to implement an algorithm that merges elements in an ordered container, if they satisfy a BinaryPredicate.
template <typename ForwardIt,
typename OutputIt,
typename BinaryPredicate,
typename Merge>
void merge_adjacent(ForwardIt first,
ForwardIt last,
... | You may be looking for something like this:
template <typename InputIt,
typename OutputIt,
typename BinaryPredicate,
typename Merge>
void merge_adjacent(InputIt first,
InputIt last,
OutputIt out,
BinaryPredicate pred,
... |
71,718,840 | 71,718,900 | << operator overloading and template specialization | As part of study purpose, I was just playing with template specialization together with operator overloading
#include <iostream>
template<class T>
void operator<<(std::ostream& COUT,T val)
{
std::operator<<(COUT,val); //works for basic data types
}
//specializing for const char*
template<>
void operator<<(std::ost... | The problem is there is already operator<<(std::ostream& COUT,const char* val) defined by the standard library.
So now there are two symbols
std::operator<<(std::ostream& ostream,const char* val);
operator<<(std::ostream& COUT,const char* val); // YOURS
Because the symbols are different, there are no multiple-definiti... |
71,718,920 | 71,718,982 | gcc: invalid error "use of deleted function" (copy constructor)? | Simplified issue:
#include <stdio.h>
class X
{
public:
int a = 0;
X() { printf("constr-def %d\n", a); }
X(int i):a(i+1) { printf("constr-i %d\n", a); }
int operator=(int i) { a = i; return i; }
operator bool() { return !!a; }
//~ X(const X& o) { a = o.a; printf("copy-constr %d\n", a); };
... | Before C++17 such copy elision is an optimization, which is permitted but the copy (or move) constructor still must be present and accessible.
Since C++17 the code works fine because for mandatory copy elision the copy/move constructors need not be present or accessible again.
C++17 core language specification of prva... |
71,719,266 | 71,719,599 | C++17 decorate lambda or member function with non-capturing lambda | I'm trying to craft a function that returns a non-capturing lambda (so it can be converted to a function pointer) that decorates an inner function, where the inner function can be either a lambda or a member function pointer.
Compiler Explorer link for reference, which I'll dissect in the following.
I've come up with t... | First, your decorate_lambda is buggy: it silently breaks if you call it with a stateful callable. As a simple check, you could allow callables only if std::is_empty_v is true.
The end result that I would like is to roll decorate_lambda and decorate_memfn into a single decorate(lambda_or_memfn) function
You can use s... |
71,719,326 | 71,719,468 | Writing a custom std::next_permutation(string) function | I am trying to implement a function similar to std::next_permutation(std::string w). Please see the code below for how I am doing this:
string biggerIsGreater(string w) {
// 1. Find the largest non-increasing suffix. This suffix already has the maximum permutation.
// 2. Assign the char before that as the pivot... | I re-implemented your function my own way, if it is not an acceptable answer, then at least it is benefitial for educational purpose. Maybe by my code you can figure out what's wrong in yours.
If this is last permutation, like "bb" case then first lexicographical permutation is returned, same as in std::next_permutatio... |
71,719,493 | 71,720,203 | Function or library to create strings from every primitive data type and String? | Is there a function to create strings or char[] by concatenating multiple types?
Something like:
int int_type = 5;
float float_type = 3.14;
String string_type = "I'm";
char char_type = ' ';
char char_arr_type[9] = "a pirate";
String merged = x_func(int_type, float_type, string_type, char_type, char_arr_type);
// exp... | in c++17 you can use fold expression and string stream.
Example:
#include <iostream>
#include <sstream>
using namespace std;
template<typename ... Args>
string makeString(Args ... args)
{
stringstream ss;
(ss << ... << args);
return ss.str();
}
int main(){
cout<< makeString("a b" , 1, "c d");
}
Out... |
71,719,584 | 71,720,289 | Convert Vector of integers into 2d array of type const int* const* | I have a vector of integers that I should make into a 2d array. The row and column size of the new 2d array are given by user and contain all the integers from previous vector. The 2d array should be of type const int* const*. How do I do this in c++?
| Try something like this:
std::vector<int> nums;
// fill nums as needed...
int rows, cols;
std::cin >> rows >> cols;
if ((rows * cols) > nums.size())
// error
int** arr = new int*[rows];
for (int row = 0; row < rows; ++row) {
arr[row] = new int[cols];
for (int col = 0; col < cols; ++col) {
arr[row... |
71,719,941 | 71,720,000 | C++ Function to be called later | I am a complete beginner just started to learning C++. I want to make function say a formula which would take square of a variable. Check the code below to understand better
double raiseToPow(double x, int power)
{
double result;
int i;
result = 1.0;
for (i = 1; i <= power; i++)
{
result *... | For now, add a main function and call that function. Add this to your code:
#include <iostream>
int main() {
double value = 2.0;
double result = raiseToPow(value, 2);
std::cout << result << 'n';
return 0;
}
Compile the file into an executable and run the executable.
|
71,720,133 | 71,720,607 | Deleted assignment operator error which isn't used | Implicitly deleted member assignment causes a compile error in code that never calls the assignment operator.
#include <vector>
struct A {
A(int arg) : i{ arg } {}
// A& operator=(const A& arg) { return *this; }
const int i;
};
int main()
{
std::vector<A> v;
v.emplace_back(1); // vector of one A ... | Consider how the erase function might be implemented. It might look something like this:
constexpr iterator erase(iterator pos) {
for (auto i = pos; i + 1 != end(); i++) {
*i = move(*(i + 1));
}
pop_back();
return pos;
}
(The real parameter type is const_iterator, but let's ignore this detail.)... |
71,720,201 | 71,720,467 | Why does MSVC compiler put template instantiation binaries in assembly? | I encountered something weird in the MSVC compiler.
it puts function template definition in assembly while optimization eliminates the need for them.
It seems that Clang and GCC successfully remove function definition at all but MSVC does not.
Can it be fixed?
main.cpp:
#include <iostream>
template <int n> int value()... | The /FA switch generates the listing file for each translation unit. Since this is before the linking stage, MSVC does not determine if those two functions are required anywhere else within the program, and are thus still included in the generated .asm file (Note: this may be for simplicity on MS's part, since it can t... |
71,720,217 | 71,720,265 | Why can vectors be instantiated like arrays? | I was learning about classes in my C++ class, and I was trying to understand some of the things about common classes I've used. One of which being vector. I looked through the vector reference on Cplusplus.com, but there was one thing that I couldn't quite understand and was having trouble finding answers to it online.... | This uses an std::initializer_list. Just like "string" forms a string, {element1, element2, ...} forms an initializer list that can be converted to a vector, or another datatype.
For example, we could construct an array manually doing the following:
int w[4];
auto x = {1, 2, 3, 4}; //type is std::initializer_list
int ... |
71,720,245 | 71,727,011 | PubSubClient.publish tries convert char into unsinged int and throws error | First of all, I am a far cry from a being an experienced programmer, so please forgive me if I am asking beginners question here.
I encountered a problem trying to publish a payload using the PubSubClient on an ESP8266. I am using VS Code with Platformio.
During Build I receive the following error. It seems like the Pu... | Your mqttMessageCharArray is of type char[] (which decays to char* on passing to function), whereas your mqttClient->publish() takes a uint8_t* as its second argument.
It can simply be fixed by replacing the last line with :-
mqttClient->publish(relay_Status, (uint8_t*)&mqttMessageCharArray, msglength, false);
Here we... |
71,721,417 | 71,723,954 | How to set correct directory path in add_subdirectory function? | Using Android Studio and have two libraries, Lib(A) and Lib(B), there are two CMakeList.txt for each project.
I want to know how can I set add_subdirectory in Lib(A) because in run mode can not detect function in Lib(B), I guess the compiler/Gradle ignores CMakelist of Lib(B).
libraries structure:
A
|--src
|--mai... | The first parameter of add_subdirectory takes the path to the directory containing the CMakeLists.txt file to include. If this path is relative, it's resolved relative to the directory containing the CMakeLists.txt currently being parsed.
If you specify an absolute path or a relative path navigating to a parent directo... |
71,722,140 | 71,722,154 | C++, operator [], and tracking a change | I'm trying to build a little array-ish class, like so:
class dumb
{
bool mChanged=false;
int mData[1000];
int& operator [](int i) {return mData[i];}
};
Here's my question-- is there any kind of hack or trick I could do so that if I did this:
dumb aDumbStuff;
aDumbStuff[5]=25; <- now mChanged gets set to t... | You could set the flag to 'changed' inside your existing operator[] method, and add a second version with const returning an int (= not as a reference):
int operator [](int i) const {return mData[i];}
The compiler would pick the right one - modifying or not, as needed!
|
71,722,164 | 71,722,216 | Is it possible to use fold expression in class template deduction guide? | I did a simple test as follow:
#include <iostream>
template <typename T, std::size_t N, std::size_t D> struct MyArray {
template <typename First, typename ... Rest> MyArray(First, Rest...);
int dimension[N];
T m_array[D];
};
template <typename First, typename... Rest> MyArray(First first, Rest... values)
... | You cannot use the values of function arguments inside constant expressions and here in particular not in a template argument.
If you want to deduce the type differently for different values, you need to make sure that the type also differs from value to value.
Example:
#include<type_traits>
template<auto V>
constexpr... |
71,722,452 | 71,724,140 | C++ Using upper_bound instead of find () | I need advice on how to modify the program so that I can search using the upper/lower_bound function. The program works correctly(ok asserts) for the find () function.
I sort the company database after each insertion or deletion, so that's probably not the problem
In the link I enclose the whole program for a better un... | If DCompany is sorted with respect to Company::operator< (i.e. with respect to the company tax ID), then you can do:
bool CVATRegister::cancelCompany ( const string &taxID )
{
Company const cmp("", "", taxID);
auto const itr = lower_bound(DCompany.begin(), DCompany.end(), cmp);
if(itr != DCompany.end()... |
71,722,565 | 71,722,841 | create number pattern into a string vector | new to programming so I apologize if this has been answered before...I have tried searching with almost zero luck.
I am trying to create a number pattern like 1,2,2,3,3,3,4,4,4,4 etc;
I have gotten to that point but I need to put it into a string vector so that if the user inputs 5, the string vector elements are 1,2,2... | If you really need a vector of strings, and need to reproduce the output in a comma-separated pattern, you can do something simple like:
#include <iostream>
#include <vector>
#include <string>
int main () {
size_t n = 0; /* unsigned variable for n */
std::vector<std::string> pattern{};... |
71,723,099 | 71,725,647 | What is the macOS alternative to namespaces(7) in Linux or jails in FreeBSD? | When I was using Linux I used to use Linux namespaces:
https://man7.org/linux/man-pages/man7/namespaces.7.html
Also on FreeBSD, there are jails:
https://www.freebsd.org/cgi/man.cgi?jail
I was wondering what the alternative was on macOS 12? I'm new to Macs so I'm just trying to learn the system and any features it might... | The equivalent feature to FreeBSD's jails and linux namespaces for macOS is the App Sandbox.
You can find relevant details in the App Sandbox Design Guide.
|
71,723,586 | 71,746,927 | Insert indices to pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> in PCL Library | I'm trying to partitioning & perform some actions to a point cloud using pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree.
In the method, it provides a public function called
setInputCloud(const PointCloudConstPtr &cloud_arg, IndicesConstPtr &indices_arg = IndicesConstPtr ())
In the doc, the explanation is us... | Found the solution to the above question.
PCL Function
setInputCloud(const PointCloudConstPtr &cloud_arg, IndicesConstPtr &indices_arg = IndicesConstPtr ())
accepts indices but you have to convert it to the pcl::IndicesPtr type.
So, My solution was to,
pcl::IndicesPtr indicesTemp(new std::vector<int>());
std::copy(se... |
71,723,659 | 71,733,621 | how to run a membber function with QtConcurrrent Qt6? type 'decay_t cannot be used prior to '::' because it has no members) | i'm trying to run a member function but but i got an error , help me please
i tried with this line of code
QFuture<qlonglong> future = QtConcurrent::run(this,&backD::analysa);
and analysa() is a methode that returns a qlonglong
| Try QtConcurrent::run([this]{ return analysa(); }); or QtConcurrent::run([this] -> qlonglong { return analysa(); });, whichever compiles in your case.
|
71,724,023 | 71,724,052 | C++ Error checking before constructor delegation | I have a constructor that creates a matrix from size_t dimensions, I want to add support for int dimensions. However, before passing the ints to the size_t constructor I would like to make sure that they are positive.
Matrix(vector<double> vals, int rows, int cols )
\\throw something if rows<= 0 || cols<= 0
:Matrix(... | Pass them through a function,
int enforce_positive(int x)
{
if (x <= 0) {
throw something;
}
return x;
}
Matrix(vector<double> vals, int rows, int cols )
: Matrix(vals,
static_cast<size_t>(enforce_positive(rows)),
static_cast<size_t>(enforce_positive(cols)))
You can... |
71,724,261 | 71,725,495 | How detect and avoid multi-threading conflict in a loop with OpenMP compilation? | I am using an open-source simulation software that can be compiled with OpenMP-enabled cmake option. (https://github.com/oofem/oofem/)
In my class I am calling the following method in a for loop:
MaterialStatus *
Material :: giveStatus(GaussPoint *gp) const
/*
* returns material status in gp corresponding to specific ... | giveStatus is clearly not thread-safe. Thus, calling it from multiple threads in parallel cause a race-condition. Indeed, some threads can concurrently check if status is null and can enter the conditional in parallel. Then status is set by multiple thread causing an undefined behavior (typically an outcome that is dep... |
71,724,404 | 71,724,502 | template deduction of member functions | I'm trying to understand template argument deduction with regular functions, pointer to regular functions, member functions and pointer to member functions. Can someone explain why the last line yields a compile error while there is no issue with standalone?
#include <iostream>
#include <type_traits>
struct A {
i... | The problem is that we cannot pass a reference to a member because from Pointers to members:
The type “pointer to member” is distinct from the type “pointer”, that is,
a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer
declarator syntax. There is no “reference-to-... |
71,724,511 | 71,724,540 | How to use read syscall with an integer fd in C++ | I am working with sockets. On creating one using socket(), we get an integer file descriptor. I then want to read data from this fd.
To do so, I was following functioning C code - using the read() syscall, in the following line:
read (sockfd /* int */, buff /* char* */, 50);
However, compiling gives the error "read wa... | You might be missing #include <unistd.h>
But I also recommend using recv, which is declared in sys/socket.h
If you're stuck, always try manpages: man read.2
|
71,724,709 | 71,725,060 | How to get all process in task manager with Microsoft API using C++ in win 64bit | I have a block code below.
I want to get all processes in tasks manager with C++ but it not work.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess( PROCE... | You should try to link with Psapi.lib.
Your errors are linker errors. The linker is creating the final exe, after the compiler compiled the source files to object files.
When you use functions like EnumProcessModulesEx from from <psapi.h>, you need to link with their implementation.
It is recommended to read the docume... |
71,725,753 | 71,727,587 | Truly Lock-free MPMC Ring Buffer? Threads able to assist each other to avoid blocking? | This question is inspired by Lock-free Progress Guarantees. The code shown is not strictly lock-free. Whenever a writer thread is suspended when the queue is not empty or not full, the reader threads returned false, preventing the whole data structure from making progress.
What should be the correct behavior for a tru... | As a good example of how cross-thread assist often ends up working in real life, consider that a lock-free MPMC queue can be obtained by changing the liblfds algorithm along these lines:
Use 3 counters:
alloc_pos: the total number of push operations that have been started. This is incremented atomically when a push s... |
71,726,052 | 71,726,332 | Can a base class and a derived class of that base class have a common friend class which is a friend of both the classes? | I know that a friend class can access the private elements of a class, so I was wondering weather a derived class can use a friend class to access the private members of the base class, if the friend class is friends with both the base class and the derived class?
I am a complete beginner in programming and I have just... | In C++,
In order to grant access to private or protected members of a class, we should define a friend class or a function (or a method of another class).
Friendship is not inherited.
So in order to access private or protected members of a base class and derived class, from another class you should define the "another... |
71,726,178 | 71,726,422 | Why the code snippet gets stuck when optimization is enabled? | There are three question about the code snippet below.
When the macro(i.e. NO_STUCK_WITH_OPTIMIZATION ) is not enabled, why this code snippet gets stuck when the optimization is enabled(i.e. -O1, -O2 or -O3) whereas the program works well if the optimization is not enabled?
And why the program no longer get stuck if s... | You have a multi-threaded program. One thread does is_run = 0;.
The other thread does while(1==is_run). Although you guarantee, with a sleep (matter for another question), that the write is done before the read, you need to tell the compiler to synchronize this variable.
In C++, the simple way to make sure one thread s... |
71,726,679 | 71,726,809 | Count square numbers in array using count function | I need to count how many numbers are perfect squares in array of integer values, using a function from the algorithm library.
I have chosen the std::count() function to do that:
#include <algorithm>
#include <iostream>
#include <math.h>
bool is_square_number(int x) {
if (x >= 0) {
long long sr = sqrt(x);
retu... | First, you are confusing the std::count function – which just counts how many values in the container/range are equal to the last parameter (which is a value, not a function)1 – with the std::count_if function (which counts how many values satisfy the predicate, specified as the last parameter and should be a function ... |
71,726,692 | 71,726,738 | what do three dots(...) in c++ mean ? | for exmple:
msg is a class whith (operator <<)
msg << ... << args
[source code path][1]
what does three dots (...) imply? anyone know this, please tell me
[1]: https://github.com/Kistler-Group/sdbus-cpp/blob/5caea3b72bf783d88c3fa36eb8cf97cc10a71170/include/sdbus-c%2B%2B/Message.h#L295
| This is a template parameter pack (variadic template)
If you search for variadic template c++ you will find many questions on here related to it.
There is also en.cppreference.com.
https://en.cppreference.com/w/cpp/language/variadic_arguments
https://en.cppreference.com/w/cpp/language/parameter_pack
|
71,726,899 | 71,727,038 | How to make that equal values in array will be written inside brackets? | I'm new at C++ and I'm trying to solve this problem. Here is the code.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int my_rand_arr(int a, int b);
void random_arr(int arr[], int n);
void output_arr(int arr[], int n);
int main(){
srand(time(0));
const int N = 20;
int arr[N];
r... | Just count the number of repetitons of each element and print the elements when reaching the a different element or the end of the array.
void output_arr(int arr[], size_t const n) {
auto pos = arr;
auto const end = arr + n;
while (pos != end)
{
size_t count = 1;
auto const element = *p... |
71,727,455 | 71,727,518 | Simplify C++ inclusion with macros | Considering a C++ project with an include folder inside which the source code of several repositories is placed, how could I simplify their inclusion in the main file?
I tried something like this:
// config.h
#define SOMEPROJ_SRC_PATH "include/someproj/src/"
#define EXPAND_PATH(root, filepath) #root #filepath
//main.c... | The right way to do it is to pass SOMEPROJ_SRC_PATH as a search path of include files with -I option.
main.cpp:
#include <iostream>
#include "some.h"
int main() {
std::cout << HELLO << std::endl;
}
/some/path/some.h:
#define HELLO "Hello, world!"
And then compile it:
g++ -I /some/path -o main main.cpp
|
71,727,501 | 71,727,679 | c++ fetching web page using wininet | I'm trying to download a web page using WinInet. I've used the code given here: http://www.cplusplus.com/forum/windows/109799/
It mostly works, but there seems to be some encoding issue that I have no idea how to fix.
For instance, this line (using www.stackoverflow.com as an example page):
<link rel="stylesheet" type=... | In this code:
while(InternetReadFile(OpenAddress, DataReceived, 4096, &NumberOfBytesRead) && NumberOfBytesRead )
{
cout << DataReceived;
}
DataReceived is receiving arbitrary bytes. It is not a null-terminated string, but the code is passing it to the operator<< overload that expects a null-terminated string. So t... |
71,727,530 | 71,806,716 | How to find indexes of elements in recursive-knapsack? | I'm trying to implement recursive Knapsack which would return 2 things:
Max value we get by filling knapsack.
Indexes of the elements considered for filling the knapsack.
Please note that I don't want to use Dynamic Programming Approach to get this done (by reverse iterating the 2-D matrix to get the indexes of eleme... | The vector idx is passed by reference: vector<int>& idx.
The issue is that here:
int consider = val[N - 1] + knapsack(wt, val, W - wt[N - 1], N - 1, idx);
int dontconsider = knapsack(wt, val, W, N - 1, idx);
This vector idx is modified twice.
One solution is to create a temporary vector for the first call...
#includ... |
71,728,040 | 71,728,102 | Error C2011, Tried everything already asked on here | i am new to Cpp and am having this error:
Error C2011 'point2d': 'struct' type redefinition
it is the first time i use modules, and i am having an error with the headers. Here is my code:
squarecell.cc:
#include <vector>
#include "squarecell.h"
using namespace std;
struct point2d {
point2d(int x, int y) {
... | The issue is in the source file, not the header.
Implementations are done like this:
point2d::point2d(int x, int y) { ... }
Not like this:
struct point2d {
point2d(int x, int y) { ... }
};
|
71,728,124 | 71,728,169 | C++ Error (Segmentation fault / Bus error / Memory limit exceeded / Stack limit exceeded) when using functions lower_bound, sort, | My program crashes after uploading to the school test server with the announcement that one of these errors has occurred (Segmentation fault / Bus error / Memory limit exceeded / Stack limit exceeded), I have no exact information. If I run the program in the debugger, I can't find anything. The audit method may fail.
T... | That sort lambda doesn't provide strict weak ordering as required by std::sort. Both sort and lower_bound can/will fail.
Did you mean?
sort(tmp.begin(), tmp.end(), [](const Company & a, const Company & b)
{
if ( a.getName() != b.getName())
return a.getName() < b.getName();
return a.... |
71,728,125 | 73,003,610 | Getting Arduino IDE to compile for C++14 | I've been looking to modify the build flags under Arduino's IDE 1.x, or even the Arduino CLI (which I haven't used but am willing to adopt) such that I can undefine -std=gnu++11 and instead define -std=gnu++14
I found a question related to this which gives me almost what I need:
Arduino 1.0.6: How to change compiler fl... | You can modify the default compile flags in the hardware/arduino/avr/platform.txt file.
$ grep -n "std" hardware/arduino/avr/platform.txt
23:compiler.c.flags=-c -g -Os {compiler.warning_flags} -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects
28:compiler.cpp.flags=-c -g -Os {compiler.warnin... |
71,728,218 | 71,728,324 | Why is C++ copy constructor called twice? | I have some code that returns a class object by value and the copy constructor is being called more than I thought it would. This seems to be how the g++ compiler does things but I'm not sure why. Say I have this code:
#include <memory>
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "con... | Pre-C++17
In Pre-C++17 standard there was non-mandatory copy elison, so by using the -fno-elide-constructors flag you are disabling the return value optimization and some other optimizations where copies are elided.
This is what is happening in your program:
First due to the return statement return A(); an object is c... |
71,728,323 | 71,728,967 | How do you access the menus given a QMenuBar? | In Qt how do you recover the menus given a populated QMenuBar?
They do not seem to be the menu bar's children. For example, after the following (where the menu creation functions succeed and do what you expect)
menuBar()->addMenu(create_file_menu(this));
menuBar()->addMenu(create_view_menu(this));
auto children = menuB... | A QMenu is added to a QMenuBar internaly via QWidget::addAction(menu->menuAction()) (see <QtInstallPath/src\widgets\widgets\qmenubar.cpp>.
From QWidget you can retrieve the added QActions via QWidget::actions() - method which returns a list of associated QActions. In your specific example menuBar()->actions() should re... |
71,728,842 | 71,729,048 | Problem on std::sort with QObject and QVector<MyQObject*> | I have a problem with sort of QVector<MyQObject*>. This is in real case of use for listing directorys and datas (like ls unix command). Here in this example "/Users/Stephane/" on my unix mac os computer.
The std::sort function doesn't work, I'm sure I have done a mistake.
Here are my files of Console Qt:
entry.h
#ifnde... | When you pass a pointer to any function, it's your responsibility to dereference the pointer and get from it the information it points to. That is not automatic -- you have to write the code to do it.
As to std::sort "not working", it is working exactly as you've written. Your comparison spec is comparing the value o... |
71,729,018 | 71,729,681 | How can I get icon of Windows app in CPP? | I'm trying to build an File Manager with in Win32, and I have a problem with the icons. Whenever I trying to get icon that an windows 10 app is associated with it like .png (Photos app), the icon is blank paper. What I'm doing wrong? Thanks in advance and please answer :)
BOOL InitTreeViewImageLists(HWND hwndTV) {
... | You can use the IShellItemImageFactory interface, something like this:
...
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // need this somewhere when your thread begins, not for every call
...
IShellItemImageFactory* factory;
if (SUCCEEDED(SHCreateItemFromParsingName(path, nullptr, IID_PPV_ARGS(&factory))))
{
// t... |
71,729,019 | 71,729,127 | Apparently you can modify const values w/o UB. Or can you? | ---- Begin Edit ----
User @user17732522 pointed out the flaw that invokes UB is from the fact pop_back() invalidates the references used according to the vector library documentation. And constexpr evaluation is not required to detect this when it occurs as it's not part of the C++ core.
However, the fix, which was als... | It is UB to modify a const object.
However it is generally not UB to place a new object into storage previously occupied by a const object. That is UB only if the storage was previously occupied by a const complete object (a member subobject is not a complete object) and also doesn't apply to dynamic storage, which a s... |
71,729,038 | 71,744,046 | Cannot add color to character on multiple lines using Ncurses mvchgat | I'm trying to color a video game map in Ncurses using a loop to have a specific color for multiple characters, it works fine on a single line but whenever I try to apply color to multiple lines either it doesn't apply any color, or it only applies color on the last line.
Here's my code:
initscr();
start_color();
char *... | The \n in the string erases the next line(s), wiping out the video attributes.
mvprintw (and printw, etc), ultimately call waddch, which documents the behavior:
Newline does a clrtoeol, then moves the cursor to the window left
margin on the next line, scrolling the window if on the last line.
|
71,729,213 | 71,729,311 | C++ Search using lower_bound in the vector and ignore lowercase / uppercase letters | How can I find an element in a vector if I don't care about case. For example, if I have in cmp name = "tOM" addr = "LONDON" and I want it to find an element with values name = "Tom" addr = "London" that I have saved in vector? I enclose the whole program https://onecompiler.com/cpp/3xy2j7dmd .
bool Company::cmpNA2 (co... | The first thing is that std::sort requires you to return true or false. The issue is that strcasecmp returns an int denoting whether the first item comes before, is equal, or after the second item (-1, 0, 1). That's three values, not just true or false.
To simplify your code, you could do something similar to this:
b... |
71,730,891 | 71,731,004 | How to Unreal Engine C++ CustomStruct RemoveAt or Remove UE4 | #1 or #2
The function is not working but It works fine with inEditor Blueprint
(Write operator==)
.h
TArray<FStruct> StructArray
.cpp
void Func(FStruct struct_2)
{
const uint32 Index = SturctArray.Find(struct_2); // Always Value = 0
if(StructArray[Index] == struct_2)
{
StructArray.RemoveAt(struct_2) // #1
... | Calling Func will create a copy of the FStruct object passed in. StructArray will never contain the copy that was made for function Func. To make that work, have Func use something that does not create a copy. Like a reference.
Don't use the result of TArray.Find() before checking if it is valid.
TArray.RemoveAt() expe... |
71,731,641 | 71,732,431 | how to make console automatically zoom to full screen when running (In C++) | I want to make a game by coding on Visual Studio. When I run code, the console will appear but it's small. And I need to press maximize to make it full screen.
After I google about window.h, I use this code:
void ConsoleSize(SHORT width, SHORT height)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_R... | I have written two functions, maxsc() and fullsc() are two different full screen, you could use these two functions separately to see if it can meet your needs.
#include<iostream>
#include<Windows.h>
using namespace std;
void maxsc()
{
HWND Hwnd = GetForegroundWindow();
ShowWindow(Hwnd, SW_MAXIMIZE);
}
void ful... |
71,731,703 | 71,731,829 | How do I erase the last star? |
I tried many things, but I fell into a swamp.
When you enter an odd number, one star in the last row pops out and you try to erase it, but it's hard...
#include<iostream>
using namespace std;
int main()
{
int num, star, line;
cout << "num ";
cin >> num;
for (line = 0; line < num/2+1; line++)
{... | The problem is that the last line breaks the pattern.
This is what you get:
*xxx*
**x**
******
And from your description, I assume this is what you want:
*xxx*
**x**
*****
In all the lines before the last line, the number of x:s are odd, but in the last line, the number is even (zero). You first add three *, then zer... |
71,733,342 | 71,733,548 | How do I deallocate the dynamic memory correctly in this C++ program? I get a segmentation fault (core dump) when I execute the program | How do I deallocate the dynamic memory correctly in this simple C++ program? I get a segmentation fault (core dump) when I execute the program. I am trying to find out where I went wrong. Thanks in advance.
I am trying to add dynamically allocated objects to an array and am trying to get the destructor to clear the mem... | Array indexes starts at 0 in C++. So,
this->listCar[length+1] = car;
should be
this->listCar[length] = car;
Otherwise you don't initialize index 0, but you delete it.
Second problem is with the delete. You should use delete for pointer returned by new and delete[] for new[]. You used new. So,
delete[] listCar[i];
sh... |
71,733,467 | 71,733,865 | C++ Multiple function parameters with varargs of a specific type | I am relatively new to C++ coming from a Java background so I am not sure if the functionality I am looking for is directly possible.
I am attempting to create a C++ function that accepts two different parameters but with the following requirements: The first parameter is a single input object of a specific type and th... | You need to define two templates types, one for the input and one for the parameter pack.
The function would then look like this:
template <typename T, typename ... Ts>
bool func(const T & input, const Ts & ... args);
To guarantee all the types are the same, we can combine std::conjunction with std::is_same.
We can al... |
71,734,316 | 71,734,431 | List initialization (aka uniform initialization) and initializer_list? | Why does the following code give different output?
std::vector<int> v{12};
std::cout << v.size() << std::endl;
std::vector<int> v(12);
std::cout << v.size() << std::endl;
What if I list-initialize an object which has a ctor accepting an initializer_list as parameter?
And how can I call std::vector::vector(size_t) wit... | List-initialization prefers constructors with a std::initializer_list argument. From cppreference:
The effects of list-initialization of an object of type T are:
[...cases that do not apply here ...]
Otherwise, the constructors of T are considered, in two phases:
All constructors that take std::initializer_list as t... |
71,735,475 | 71,735,839 | How to properly implement operator<=> for a non-POD class? | I'm looking for a way to implement the three-way comparison operator and the operator== for the following class:
class Foo
{
public:
auto operator<=>( const Foo& rhs ) const noexcept = default;
private:
std::uint32_t m_Y;
std::uint32_t m_X;
char m_C;
std::vector<char> m_Vec;
};
But the default imp... | I believe this is a partial order, which is an order where elements may be incomparable (none of <, >, or == hold between them). You should verify the necessary laws hold (a <= b iff a < b || a == b, a <= a for all a, a == b if a <= b && b <= a for all a, b, and a <= c if a <= b && b <= c for all a, b, c). If that is ... |
71,735,690 | 71,735,823 | Find index of vector element using search_n function | I need to find index of vector element using a function from algorithm library.
EXAMPLE:
{1,2,3,4,5,6,7,8,9,10}
Element 5 found at 5 position.
#include <algorithm>
#include <iostream>
#include <vector>
bool comp(int a, int b) { return a < b; }
int main() {
int n = 10;
std::vector<int> a{10, 8, 5, 4, 1, 2, 3, 6, 7, ... | The std::search_n function looks for a sequence of a specified number of occurrences of a particular value in a range; that number is the third argument (count on this cppreference page).
So, if you insist on using std::search_n for this, you will need to add an extra argument (count, which will be 1) in your call:
it ... |
71,736,101 | 71,737,418 | Why std::shared_ptr doesn't work with base template classes? | First let me show you the inheritance structure:
template <class Type>
class Base {
public:
Base() {}
virtual bool verify() const = 0;
};
class Derived : public Base<int> {
public:
Derived() : Base<int>::Base() {}
virtual bool verify() const override;
};
So, the base class for Derived is Base<int>.
I... | you have to either specify operator for a Derived class, or to save both of your variables in the pointer of Base:
std::shared_ptr<Base<int>> d = std::make_shared<Derived>();
std::shared_ptr<Base<int>> bInt;
auto res = d | bInt;
|
71,736,102 | 71,736,161 | How to use Class? (with poor English ability) | Code that implements Vectors as Class and inputs and outputs them as txt files.
I was temporarily implementing a function of Class, but I have a question because there is an error.
I tried to add vectorA and vectorB as Add functions in the main function and replace them with vectorO to printf.
However, in the Vector ou... | This should fix your errors. have a basic and an overrided contructors, also be careful of the variable names they shouldn't be the same
#include<stdio.h>
class Vector
{
public: // private?
double x, y, z;
public:
Vector() {
x = 0;
y = 0;
z ... |
71,736,276 | 71,736,338 | Does std::terminate() trigger stack unwinding? | I've been trying to implement Exception class, and for program termination i've decided to use std::terminate(), but i'm not suse whether or not std::terminate() triggers stack unwinding process.
For example, if i compile and run this code:
struct Test {
Test() {
std::cout << "Constructed\n";
}
~Tes... | The standard handler for std::terminate() calls directly std::abort.
If you take a look here, you will find out that std::abort() did not call any of the destructors.
Destructors of variables with automatic, thread local (since C++11) and static storage durations are not called. Functions registered with std::atexit()... |
71,737,118 | 71,739,320 | What is a good technique for compile-time detection of mismatched preprocessor-definitions between library-code and user-code? | Motivating background info: I maintain a C++ library, and I spent way too much time this weekend tracking down a mysterious memory-corruption problem in an application that links to this library. The problem eventually turned out to be caused by the fact that the C++ library was built with a particular -DBLAH_BLAH co... | One way of implementing such a check is to provide definition/declaration pairs for global variables that change, according to whether or not particular macros/tokens are defined. Doing so will cause a linker error if a declaration in a header, when included by a client source, does not match that used when building th... |
71,737,442 | 71,744,877 | Why don't types with invalid inheritance get rejected when passed as template parameters? | As we all know, classes can't be inherited from fundamental types and from classes that are marked as final. But despite that, the code presented below compiles without any problems on Clang 12 and GCC 9.
#include <type_traits>
template<typename T>
struct Inheriter : public T{};
int main()
{
std::void_t<Inheriter... | There will only be an error due to the inheritance if the template specialization Inheriter<int> is instantiated.
Simply using the specialization, e.g. as a template argument, does not cause implicit instantiation. Roughly speaking implicit instantiation of the class template specialization happens only if it is used i... |
71,737,631 | 71,738,051 | What is the design purpose of iterator_traits? | The C++ standard library has both iterator and iterator_traits templates defined. It seemed that in general, the iterator_traits just extracts properties that defined explicitly in iterator. If a iterator_traits is to be used, one can use the corresponding iterator directly. If a specialization of certain type (e.g. T*... |
It seemed that in general, the iterator_traits just extracts properties that defined explicitly in iterator. If a iterator_traits is to be used, one can use the corresponding iterator directly.
Not all iterators can type aliases as members.
What's the benefit this indirection?
To allow all iterators to have a unifo... |
71,737,656 | 71,738,009 | What are the use cases for a base class pointer pointing to a derived class object | I'm a new to OOP and trying to learn C++ and I came cross polymorphism and using the virtual keyword.
I just don't understand why we might need to do that.
I've checked this site for similar questions but none of them attempts to answer that why?
| The main goal is: Separation of concerns.
Let's take an example from my day job. I work on a codebase that does networking. The vast majority of the codebase depends on a class that looks like:
class Transport
{
public:
virtual bool SendMessage(int clientId, string message);
};
Imagine I've got hundred files, ... |
71,737,757 | 71,737,883 | Doxygen multi line comments | I am new to Doxygen and trying to comment my code.
I have some issue with the comments: my multi line comments appear in a single line and I don't want to use \\n or <br>.
/**
Brief - this is a function
Get -
Return -
*/
void func1()
{
return
}
I want each line to start a new line.
However, the result is:... | The doxygen comments in that case are meant to ignore the implicit new lines so the text wrapping doesn't affect the output like
/** This is a long comment that caused the
IDE to wrap the text and therefore
span onto multiple lines **/
int func(bool b) {
}
but in your example I think you should use appropriate command... |
71,738,552 | 71,739,093 | C3520 parameter pack must be expanded - incorrect behaviour for 'variadic using' | While compiling the code below with Qt 5.12 using Microsoft Visual C++ Compiler 15.9.28307.1300 (amd64) and c++17 standard I get the following error:
error C3520: 'Args': parameter pack must be expanded in this context
note: see reference to class template instantiation
'Helper<Args...>' being compiled
template<typen... | As workaround to variadic using (C++17), you might use the recursive way:
template <typename... Args>
class Helper;
template <>
class Helper<>
{
};
template <typename T>
class Helper<T> : Base<T>
{
public:
using Base<T>::operator();
};
template <typename T, typename... Ts>
class Helper<T, Ts...> : Base<T>, Helpe... |
71,739,445 | 71,739,621 | Procedure entry point could not be located in exe | I have a exe that I built on Windows using mingw-gcc. It has several dependencies. All of them are located on the PATH. However, when I run it I get the following error.
The procedure entry point _ZNSt11logic_errorC2EOS could not be located in the dynamic link library <name_of_exe>
I have looked at similar questions an... | Usually the entry point name is the name of a function or class method with some decoration. I think you are missing some dll or in the path you have some not updated version of the dll. The first thing to do is to search your project for anything like St11logic_error. This way you'll find the dll which is not updated ... |
71,739,626 | 71,739,676 | string subscript out of range in C++ for Cowculations | Please help with debugging.
It gives me an error 'string subscript out of range error' after the fifth input.
I was unable to figure out what to change.
Here is the code:
#include <iostream>
#include <string>
#define N 100
int str2int(std::string input)
{
int num = 0;
for (int i = 0; i < input.length(); i++... | You may not use the subscript operator for an empty string to change its value
std::cin >> operation[oprt];
At least you have to declare the object operation with the magic number 3 used in your for loop. For example
std::string operation( 3, '\0' );
Or
std::string operation;
operation.resize( 3 );
If you need to e... |
71,739,765 | 71,740,893 | Is there a way to create std::vector<arma::mat> from arma::mat matrices without creating a copy of the matrices? | I am new to C++. For a statistical method, I compute large matrices, e.g. A and B . They are n x n so for large sample sizes n, they become very large. If they are double and n = 70k , I think it might be on the order of 30GB?
Because the number of matrices needed can vary, I implemented the algorithm to use a vector o... | You need to reverse the logic: Let the std::vector allocate the memory and create the matrices. Then you work directly with the elements in the vector. For example:
std::vector<arma::mat> matrices;
matrices.resize(2);
arma::mat & A = matrices[0];
arma::mat & B = matrices[1];
// Initializing the values of A and B, and d... |
71,740,041 | 71,740,104 | Not calling the appropriate constructor | #include<iostream>
using namespace std;
class String
{
protected:
enum {SZ= 80};
char str[SZ];
public:
String (){str[0]='\0';}
String(char s[])
{
strcpy(str,s);
}
void display() const
{
cout<<str;
}
operato... | This code snippet
else
{String(s);}
does not make a sense.
This line
String(s);
is a declaration of the variable s of the type String with the scope of the compound operator of the else part of the if statement.
Pay attention to that this constructor
Pstring(char s[])
calls implicitly the default con... |
71,740,186 | 71,740,356 | Loop for load multiples files (C++) | I´m trying to load all the files in a folder that have names from the form "file_i.csv".
For this I write the program:
void load_reel_set()
{
bool file_exists = true;
unsigned n_files = 0;
vector<unsigned> my_vector;
string line;
int i;
ifstream file("..\\file_" + to_string(n_files) + ".cs... | You have two independent instances ifstream file, the one inside the loop hiding the one outside. While the inner one runs out of scope after closing the loop the outer one remains at the end of the very first file.
Try instead:
file.open("the new path");
Side note: This file_exists variable is totally obsolete, you c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.