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 |
|---|---|---|---|---|
70,813,025 | 70,814,207 | Argmax of 2d vector on C++ | I am working on python/pytorch and I have an example like
2d vector a
|
v
dim-0 ---> -----> dim-1 ------> -----> --------> dim-1
| [[-1.7739, 0.8073, 0.0472, -0.4084],
v [ 0.6378, 0.6575, -1.2970, -0.0625],
| [ 1.7970, -1.3463, 0.9011, -0.8704],
v [ 1.5639, 0.7123, 0.0385, ... | You can use std::max_element to find the index in each sub vector
#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int main()
{
vector<vector<float>> a_vect=
{
{-1.7739, 0.8073, 0.0472, -0.4084},
{0.6378, 0.6575, -1.2970, -0.0625},
{1.7970, -1.3463, 0.9011, -0.8704},
... |
70,813,613 | 70,813,787 | "Invalid base class" error when trying to inherit from derived struct (C++) | I've got a "Base" struct, an "NPC" struct derived from the "Base". All works perfectly fine. But when I try to create a new struct called "PC" from the "NPC" struct, I get an error: "invalid base class".
What's the problem? Is it not possible to create a struct from a derived struct?
struct Base
{
char* name = 0;
... | When you wrote:
struct NPC : Base
{
int gold = 0;
int stats[]; //NOT VALID, this is a definition and size must be known
};
This is not valid as from cppreference:
Any of the following contexts requires type T to be complete:
declaration of a non-static class data member of type T;
But the type of the non... |
70,813,733 | 70,814,064 | Error: " expected unqualified-id before 'int' ", array, argument, function, | I am fairly new to C++ and currently following a certification to learn this language. I previously only used languages such as Python.
I found similar posts with the same but none could relate to my code.
I have the following code to create a hex game. I am trying to have a simple function to display the board every t... | In Standard C++ the size of an array must be a compile time constant. So when you wrote:
int size;
cin>> size;
int array[size][size]; //NOT STANDARD C++
The statement array[size][size]; is not standard c++.
Second when you wrote:
void display_current_array(array[size][size], int size){
//...
}
Note in the first param... |
70,813,892 | 70,816,684 | custom exception class, using a base class, with multiple arguments | So I'm setting up custom exception classes for a program I am writing. I'm creating a catch-all base class, that I will use primarily as a generic exception. This base class will be inherited by several other custom exceptions. Here is the base class and one of the additional exception classes, there will be 10+ child ... | As Silvio mentioned in another comment, you can't use strcat if the buffer can't contain the resulting string. In this case, you also have the problem that you're passing a const char * to strcat which is a no no (literal strings are const).
I suggest that you change your msg variable to a std::string. It will then b... |
70,814,312 | 70,816,325 | Mouse click with GetAsyncStateKey | I am trying to make a program that when you click, it uses GetAsyncStateKey() to know that you've clicked and makes the code click once more, like a double-clicker.
The problem is, I don't know anything about coding, so I tried to look at many codes and came up with this:
#include <iostream>
#include <windows.h>
#inclu... | Your program performs 1 operation and then exits. You need a loop to keep it alive, eg:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
while (true) {
if (GetAsyncKeyState(VK_LBUTTON) < 0) {
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}... |
70,814,930 | 70,814,998 | How to implement arrays of abstract classes in C++? | My use case is the following. I have a pure abstract class and inherited classes like so:
class AbstractCell {
public:
// data members
virtual void fn () = 0; // pure virtual functions
}
class DerivedCell1 : public AbstractCell {
public:
// more data members
void fn () {} // implementation of all virtual f... | Abstract classes rely on virtual functions to be useful. The right function to be called is determined at runtime depending on the real type of the polymorphic object.
You cannot benefit of such polymorphism with an array of objects. Arrays require a type that is determined at compile-time and that can be instantiated... |
70,814,941 | 70,815,042 | memory address of dynamic array | double *tt;
tt = new double[2];
std::cout << tt[0] << std::endl;
std::cout << tt << std::endl;
The result is like this
-1.72723e-77
0x12e6062e0
What is the difference between these two?
I don't know why the two values have different formats (tt[0] is X.~~ but tt there is no point)
| tt[0] is dereferencing the pointer to the array tt and the result is an expression of type double. It is equivalent to *tt. There is a random value in that location so you see a random floating-point value being printed.
But tt is just a pointer (of type double*) and thus when you print it, the address of a memory loca... |
70,814,975 | 70,815,305 | How can I draw an ellipse using QPainter? | I want to draw ellipse in UI but my code doesn't work.
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),... | The issue isn't the way you're using the QPainter, it's the time you're obtaining it.
As the reference documentation says, "the common use of QPainter is inside a widget's paint event". So if you want to do custom painting in your main window, override paintEvent and put your code there.
|
70,815,062 | 70,815,229 | Calling destructor in member function | If we are implementing, for example, smart pointers, and we want to do a = std::move(b) --- we need to delete memory to which a is pointing, but can we call destructor inside move assignment operator, instead of copy-pasting destructor's function body?
Is the behavior on calling destructor inside move-assignment define... | Explictly calling destuctor is technically available, you can use this->~Object() in non static method of the class Object.
However this is a bad practice. Consider use these instead.
class Test {
public:
Test() {}
~Test() {
Deallocate();
}
Test(const Test& other) = delete;
Test(Test&& other) {
De... |
70,815,347 | 70,815,452 | How can I delete decimal points from a 'double' type to later be displayed as a currency? | I am currently building a mock banking app that can display the history of transactions on an account.
Part of a transaction is, naturally, the amount.
Amounts are stored as doubles in my program which leads to many of them being displayed with way too many decimal points (for example £500.000000 instead of £500.00).
W... | You may use this helper function:
#include <sstream>
#include <iomanip>
std::string value2string(double value)
{
std::ostringstream out;
out << std::fixed << std::setprecision(2) << value;
return out.str();
}
string Transaction::toString() {
fullString = "-- " + desc + ": -\x9c" + value2string(value) + " on " +... |
70,815,729 | 70,816,426 | How do we handle errors in the input of a User Defined Literal? | Say I want to have an integral percent defined like so:
constexpr int operator""_percent (char const * literal)
{
int percent(0);
for(; *literal != '\0'; ++literal)
{
if(*literal >= '0' && *literal <= '9')
{
percent *= 10;
percent += *literal - '0';
if(per... | I don't really know what common practice for such situations is, but I will give some ideas below.
With C++20 you can make the literal operator consteval instead of constexpr.
On error you can then throw an exception. The throw expression itself is allowed in a constexpr/consteval function, but actually throwing makes... |
70,815,794 | 70,816,026 | How to display a map of a map (C++)? | I made the following map to store data from a .log :
map<string,pair(int,map<string,int>)>.
I manage to store the data but not to retrieve it. What I do is:
cout<< "first string: "<< debut->first
<< " pair (first int): " << debut->second.first << endl;
(debut is a constant iterator of a map)
With that I get the... |
I don't know how to get the content of the map.
You can print out the content of the innermost map as shown below([DEMO]):
auto beg = debut->second.second.cbegin();
auto end = debut->second.second.cend();
while(beg!=end) //can also use for loop
{
std::cout<<beg->first<<" ";
std::cout<<beg->second<<std::endl;
... |
70,816,188 | 70,816,471 | How to create a vector of unique pointers pointing at default constructed objects | Is there a way to create a vector containing N number of std::unique_ptr<T>s? GCC v11.2 shows huge and cryptic error messages so I'm not able to detect the issue.
Here is an MRE of what I was trying to do:
#include <iostream>
#include <vector>
#include <memory>
// a dummy struct
struct Foo
{
int m_value;
};
int... | The line:
std::vector< std::unique_ptr<Foo> > vec_1D( colCount, std::make_unique<Foo>( ) );
makes use of the following vector constructor:
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
Which receives a given value and copies it to every element of the... |
70,816,425 | 70,817,236 | Declaring a std::list with an array index C++ | I was following a hash table implementation online (https://www.youtube.com/watch?v=2_3fR-k-LzI) when I observed the video author initialize a std::list with an array index. This was very confusing to me as I was always under the impression that std::list was always meant to operate like a linked list and was not capab... | After reading the responses from @IgorTandetnik I realized that I was thinking about the list incorrectly. What I didn't fully understand was that we were declaring an array of lists and not attempting to initialize a list like an array. Once I realized this, I was able to access the elements correctly since I was not ... |
70,816,674 | 70,817,550 | Passing a member function as template argument | I have a hash table class. It has a template parameter hashFunction:
#include <string>
template<class KeyType> using hashFunction_t = size_t(size_t, const KeyType&);
template< class KeyType, class ValueType, int nHashGroups,
hashFunction_t<KeyType> hashFunction >
class HashTable
{
};
class Entity
{
//djb2
... | The problem is that you are trying to use a pointer-to-member as a type template parameter, and this is not supported, basically because when you define a type you don't bind that type to any specific object.
When (as suggested in a comment) you make stringHash static, then you no longer need the object, so it can be u... |
70,816,714 | 70,816,794 | Why my program isn't accepting the second input? | I don't know why it doesn't take the second input. Help me solve it.
This is the code:
#include <iostream>
using namespace std;
int main()
{
char fn,ln;
cout<<"Enter your First Name\n"<<endl;
cin>>fn;
cout<<"Enter your Last Name"<<endl;
cin>>ln;
return 0;
}
| Since char can only hold a single character, you may use std::string for storing names.
Example:
#include <iostream>
#include <string>
int main( )
{
std::cout << "Enter your first name\n";
std::string firstName;
std::getline( std::cin, firstName );
std::cout << "Enter your last name\n";
std::stri... |
70,816,850 | 70,816,894 | How Does Vertex Buffer Description Read Input Data in DirectX 11? | I created a Math Struct that holds positions for vertex coordinates and am wondering how DirectX is able to read the members of the struct without knowing the names of the member values or being able to use them for input despite them being private.
Example:
//The values can be used for input despite being private
clas... | The private vs public only applies to C++ code and is enforced by the compiler. Instances of Math3 are just a block of 12 bytes in memory with no special hardware protections.
In other words, from an 'in-memory' perspective the Math3 is exactly the same if it's:
class Math3
{
public:
float x;
float y;
float... |
70,816,917 | 70,817,015 | Perfect forwarding of a braced initializer to a constructor? | There are similar questions, but none seem to be quite this.
I have a wrapper class that exists to hold an S. In it's simplest form we have
// A simple class with a two-argument constructor:
struct S {
int x[2];
S(int x, int y) : x{x, y} {}
};
struct WrappedSSimple {
S s;
template <typename... Args>
... | In your first example WrappedSSimple({1,2}) is calling the move-constructor of WrappedSSimple with the a temporary constructed via the user-defined constructor as argument.
You cannot replicate this behavior with a factory if the constructor is private, because the temporary object which needs access to the constructor... |
70,817,174 | 70,817,195 | How can I read a single byte from a binary stream? | I have a binary file which I would like to process one byte at a time. This is what I have for reading the first character of the file:
ifstream file("input.dat", ios::binary);
unsigned char c;
file >> c;
However, when I step through this code with a debugger, c always has the value 0x00 although the first (and only) ... | Use std::istream::get or std::istream::read.
char c;
if (!file.get(c)) { error }
int c = file.get();
if (c == EOF) { error }
char c;
if (!file.read(&c, 1)) { error }
And finally:
unsigned char c;
if (!file.read(reinterpret_cast<char*>(&c), 1)) { error }
|
70,817,312 | 70,817,334 | Adding char[] to vector | Trying to add value to vector :
std::vector<char[256] > readers;
char d[256];
strcpy(d, "AAA");
readers.push_back(d);
Got error:
an array cannot be initialized with a parenthesized initializer
What I do wrong?
| A C-style array is not assignable, so it cannot be used as the value type of a vector.
If you are using at least C++11, you can #include <array> and use std::array. (Historically available in Visual C++ 2008 SP1 as std::tr1::array).
#include <iostream>
#include <array>
#include <vector>
#include <cstring>
int main()
... |
70,817,628 | 70,817,686 | Create std::string from std::span of unsigned char | I am using a C library which uses various fixed-sized unsigned char arrays with no null terminator as strings.
I've been converting them to std::string using the following function:
auto uchar_to_stdstring(const unsigned char* input_array, int width) -> std::string {
std::string temp_string(reinterpret_cast<const cha... | You want:
auto ucharspan_to_stdstring(std::span<unsigned char const> input_array) -> std::string {
return std::string(input_array.begin(), input_array.end());
}
string, like other stand library containers, is constructible from an appropriate iterator pair - and this is such a pair. Since these are random access i... |
70,817,998 | 70,818,055 | Why does this while loop keep looping even when its false? In C++ | This is the code in question:
int integer;
while (integer != 0 || integer != 1) {
cout << "Choose an integer: \n0\n1\n";
cin >> integer;
}
When I type 1 it continues looping even though the statement is false.
I have had this problem before or similar but it got fixed in a weird way... | let me put you out of your misery
while(chosen != 1 && chosen != 2 && chosen != 3)
{
cin >> chosen;
}
This is a common issue, people translate the human idea in their heads into code: "if its not 1 or 2 or 3 then do xx". But that doesnt work.
(chosen != 1 || chosen != 2 || chosen != 3)
will always be t... |
70,818,107 | 70,818,409 | Identifier not found when calling a function under a function | I trying to develop a program that displays a 12 hour and 24 hour clock at the same time. But whenever I compile, I get a build error saying 'GetAM_PM': identifier not found. I get this error on line 26 in spite of using the same variable from my function parameter. What could be the root of this problem? Here is my co... | Just move these lines to the beginning, before any other function:
// function return AM/PM respect to hour of time
string GetAM_PM(int twelve_hours) {
return twelve_hours >= 12 ? "PM" : "AM";
}
It is not this case, but if you end up with circular dependency, try to declare the methods in a .h or forward declare the ... |
70,818,250 | 70,818,521 | No default constructor available when I put a struct in an union, but no errors if it is outside | I am trying to put RenderTargetView into an union defined below.
But when I try to do that I get the error for the no default constructor available. I am sure there should be default constructor because everything is defined.
Also if I put RenderTargetView outside of the union I am no longer getting that error. Does an... | A union has default non deleted constructor only if all members of the union have trivial constructors. Same for destructors. Since your struct has a member initializer this means that it doesn't have a trivial constructor this means the union constructor is deleted. You need to create special members for union where y... |
70,818,266 | 70,818,316 | How to parse JSON array from inside an object with rapidjson | The following is a JSON file exported from Tiled Map Editor.
{ "compressionlevel":-1,
"height":32,
"infinite":false,
"layers":[
{
"data":[ A whole bunch of integers in here],
"height":32,
"id":1,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
... | doc['layers'] is an array.
const rapidjson::Value& layers = doc["layers"];
assert(layers.IsArray());
for (size_t i=0; i < layers.Size(); i++) {
const rapidjson::Value& data = doc["layers"][i]["data"];
assert(data.IsArray());
}
UPDATE:
Direct access to first data item in layers:
const rapidjson::Value& data = doc... |
70,818,401 | 70,818,547 | What difference between passing an instance and a brace-enclosed initializer list to a function? | Say I have the following code.
class A
{
public:
float x, y, z;
A(float x, float y, float z) : x(x), y(y), z(z) {}
};
float average(A a)
{
return (a.x + a.y + a.z) / 3;
}
Are there any practical differences between calling the function in these two ways?
// a)
average(A(1, 2, 3))
// b)
average({1, 2, 3})... | It depends on the C++ version you are using.
Copied (and sligthly modified) from copy elision @ cpprefrence (so, not an exact quote):
In C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from.
Th... |
70,818,497 | 70,818,653 | Does C++ standard guarantee that std::vector's underlying pointer initialized as nullptr | According to https://en.cppreference.com/w/cpp/container/vector/data, the underlying pointer is not guaranteed to be nullptr if the size is 0
If size() is 0, data() may or may not return a null pointer.
but does that apply to the default initialized std::vector with no elements? or does that simply state that if all ... | No.
The standard guarantees that a default-initialised std::vector has size() equal to zero, but that doesn't require that data() will return nullptr.
There is nothing in the standard that prevents (and "not preventing" is not equivalent to "requiring") a default-constructed vector having zero .size() and non-zero capa... |
70,818,746 | 70,827,795 | OpenGL texture coordinates are mirrored when GLM_FORCE_LEFT_HANDED is defined | My engine uses a left-handed coordinate system (y up z forward), so I am defining GLM_FORCE_LEFT_HANDED. However, I have found an issue that all textures are mirrored on the x axis. I tried fixing it by flipping the image on load, and while the image does render correctly after that, the uv coords become aligned to the... | Alright I figured it out. It was actually my mesh that was the culprit. Not GLM_FORCE_LEFT_HANDED or OpenGL.
Each individual face was backward, with the 0,0 uv coordinate in the bottom right corner and 1,1 in the top left. After fixing the mesh the problem has gone away.
|
70,818,766 | 70,818,818 | Why can't I include the string library in C++? | This is a short one.
There's a fatal error:
No library titled "string" or something like that.
#include <string>
using namespace std;
int main () {
//[insert code here]
}
It should be correct, I looked how to use strings and this is exactly what to do.
| Make sure you are compiling it with a c++ compiler. Using a C compiler for C++ code may produce confusing error messages just like the one you got.
|
70,818,779 | 70,818,937 | Segmentation fault Binary search Tree | I know there is few questions with a similar title, however I went over them and still couldn't solve my error.
This is the BST implementation:
struct node {
int val;
node* left;
node* right;
};
node* createNewNode(int x)
{
node* nn = new node;
nn->val = x;
nn->left = nullptr;
nn->right = ... | First of all, your Binary Search Tree is Right Skewed Binary tree because the new element will get added as the right most child of existing tree.
That said, for every insertion, the recursion will go as deep as the value of i passed to bstInsert() and, for some big value of i, eventually it run out of space, while rec... |
70,818,781 | 70,818,969 | How to create a constructor in source file C++ | I have been researching for hours. This simple task is eluding me...
Any suggestions of refactoring are encouraged. I am not a C++ person obviously.
I've watched all these videos but none of the demo classes have multiple fields. I certainly have not seen a source file that initializes a null array.
Links:
C++ - Classe... | You need to declare a default value for your constructor taking a bool if you want it to be usable without arguments. A constructor without any mandatory arguments is a default constructor.
The definition of the class and declaration of its member functions:
#pragma once // or a standard header guard
class Node {
publ... |
70,818,894 | 70,819,147 | How to pick up elements from std::vector<struct> quickly? | I have a struct MyStruct which have some elements (including int value1), and a std::vector<MyStruct>. How can I pick up all value1 from each MyStruct and have a std::vector<int> which is the vector of value1. No write will be operated on the new vector.
The following is possible but the copy is needed. Is there any so... | I believe a more optimal solution would be to change the func2 to take in a &std::vector<MyStruct> as an argument by reference so that no copy is made. Then you can just access each element by myStruct[i].value1.
|
70,818,988 | 70,819,229 | What are "extern char condition tricks"? | I was reading the GCC documentation on C and C++ function attributes. In the description of the error and warning attributes, the documentation casually mentions the following "trick":
error ("message")
warning ("message")
If the error or warning attribute is used on a function declaration and a call to such a functio... | I believe the premise is to have a compile time assert functionality. Suppose that you wrote
extern char a[(condition) ? 1 : -1];
If condition is true, nothing happens and the line compiles to nothing. The extern makes sure that a doesn't use any memory. However, if condition is false, a is declared as an array of neg... |
70,819,005 | 70,819,061 | C++ : Can a thread be executed without calling the join() function in the main function? | Please help me with a simple question about the output of the following code.
I thought that a thread is executed only when the join() or detach() function is called.
So, I expect the output to print only "pause of 2 seconds ended , ID = 59306", and not to print "pause of 1 seconds ended , ID = 10218" because I though... | Threads start execution not when .join() is called on them, but when they are constructed.
.join() is used to block the calling thread's execution until the thread being joined to has finished execution. It is typically required to join all threads before main() exits for the reason you observed:
When main() reaches th... |
70,819,502 | 70,819,752 | What is the lpstr filter for folders? | I am trying to open a dialog box where the user selects a certain folder on pure C++, no .Net framework or C#, and am struggling to find how the lpstr would filter everything but directories. I am currently using the OPENFILENAME function. I tried filtering to .dir, but it does not work. Anyone know the actual extensio... | The OPENFILENAME struct is used with the old GetOpenFileName() Common Dialog Box, which can't be used to select a folder. It is simply not designed for that purpose.
You need to use SHBrowseForFolder() instead, or in Vista+ you can (and should) use the newer IFileOpenDialog Common Item Dialog with the FOS_PICKFOLDERS o... |
70,819,577 | 70,819,673 | Why do I have a memory leak in my c++ code? | I'm new to c++ and I have code that compiles but won't publish to linux because it says I have a memory leak in the error. Please help me find the error in the code. Linux uses valgrind, which finds the leak.
Please help me find the error and fix it.
Output with memory leak:
==6858== Memcheck, a memory error detector
=... | Here,
if (Name == "!")
break;
you are breaking the outter loop, hence exiting the code without closing the file. This will leak memory. You should close the file before the break.
|
70,819,960 | 70,823,405 | How to turn an integer into vector and then turn that vector into string in C++ | I want to take an integer and turn it into an array and then store it into a string in C++. But I do not know how to turn an integer into an array and then store it into a string. I am still learning C++, so help me, please. That's how I want it to be done:
#include<iostream>
#include<vector>
using namespace std;
int... | Here you are:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
int n;
std::cin >> n;
std::vector<int> split(static_cast<int>(std::log10(n)) + 1);
auto royal_10 = split.rbegin();
auto cpy{ n };
do {
*royal_10++... |
70,819,990 | 70,820,014 | How to set the specific value to the concept template class explicit instantiation? | I have codes as follow:
#include <concepts>
//Fibo Begins
template <std::unsigned_integral num>
struct Fibo {
constexpr static std::size_t value = Fibo<num - 1>::value + Fibo<num - 2>::value;
};
template <>
struct Fibo<1> {
constexpr static std::size_t value = 1;
};
templat... | First, the syntax you are using is for a constrained type template parameter, not a non-type template parameter with constrained type. So the compiler is complaining that it expects a type as template argument, not a value.
For a non-type template argument with constrained type it should be std::unsigned_integral auto ... |
70,820,047 | 70,820,075 | Getting wierd output in recursion code! Even though logic seems to be correct | I've been trying to attempt a question on recursion pattern and it is pretty easy one but I am not able to getting why I am getting such an unexpected output. I traced the variables and parameters in callstack and my logic seems to be right but still it is printing random numbers.
#include <bits/stdc++.h>
using namesp... | You are missing a return statement from pattern() function.
vector<int> pattern(int N)
{
if (N <= 0)
{
// cout << "stopped" << endl;
sol.push_back(N);
return sol;
}
sol.push_back(N);
pattern(N-5);
sol.push_back(N);
return sol; // <--------- this was mi... |
70,820,127 | 70,820,232 | std::construct_at on top of existing object skipping re-initialization of some fields | In the following program, in a constant expression, a temporary object of A is created with all fields initialized, and then function f creates another object of A at the same address, skipping (re)initialization of the field x, which is read afterwards:
#include <memory>
struct A {
int x;
constexpr A() {}
... | I'm convinced this is UB, and GCC is wrong.
std::construct_at<A>(&a) creates a new A object, and thus a new int x member in it. That new object isn't initialized.
For this to be legal, there would have to be a special rule that uninitialized objects may get values based on the contents of memory they occupy, and I don'... |
70,820,275 | 70,842,385 | Vulkan image incompatibility, is there a nice way to check which parameters are incompatible? | My validation errors are returning the following error:
Message ID name: VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251
Message: Validation Error: [ VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251 ] Object 0: handle = 0x1867f53a780, name = Logical device: NVIDIA GeForce GTX 1070, type = VK_OBJECT_TYPE_DEVICE... | If some parameters are clashing, then ask https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues for improved error reporting. There should ideally be appropriate error message.
But if the GPU simply does not support given combination of parameters, then there is nothing that can be done. It is meaningles to as... |
70,820,639 | 70,820,954 | Can anyone explain this code? I do not understand the working of not1() and ptr_fun() | Can anyone explain the working of this function?
string rightTrim(const string &str)
{
string s(str);
s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
return s;
}
I don't know the working of not1() and ptr_fun(). Can anyone provide me with a good explanation for thi... | The question is essentially
What is not1(ptr_fun<int, int>(isspace))?
Short answer
You should use std::not_fn(isspace) instead, which clearly states it is a "thing" that expresses the idea that "something is not a space".(¹)(²)
Wordy answer
It is a predicated that asks if its input is not a space: if you apply it to ... |
70,820,698 | 70,821,163 | Ensuring compilation error while passing null pointer to a function | Let's say that I have a function which takes in pointers.
int functionA(int* a, int* b)
{
...
}
I can add null checks inside functionA. Is there a way that I can ensure that an error occurs on the compile time whenever nullptr is passed as a parameter.
|
Is there a way that I can ensure that an error occurs on the compile time whenever nullptr is passed as a parameter.
If you specifically mean the nullptr keyword, then sort of. You can provide overloads that would be chosen in that case, and define them deleted. This works as long as you don't explicitly bypass the o... |
70,820,998 | 70,821,048 | Why are the addresses of these two local variables the same? | I have defined a function here that accepts an array as a parameter
void print(char ch[]);
When I call the function and give it the array as an argument
int main(){
char ch[10];
print(ch);
}
And I print the addresses of these two variables in two different functions,
#include <stdio.h>
void print(char ch... | For starters to output a pointer you need to use the conversion specifier %p instead pf the conversion specifier %d. Otherwise the call of printf invokes undefined behavior.
printf("address of ch is %p\n", ( void * )ch);
Secondly within the function this call of printf does not output the address of the variable ch it... |
70,821,003 | 70,821,069 | How to modify the same variable in different classes and modify it? | I have many function definitions which I have placed in different cpp files with function declarations in their respective .h files.
I have a set of a variables which I have placed in a .h file. These variables need to modified by different functions. I am using static to keep the changes from each function, but I hear... | You can simply move these variables into another class:
struct Shared {
int x;
int y;
};
Now you can pass an instance to this class as parameter to your function, this is called dependency injection:
void foo(Shared& shared) {
shared.x = 4;
shared.y = 2;
}
This is better because you don't have any glo... |
70,821,399 | 70,821,444 | Is Undefined Behavior To Using Invalid Iterator? | Consider this code:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> map = {
{ "ghasem", "another" }
};
std::cout << map.find("another")->second << std::endl;
std::cout << map.size() << std::endl;
}
It will be compiled and run successfully(the process... | There is no key comparing equal to "another" in the map. Therefore map.find("another") will return the .end() iterator of the map. Dereferencing this iterator in ->second is then undefined behavior since end iterators may not be dereferenced.
Your code should check that the iterator returned from find is not the end it... |
70,821,434 | 70,821,502 | C++ variadic template syntax within dependent scope | I have a problem with real-world code and have replicated the problem with the following sample code.
#include <iostream>
#include <tuple>
using namespace std;
struct Identity
{
template <typename... T>
static std::tuple<T...> Apply(T... val)
{
return std::tuple(val...);
}
};
template <typena... | You are missing one keyword. You need:
return F::template Apply<T...>(t...);
And it'll be fine. This error message is not the clearest one. :)
You can find an explanation here if you are interested in the details:
Where and why do I have to put the "template" and "typename" keywords?
|
70,821,456 | 70,824,472 | Exception handler catch(...) in C++ | I understand that exception handler catch(...) in C++ handles any type of exception. I am wondering what happens if it has to handle an exception that is of some class type - is the object of that class passed to this handler by reference or by value?
This is the code that could help in understanding this. When the exc... | When you throw an exception, the exception object is created from the operand to throw. It is an object stored in an unspecified way.
When a matching handler for the exception is reached and the handler is not ..., then the handler's parameter is initialized from the exception object.
Essentially, if you declare a catc... |
70,821,514 | 70,823,638 | Inner product of compile-time coefficients and sequence of values | Looking to calculate the inner product of a series of floating point values and corresponding coefficients (given that the coefficients are known at compile-time).
template <uint64_t Divisor, uint64_t... Coefficients>
static consteval std::array<double, sizeof...(Coefficients)> createCoefficients()
{
double coeff[]... | This appears way too complicated. Something along these lines perhaps:
template <uint64_t Divisor, uint64_t... Coefficients>
static constexpr auto inner_product(std::floating_point auto... values)
{
return ((values * Coefficients / Divisor) + ...);
}
Demo
|
70,821,856 | 70,829,598 | C++ trivial function: return value type doesn't match the function return type: ternary operator | I cannot understand why would Visual Studio Intellisense complain.
In the code:
int absolute_value(int x) {
return x > 0 ? x : - x;
}
It underlines x in return x with the message: return value type doesn't match the function return type.
| My environment is win10, vs2022. I tested the code you posted, the code works fine, I suggest you repair your Visual Studio or download it again.
#include<iostream>
using namespace std;
int absolute_value(int x) {
return x > 0 ? x : -x;
}
int main()
{
cout << absolute_value(-6);
}
|
70,821,987 | 70,822,384 | MultiIndex containers -- offering vector and set access | I have an application where, first, an std::vector<int> object is generated. Then, some operations need to be performed on this object viewed as an std::set<int> where the order does not matter and repetitions don't count.
At present, I explicitly construct an object of type std::set<int> from the std::vector<int> obje... | Random access index would match the "vector" interface.
An ordered unique index would match the "set" interface.
However, if you have a unique index, this will prevent insertion of duplicates. So, you would get:
Live On Compiler Explorer
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/ordered_inde... |
70,822,270 | 70,828,426 | How to rewrite a function from C++ to Python that converts a number from any number system to the decimal system | I have a problem.
I have a function in cpp that converts a number from any number system to decimal. But I need a function like this in Python. I just don't know how to rewrite it to work in Python. And I can't use the built-in functions that exist in a given language to replace a number.
This is function in cpp and I ... | In order to convert a number to decimal number system. We can iterate over the number from the end and take each number then multiply the number with number system to the power of its place from the last and sum them all.
C++
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cc... |
70,822,301 | 70,822,473 | given list of grades | This is the code I have made, however, what is being displayed is incorrect. Kindly teach me what do I need to fix.
#include <iostream>
#include <list>
using namespace std;
bool check(int passing){
int g;
if(g<=passing){
return false;
}else{
return true;
}
}
int main()
{
int pg;
... | Use a lambda as a predicate for remove_if like below:
#include <iostream>
#include <list>
int main( )
{
std::cout << "What is the passing grade?\n";
int passingGrade { };
std::cin >> passingGrade;
std::list<int> grades { 100, 90, 93, 95, 92, 49, 50, 98, 97, 99, 11, 94 };
/*grades.remove_if( [ &p... |
70,822,344 | 70,911,866 | Bazel | How to copy resources to build directory? | I am making some openGL project, and want to just copy one of my directory into build directory (I store my textures there).
So basically this is what my project structure looks like:
|-WORKSPACE
|-/src/
| -BUILD
| -main.cpp
| -*some folders here*
|-/resources/
| -BUILD
| -*some folders here*
All i want is to rem... | What you have looks correct, although the copy_resources target isn't necessary. The data dependency on //resources:resources is sufficient for those files to exist in the runfiles directory of //src:OpenGL_Project.
The files should exist under bazel-bin/src/OpenGL_Project.runfiles. When you bazel run //src:OpenGL_Proj... |
70,822,373 | 70,822,543 | How can I access that array of indexes in C++? | #include<bits/stdc++.h>
using namespace std;
int arr[10][2];
int main(){
memset(arr,-1,sizeof(arr));
for(int i=0;i<10;i++)
cout<<arr[i][i]<<" ";
return 0;
}
result = -1 -1 -1 -1 -1 -1 -1 0 0 0
I declared an array of size 2 * 10 as a global variable and initialized it to -1 using the memset func... | Your program has undefined behavior because you're accessing elements outside the bounds of the array arr.
When you wrote:
int arr[10][2]; //arr is a 2D array
The above statement defines a 2D array. This means, arr has 10 elements and each of those 10 elements are themselves an array of 2 int elements.
This also means... |
70,822,603 | 70,822,636 | Using Destructor in inheritance | In this inheritance program I create 2 classes which A is parent and B is child class . and i crate cons of both classes and also use
Destructor, and both classes have tow objects . @ MY question is that
when my program is run then its output show 2 Destructor of class a
why ?
#include <iostream>
using namespace std;... | The first "A Disturctor" is for object "A hamza(1)".
The second "A Disturctor" is for object "B Ramza(4)"
Since B inherits from A, when object of class B is destroyed, destructor of both class B and class A are called.
|
70,822,670 | 70,823,269 | How to send messages properly from python server to c++ client? | I have a python server running on the following code:
import socket
ss=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ss.bind(('0.0.0.0',8080))
ss.listen(5)
cs,adr=ss.accept()
print("Got a connection from:"+str(adr))
while 1:
msg=input('Enter your message:')
cs.send(msg.encode('ascii'))
cs.close()
For client... | char* receive()
{
char message[2000];
if (recv(sock, message, 2000, 0) == SOCKET_ERROR)
{
WSACleanup();
return (char*)"Failed to receive Message";
}
return message;
}
...
message = c1.receive();
cout << IP << ':' << port << " Says: " << message << endl;
This is wrong in multiple pla... |
70,822,701 | 70,822,850 | QT6 - signal/slot between 2 classes | I have created a new class for qpushbutton, I am trying to establish signal slot communication between this class and my mainwindow class
connect(&MyPushButton, &pushbutton::pb_isChecked, this, &MainWindow::MainWindowPBClicked, Qt::DirectConnection);
I used this code but as output only
qDebug("pushButtonClicked");
I ... | CASE 1: Not creating button in UI file:
In your class MainWindow, variable MyPushButton is a local variable that gets destroyed after it end its scope in constructor. You need to create a dynamic variable of pushButton like this:
pushbutton *MyPushButton = new pushButton(this);
connect(MyPushButton, SIGNAL(pb_isChecked... |
70,823,564 | 70,823,595 | what will bw the output of this code? c++ | #include <iostream>
using namespace std;
int f(int i){
int k=0;
if(i>0)
{
int k=i*10;
}
else {
int k= i++;
}
cout <<k;
return i;
}
int main()
{
cout << f(1);
cout << ".";
cout << f(0);
return 0;
}
This is the code, compiler shows "01.01" which i quite d... | int k = i * 10; and int k = i++; are declarations of k that shadow the outer k. The statement std::cout << k; in the outer scope therefore always outputs zero.
The only effect of the if body is to increase i by 1. And it only does that if i is zero (or less). That value of i is returned printed.
Thus the output is 01.0... |
70,823,604 | 70,937,048 | Showing metadata on response side with GRPC on BloomRPC | My goal is sending source part from request to response side. In bloomRPC, with these codes, I can send name and uuid to response side, but I cannot send metadata. Is there a similar code that I can go for metadata in here? If you need editor and response in bloomRPC, I can send that too.
//main.cpp:
class RouteGuideIm... | Well, metadata is a google map object. So I did this and it worked:
for(const auto& elements_source_metadata : request->events(i).source().metadata()){
x->mutable_metadata()->insert({elements_source_metadata.first,
elements_source_metadata.second});
|
70,823,631 | 70,833,077 | get remaining data size on tcp socket on mingw | I want to get size of remaining data on tcp socket.
On linux I can do this:
#include <sys/ioctl.h>
int count;
ioctl(sockfd, FIONREAD, &count);
But this does not work with mingw, is there any alternative solution that works in mingw?
| I found the solution:
#include <winsock2.h>
unsigned long count;
ioctlsocket(sockfd, FIONREAD, &count);
|
70,823,702 | 70,823,926 | Why is a local automatic object from a try block still alive in the catch block when I throw that object by address? | Here is the code:
#include <iostream>
using namespace std;
class A {
public:
void print() {
cout << "Object is still alive" << endl;
}
};
int main() {
try {
A a1 = A();
A* a = &a1;
throw a;
}
catch (A* a) {
a->print();
}
}
Why is object a1 still alive ... |
Why is object a1 still alive in the catch block
It's no longer alive.
you can check it for yourself, print method works
That proves nothing about the lifetime of the object.
I thought that all local objects in the try block get destroyed as soon as we leave it?
You have been thinking correctly.
The behaviour of ... |
70,823,791 | 70,823,880 | how to delete a member of vector which is a member of class | I am writing a program which is a system of library.
I have made a class of books which has setter and getter for setting and getting each information of a book; such as the name of book and the name of author.
then I made a vector of my class.
for example vector <books> book(1000).
for instance for book[1] the name is... | std::vector::erase is here for you!
It accepts an iterator to the element to be deleted, so something like
book.erase(book.begin() + idx);
would work to delete the element at index idx (in O(N) time)
|
70,824,256 | 70,824,442 | Why should I explicitly pass typename to std::forward? | Why is it necessary to explicitly indicate the type of template argument in std::forward?
template <class T> void foo (T&& x) {
goo (x); // always an lvalue
goo (std::forward<T>(x)); // rvalue if argument is rvalue
}
considering std::forward implementation:
template <typename T>
T&& forward(... | The argument's type in std::forward() is:
remove_reference<T>::type
Here T position is left of the scope resolution operator ::, which makes it a "non-deduced context" (see non-deduced context on cppreference). Because it is not automatically deduced, you have to provide the type yourself.
|
70,825,012 | 70,826,004 | Function to round a float to nearest float with specific allowed decimals | I'm trying to write a function that behaves like the following (c++, but answers in any language accepted)
float roundToGivenDecimals(float input, float allowedDecimals[])
usage:
float roundToGivenDecimals(10.4, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 10.45
float roundToGivenDecimals(3.15, [0.1, 0.45, 0.67, 0.80, 0.... | @Daniel Davies, I changed a bit your answer, now it works correctly:
double roundToGivenDecimals(double input, double allowedDecimals[], int numAllowedDecimals) {
double inputFractional = input - floor(input);
double result = input;
double minDiff = 1;
for (int i = 0; i < numAllowedDecimals; ++i) {
... |
70,825,368 | 70,826,132 | How do I correctly bind keys using the command pattern? | I've been working on a game using c++ and sfml and I've been trying to implement the command pattern as seen in the link below: https://gameprogrammingpatterns.com/command.html. More specifically, I am trying to implement the command pattern so that it can be used for any character in the scene.
I've set up a general c... | Maybe, try something like this (to initialize pointers in your class InputHandler):
#include "Command.h"
class InputHandler
{
public:
InputHandler()
{
W_KEY = new WalkUpCommand;
A_KEY = new WalkLeftCommand;
D_KEY = new WalkRightCommand;
... |
70,825,617 | 70,825,677 | Fill a double pointer matrix from CSV file | I want to fill a double pointer 2D array with the values from a CSV. I don't want to read the csv file to get the size of the array before filling it and I want to do it with pointers and not std::vector. My current code is this
std::pair<int, int> readFile(const std::string &filename, int **matrix) {
std::fstream fi... | You're passing matrix to your readFile function uninitialized, and then go on and access it with matrix[i]=tmp. That can cause all kinds of issues since you're working with memory that doesn't belong to you.
|
70,825,761 | 70,825,887 | Leaky bucket algorithm with concurrency | Trying to mimic a scenario where multiple threads are creating the traffic to fill the buckets & a thread which leaks the bucket a specified rate. However,code is running into deadlock.
Could you pl review this code ? Let me know if you see any errors & best possible modifications that I should add.
Code
#include <iost... | There are multiple fundamental bugs in the shown code.
thread t1(&LeakyBucket::leak, lb);
leak() will wait until the bucket has at least 0 fill rate, then subtract the leak rate from it. Then it will be done. That's it. It will be no more. The leaking thread will cease to exist. It will become an ex-thread. It will be... |
70,825,787 | 70,825,937 | How does `std::osyncstream` manage the out stream? | I wonder how a std::osyncstream object prevents data race conditons? Does it lock some mutex?
I'm specifically talking about the below program:
#include <iostream>
#include <fstream>
#include <thread>
#include <syncstream>
void worker( const std::size_t startValue, const std::size_t stopValue, std::ostream& os )
{
... |
Does it lock some mutex?
Yes, indirectly. The std::basic_osyncstream class, of which osyncstream is a specialization of the form basic_osyncstream<char>, is derived from std::basic_ostream and will typically have just one 'extra' member, of the std::basic_syncbuf class. From cppreference:
Typical implementation of s... |
70,826,115 | 70,932,588 | Using regular pointers on Polymorphism c++ | I'm trying to learn Polymorphism in C++, and the way I've been learning it was with raw pointers or smart pointers but then I've been trying to use regular pointers this time and I even tried to add the pointers to a vector from the constructor like this:
std::vector<bank_account*> bank_accounts;
bank_account::bank_a... | To your last comment, yes, those are two examples of different concerns. The main issue with this approach is that pointers are being put together in a vector, regardless of where actual account objects are constructed within the program, which may be entirely unrelated cases.
Therefore, the principle of separation of ... |
70,826,250 | 70,826,290 | Simplification of appender function using std::accumulate | I wanted a simple function that takes a collection of strings and appends them and returns one string which is each string item appended together. I thought std::accumulate was the way to go but interested to hear if this code could be improved.
Is there a simpler append type function that can be used here instead of ... | Yes, you can omit the lambda entirely (or use std::plus<>{}).
Also the "" can be removed from std::string(""), or the whole third argument can be removed if you switch to std::reduce:
std::reduce(strings.begin(), strings.end());
Also concatenate should take the vector by a const reference, or even better a std::span<c... |
70,826,720 | 70,828,373 | Problem with writing a value using CIN to individual data in a struct C++ | Okay so here is what I want to do, My overall goal is to create a sniping bot to snipe (The term used is) "OG Usernames" I'm currently using a struct within a header file, The reason for me doing this is to reduce code duplication to make the program run more efficiently. My overall goal is to pull a timestamp from a w... | I assume you are trying to get information to be stored into a struct based on your description. The main issue I noticed with what you are currently doing is that you never create an instance of the struct. You need to create an instance of the struct to store information in it.
Here is an example of how that could be... |
70,827,289 | 70,827,328 | Inheritance with template classes | I'm trying to figure out, how can I inherit from template class to template class. The problem is: I can't use protected members of Parent class.
Example:
template <class N>
class Parent {
protected:
N member;
public:
Parent(N aa){
member = aa;
}
};
class Child1: public Parent<int>{
public:
... | You need to use this->member or Parent<Q>::member.
In the second case, member is a "dependent name" because the existence of member from the base class template Parent<Q> depends on the type of class Q in the template, whereas in the first example there is no dependent type, the compiler can statically analyze that Par... |
70,827,356 | 70,827,442 | Why is this `my::test` not deduced template parameter? | I had a problem similar to this one: std::function and std::bind: how to load a std::bind with a function template
I didn't find any satisfactory answer, but my doubt is similar (not the same) as this post above
The code:
#include <iostream>
#include <functional>
using namespace std;
namespace my {
template <typena... | With
template <typename R, typename ...Ts>
void install2(my::test<R(Ts...)> func)
and calling
install2<int, int, int>(add);
you have provided explicit template arguments for the first template parameter and two elements of the parameter pack. But there could still be more elements in the pack. Therefore the function ... |
70,827,395 | 70,827,509 | Why memoization works, but returns false value from unordered_map | The following program countConstruct should return the number of possible way the target string can be constructed from the given wordBank. Now, the memo object seem to store the correct value for "ab" which is 2, but it prints out 1. I just cannot figure out, what am I keep missing here over and over again. I apprecia... | Please change bool --> int
Now it outputs:
countConstruct(ab, {ab, a, b}) = 2
Final code:
#include <string>
#include <unordered_map>
#include <iostream>
#include <vector>
using namespace std;
unordered_map<string, int> memo;
int countConstruct(const string& target, const vector<string>& wordBank)
{
if (target.s... |
70,827,531 | 70,827,571 | Aliasing a nested class of a template | I have the following in a header file:
template <typename T>
class RingDeque {
...
struct Iterator {
using reference = T&;
reference operator*() const;
}
}
and I want to implement the operator*() function in the cpp file. I currently have the following in the cpp file:
template <typename T>
typename Ring... | I would just use a trailing return type and be done with it.
template <typename T>
auto RingDeque<T>::Iterator::operator*() const -> reference {
//... some implementation
}
If you really want to use an alias template, then you mustn't forget it's also, as the name suggests, a template.
template <typename T>
using My... |
70,827,559 | 70,827,586 | I can't find how to add an object to a list of objects | I'm trying to add an object to a list of object the equivalent of myList.append() in python.
I've tried insert(), push_back() doesn't work because it's a list of objects.
I've tried new() and delete but doesn't work and i don't understand how it works.
there's some code missing cause else i cant send th message(too man... | You can not add to an array in c++ and other low level languages. You will need to use a vector for your case https://www.geeksforgeeks.org/vector-in-cpp-stl/
Vectors are dynamic arrays which can be added to and removed from.
Define like so:
vector<point> lines;
And use the following cmds to manipulate a vector from th... |
70,827,560 | 70,827,622 | Another Defined Symbols Not Found for Architecture x86_64 | I'm relatively new to CPP, currently in my second class for it, and while I was trying to compile a lab for my class I keep getting this error. I thought it might have something to do with file path but that doesn't seem to the be the case, does anyone have any suggestions? Here is the code:
#include <iostream>
#includ... | The problem is your class has a method name with no code.
personType(string = "", string = "");
The error message is simply telling you there is a declaration for personType::personType(string,string) but it can't find any definition code for this method. You can remove this line, as it is not necessary, and the compi... |
70,827,819 | 70,828,500 | can anyone help me with my linked list error please? | There is an issue with my code. I need to write a program that creates a linked list and performs insertion, deleting from the beginning, deleting from the end, and printing. Everything in the program works fine, but the delete the first node function. It throws an error in the printing function (posted a picture of th... | Take it easy. I read your code and there are no errors in logic. However, there are some mistakes in the selection of parameters. It is not necessary to use ** in the insert. Using * can meet the requirements, and use & to achieve assignment to the linked list. The same is true for deleteFront and deleteEnd. I modified... |
70,828,764 | 70,828,903 | Why can't we specialize concepts? | The syntax that works for classes does not work for concepts:
template <class Type>
concept C = requires(Type t) {
// ...
};
template <class Type>
concept C<Type*> = requires(Type t) {
// ...
};
MSVC says for the line of the "specialization": error C7606: 'C': concept cannot be explicitly instantiated, expli... | Because it would ruin constraint normalization and subsumption rules.
As it stands now, every concept has exactly and only one definition. As such, the relationships between concepts are known and fixed. Consider the following:
template<typename T>
concept A = atomic_constraint_a<T>;
template<typename T>
concept B = a... |
70,828,943 | 70,828,970 | "binary 'operator+' has too many parameters | Trying to implement operator overloading using the following code:
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator+ (Number<T>&, const Number<T> &);
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Nu... | You're forgetting about the implicit this parameter that are present as the first parameter in a non-static member function.
To solve your probelm just remove the extra first parameter from operator+ as shown below:
template<typename T>
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> op... |
70,829,394 | 70,829,664 | VS Code - Failing to take input from terminal | I am fairly new to tweaking with the settings in VS Code. I have installed the code runner extension on VS Code. I have also updated the settings to make the code run in terminal, instead of the output tab.
This works fine with other languages, but in case of C++, it fails to take inputs and finishes execution as soon ... | Go to settings in VS Code, and look for the property "Run in Terminal" under Code Runner settings. Check that box, and update your compiler directory. Once you do this, reload the VS Code window and run your code again, the terminal should take inputs now.
|
70,829,490 | 70,829,552 | Fill an array from For loops to create all the possibilities from 4 letters | I'm trying ton convert the following code from c++ to java and as I'm a beginner student in Java I have errors when tryin to assign the char to tabtemp. I didnt found examples with multiple For loops
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
for (char a = 97; a <= ... | you can do something like this in Java:
char[] tabtemp = null;
for (char a = 97; a <= 100; a++) {
for (char b = 97; b <= 100; b++) {
for (char c = 97; c <= 100; c++) {
for (char d = 97; d <= 100; d++) {
tabtemp = new char[]{a, b, c, d};
... |
70,830,334 | 70,830,778 | Is manually unlocking associated mutex of a RAII wrapper (like st::unique_lock) always a UB? | I wonder if manually unlocking a mutex associated with a RAII wrapper is always a UB. For example, is it ok if we lock it again before RAII wrapper destroys like this:
int i = 0;
std::mutex mx_;
void foo() {
for (int k = 0; k < 10000; k++) {
std::unique_lock<std::mutex> lk(mx_);
i++;
mx_.un... | I don't think it's UB if you pair it correctly (and no exception occur as @
DanielLangr said, which would try to unlock a already unlocked mutex)
You can pass the lock directly though.
template<typename lock_type>
class upgrade_lock {
public:
upgrade_lock(lock_type& src_lock):lock(&src_lock){
lock->unlock_... |
70,830,428 | 70,831,605 | Passing Rust vector to C++ function using cpp crate | I am using the cpp crate (https://crates.io/crates/cpp) to run some C++ code from inside Rust.
How can I make a vector, that is known to the Rust code available inside the C++ code?
First I tried something like this:
cpp::cpp!{{
#include <iostream>
#include <vector>
}}
fn call_some_cpp_stuff(mat: &Vec<f64>, n:... | If all you want to do is read the contents of the Rust Vec without mutating, you need to use as_ptr:
cpp::cpp!{{
#include <iostream>
#include <vector>
}}
fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){
let n = n as u32;
let mat = mat.as_ptr();
unsafe{
cpp::cpp!([mat as "const double *", n... |
70,830,523 | 70,834,275 | QPixmap causes memory leak? | I stream MJPEG from server and update QLabel's QPixmap every time a valid frame received. Memory usage swells in time and I cannot figure out why. Is this a wrong use of QPixmap?
case StreamState::Streaming: {
int ind_start_bytes = m_buffer.indexOf("\xff\xd8");
int ind_end_bytes = m_buffer.indexOf("... | It is the m_buffer that is swelling. The code i posted consumes frames with fifo logic. So I replaced
int ind_start_bytes = m_buffer.indexOf("\xff\xd8");
int ind_end_bytes = m_buffer.indexOf("\xff\xd9");
with
int ind_start_bytes = m_buffer.lastIndexOf("\xff\xd8");
int ind_end_bytes = m_buffer.lastIndexOf("\xff\xd9");
... |
70,830,938 | 70,840,074 | Create macro to generate getters for any class c++ | Recently I started thinking how to generalize access to private data members through a generalized class/function by name. The reason is that I have a lot of private members and creating a getter for each one is bothersome. I tried to use preprocessor macros to do the following
#define RETURNS(...) -> decltype((__VA_AR... | Revision:
As @HolyBlackCat mentioned, there is no need to heap allocation, and you should use the impl class as object directly:
class foo{
struct foo_data
{
int i;
std::string s;
};
foo_data data;
public:
template<typename ... Args>
foo(Args&& ... args)
: data(std::forward<A... |
70,830,981 | 70,832,659 | Clean-up a timed-out future | I need to run a function with a timeout. If it didn't return within the given timeout, I need to discard it and fallback to a different method.
Following is a (greatly) simplified sample code to highlight the problem. (In reality, this is an always running, highly available application. There I first read from the cach... |
My question is, in the case where the future read timed out, do I have to handle the clean-up of the future separately (i.e. keep a copy and check if it is ready time-to-time)? or can I simply ignore it (i.e. keep the code as is).
From my personal perspective, it depends on what you want. Under your current (minimal)... |
70,831,267 | 70,841,175 | Trouble dereferencing ip and port from socket pointer | I'm doing a simple send/receive and in order to execute each request in a thread I've set up my handler function like so:
UPDATE: Using std::thread and properly closing socket after use. I'm not using a loop for reading atm because I'm just sending small test messages that are well below the 1024 buffer limit. Unfortun... | So the function that saved the day is getpeername()
Here's my working solution:
int P2PServer::socketReceiveHandler(int s) {
struct sockaddr_in addr;
char buffer[1024] = {0};
int reader;
reader = read(s, buffer, 1024);
if (reader <= 0)
return 0;
socklen_t len;
len = sizeof(addr... |
70,832,007 | 70,832,118 | What is the construction order in a "diamond problem" where a class is derived from three base classes? | Below is an example code of what I am asking. The output will be XXbBACY, but I don't understand why.
#include <iostream>
using namespace std;
class X {
public:
X() { cout << 'X'; }
X(char c) { cout << 'X' << c; }
};
class A : virtual X {
public:
A() : X('a') { cout << 'A'; }
};
class B : X {
public:
... | Construction order is always this:
First all (direct or indirect) virtual bases, ordered depth-first declaration-order. Obviously at most one of any type.
Next, the non-virtual bases in declaration order.
All other members in declaration order.
Finally, the ctor body. Now you may safely call virtual functions, directl... |
70,832,270 | 70,832,396 | std::unique_ptr, pimpl and object lifetime | The following example compiles with both gcc 11 on Linux (GNU STL) and clang 12 on FreeBSD (Clang STL). On Linux, it runs and prints values 1 and 2. On FreeBSD, it prints value 1 and then crashes with a SEGV. I don't quite understand the object lifetimes -- so the whole thing may be UB and the runtime behavior might no... | Yes, the lifetime of the object that m_owner refers to has already ended and it's destructor call completed when m_owner->cleanup(); is called. The call is therefore UB.
|
70,832,564 | 70,832,680 | Are environment variables in C++ writeable? | The function getenv(const char * key) returns char *.
Does it mean that I can change some character inside of returned char array?
For example
char * name = getenv("PROJECT_NAME");
if(name && strlen(name) > 0) name[0] = 'P';
Is it good practice to do this? Should I make my own copy of array? Where are environment var... | In https://en.cppreference.com/w/cpp/utility/program/getenv:
Modifying the string returned by getenv invokes undefined behavior.
So you can modify it but doing so leads to undefined behavior. So you shouldn't do it
|
70,832,667 | 70,832,753 | Get the last element from a std::vector | In the following example, I would like to get an element from my vector. But I don't understand the error:
#include <vector>
#include <memory>
using namespace std;
class Foo{
virtual int end() = 0;
};
class Bar : public Foo{
int end(){
return 0;
}
};
int main(){
vector<shared_ptr<Foo>> a;
... | This is indeed confusing. As said kiner_shah in his comment. You don't want to use pop_back
int main(){
vector<shared_ptr<Foo>> a;
a.push_back(make_shared<Bar>());
shared_ptr<Foo> b = a.back();
}
The pop_back method doesn't return anything.
|
70,833,153 | 70,833,703 | Swap words in string C++ | I'm a new StackOverflow user! i need help. My task is to find two verbs in the string that are in the list (_words[]) and swap them. With string it's not that hard to implement, but I'm only allowed to use char.
My idea is this: I split the char(char str[]) array into words, and assign each word to a constant array(str... | Posted only because the OP asked for an alternative algorithm of how this can be done. There are other ways, but this has the benefit of being done entirely in place, using no additional storage besides some pointers and some lengths.
This task can be done in-place, by using a utility function to reverse a character se... |
70,833,373 | 70,851,544 | Deduce class template arguments from class constuctor | I would like to let compiler deduce partially class template arguments from constructor.
The motivation is to write a protocol library where the existance (here the length in bits) of certain data depends of the value of last variable, so a conditional class must be used to model this.
The c++ code I want to implement ... | The concept you are probably looking for is "type erasure", e.g. via std::function. Something along these lines:
template<typename T1>
struct If : T1
{
std::function<bool()> checker_;
template <typename T2, typename F, typename... Args>
constexpr If(const T2& cond, F&& f, Args&&... args)
: checker_([... |
70,833,377 | 70,833,409 | Why is C++ preincrement addition uniquely different from javascript, C#, etc.? (Sequence points?) | I have been trying to digest such references as Undefined behavior and sequence points and am interested as to why the outcome of the C++ variation of the following code is different from the outcome of a C# or Javascript variation of this code (see code samples, below).
Can you elaborate on this, what I think is an an... | Because (1) you never need to write cumbersome expressions like i = ++i + ++i and (2) C and C++ are all about not giving away performance, the behaviour is undefined.
(Although C++17 does define some more of these class of expressions).
On (2), different architectures may be able to optimise increments differently. Tha... |
70,833,470 | 70,835,380 | How do I exit the code at a certain breaking point in a function | In this function to calculate the factorial of a number:
int fact(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * fact(n - 1);
}
How do I add a condition
if(n<0)
cout <<"Error negative values are not accepted";
//Here I want to add something that makes me exit the function and st... | You can use std::exit() after the cout statement
|
70,833,693 | 70,833,806 | How to avoid double search on std::unordered_map AND avoid calling factory function when not required when implementing a cache | I've been implementing a cache based on std::unordered_map. I want to avoid calling the factory function that generates the value if the value is already stored but I also want to avoid running the search on the map twice.
#include <unordered_map>
struct Value {
int x;
Value & operator=(Value const &) = delete... | You can use a lazy factory. Ie one that only calls the actual factory when needed:
#include <unordered_map>
#include <iostream>
struct Value {
int x;
Value & operator=(Value const &) = delete;
};
using Cache = std::unordered_map<int, Value>;
Value make_value(int i){
// Imagine that this takes a time ok!
... |
70,833,795 | 70,834,122 | Weird compiler behavior on LeetCode | I was solving LeetCode problem: 7. Reverse Integer, for testing purposes I was printing some values (long long x2 and long long x3). Here, value of xRough were assigned to x2 and x3 if x or xRough is negative, otherwise an undefined value will be assined. But, LeetCode compiler assigns value of xRough to x2 and x3 even... | In your function:
class Solution {
public:
int reverse(int x) {
long long x2, x3;
long long xRough = (long long) x;
if (xRough < 0){
x2 = x3 = (-1) * xRough;
}
cout<<x2<<" "<<x3<<" "<<xRough<<endl;
return 0;
}
};
There are... |
70,834,127 | 70,837,717 | Using cpplint to find typos in variable initialization | I want to check my code to find typos like this:
bool check;
check == true; // should be: check = true;
This is a valid code in C/C++, so I want to use cpplint to find code occurrences of this type.
What cpplint configuration should I use?
| This typo indeed can be left unnoticed. I'd suggest you not to rely on default compiler configuration.
Assume following code:
int main()
{
int check;
check == 1;
}
When built with gcc main.c -o main the compiler will not produce any warnings at all. (Ubuntu 20.04.1, GCC 9.3.0).
However, when built with... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.