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 |
|---|---|---|---|---|
72,271,761 | 72,274,361 | Same opngl texture2d become all black in GTK but works in glut | I have a program using OpenGL + GLUT that caputre image from camera and use it as a 2D texture. Then display a pointcloud with that texture in the window. It works fine when in GLUT window. But when I change to GTK opengl area. The pointcloud (or vertices) shows but it become all black. With only changing the window re... | Problem Solved. I update the texture in a different thread. So, every time before update texture buffer. gdk_gl_context_make_current() should be called. (Because GTK window is control by thirdparty's code. Maybe it change context somehow)
gdk_gl_context_make_current(gdkContext);
glBindTexture(GL_TEXTURE_2D, TEXTURE);
g... |
72,271,935 | 72,272,029 | How to access C++ map inner values | This is my map std::map<std::string,ProductInfo> mymap and these are the values inside ProductInfo:
bool isActive = false;
char name[80];
I am already able to access a specific key - value pair (std::string - ProductInfo) using ::iterator but what I actually need is the name property inside ProductInfo
also this is wh... | You want to access the property name of the ProductInfo object inside a map. What you need to do is your_map["the key"]->get_name() where get_name() is a getter for name in ProductInfo.
|
72,272,061 | 72,273,287 | Qt c++ nested classes / solve illegal call of non-static member function | I'm dealing with sample code from a camera SDK, and I have issues getting the frame data "outside" the CSampleCaptureEventHandler class.
class DahengCamera : public QObject
{
Q_OBJECT
class CSampleCaptureEventHandler : public ICaptureEventHandler
{
void DoOnImageCaptured(CImageDataPointer& o... | CopyToImage is a private non-static function in the class DahengCamera.
The fact that CSampleCaptureEventHandler is a nested class inside DahengCamera allows it to access DahengCamera's private members and functions (as if it were decleared a friend class), but this does not provide CSampleCaptureEventHandler with a po... |
72,273,350 | 72,273,676 | Why does the speedup I get by parallelizing with OpenMP decrease after a certain workload size? | I'm trying to get into OpenMP and wrote up a small piece of code to get a feel for what to expect in terms of speedup:
#include <algorithm>
#include <chrono>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
#include <random>
void SingleThreaded(std::vector<float> &weights, int size)
{
... |
I agree with your theory; it's likely the overhead of setting things up.
While the CPU cores on your processor have their own L1 and L2 caches, they all share an 8M L3 cache, and once the vector becomes too big to fit into that L3 cache, there is the risk of the threads mutually evicting each other's pages from the ca... |
72,274,781 | 72,281,766 | Show failed function instead of macro in gtest | currently I'm working on creating new tests using gtest. There are some cases where I use same groups of EXPECT_EQs, so I wrap them up in a function. And now when particular test failes, it prints out the line where EXPECT that failed was written instead of the line where wrapper function was called.
class TestSuite : ... | This is done by adding SCOPED_TRACE("exampleName") before the function call. This will create something similar to the stack trace in the output:
TEST_F(TestSuite, exampleName)
{
SCOPED_TRACE("exampleName_scope"); // <------ Add this
std::string exampleVariable = "one";
wrapperForExpects(exampleVariable);
... |
72,274,888 | 72,275,136 | C++ default member initialization and constructors | I would like to know where I can find some documentation about the following behavior:
class Foo {
public:
Foo(int argX) : Foo(argX, defaultYValue) {}
Foo(int argX, int argY) : x(argX), y(argY) {};
private:
const int x;
const int y;
const int defaultYValue = -1;
}
Might it be possible that y value is undefin... | Yes, the code has undefined behavior. When using a delegating constructor it is the delegating constructor that will initialize the class members. When you pass defaultYValue to the delegating constructor, it has not yet be initialized so you are passing an uninitialized value to the delegate, and said delegate uses ... |
72,275,689 | 72,275,855 | What kinds of expressions are allowed in a `#if` (the conditional inclusion preprocesssor directives) | Many sources online (for example, https://en.cppreference.com/w/cpp/preprocessor/conditional#Condition_evaluation) say that the expression need only be an integer constant expression.
The following are all integral constant expressions without any identifiers in them:
#include <compare>
#if (1 <=> 2) > 0
#error 1 > 2
... | I think that all of these examples are intended to be ill-formed, although as you demonstrate the current standard wording doesn't have that effect.
This seems to be tracked as active CWG issue 1436. The proposed resolution would disqualify string literals, floating point literals and also <=> from #if conditions. (Al... |
72,275,713 | 72,276,600 | C++ Explicit instantiation of a template function results in an error "no definition available" | When trying to compile the files bellow this error occurs:
The error
Logging.h: In instantiation of 'void Sudoku::printBoardWithCandidates(const Sudoku::Board<BASE>&) [with int BASE = 3]':
Logging.h:10:64: required from here
Logging.h:10:64: error: explicit instantiation of 'void Sudoku::printBoardWithCandidates(cons... | The problem is that at the point inside the header file where you have provided the 3 explicit template instantiation, the definition of the corresponding member function template printBoardWithCandidates is not available. Thus, the compiler cannot generate the definition for these instantiations and gives the mentione... |
72,275,836 | 72,276,155 | Why can't I manually define a template parameter? | I have a simple sample which provides:
a struct template:
#include <iostream>
#include <vector>
template <typename T>
struct range_t
{
T b, e;
range_t(T x, T y) : b(x), e(y) {}
T begin() { return b; }
T end() { return e; }
};
a function template:
template <typename T>
range_t<T> range(T b, T e)
{
... | Based on the comments and this article about iterator overflow, here a complete working example:
#include <iostream>
#include <vector>
template <typename T>
struct range_t
{
T b, e;
range_t(T x, T y) : b(x), e(y) {}
T begin() { return b; }
T end() { return e; }
};
template <typename T>
range_t<T> rang... |
72,276,829 | 72,277,321 | Vector of set insert elements | I'm trying to write a function which will return vector of set type string which represent members of teams.
A group of names should be classified into teams for a game. Teams should be the same size, but this is not always possible unless n is exactly divisible by k. Therefore, they decided that the first mode (n, k) ... | teams being a std::vector<...> supports random access via an index.
auto & team_i = teams[i]; (0 <= i < teams.size()), will give you an element of the vector. team_i is a reference to type std::set<std::list<std::string>>.
As a std::set<...> does not support random access via an index, you will need to access the eleme... |
72,276,889 | 72,286,137 | How to handle this kind of c++ error in python | I have a problam in string of code:
self.db.bulk_insert('input', lines, columns_numbers = (2,3))
where db is my wrap for pymssql. Here is the method of that class:
def bulk_insert(self, table_name:str, dataset:Sequence, columns_numbers:Sequence=None):
self._connection.bulk_copy(table_name, dataset, columns_numbers... | So, I found the issue.
Befor that bulk_insert i made db request to get that id to insert. In table it int, but returns as Decimal('1') as i metioned in my question.
So, the problem was in data type I am inserting (decimal), because table type is int.
|
72,277,334 | 72,277,842 | Comparing characters at the same index of two strings | I am trying to compare the characters of two strings at a given index. However, I am getting the following error:
Line 9: Char 26: error: invalid operands to binary expression ('const __gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'const char') and 'const std::__cxx11::basic_string<char>')
... | In your code, smallest is a
std::vector<std::string>::iterator const
which is a random access iterator, hence provides operator[].
However,
smallest[i]
is equivalent to
*(smallest + i)
so it will return a reference to the i-th string after the one pointed to by
smallest instead of the i-th character of the string po... |
72,277,442 | 72,277,570 | Overloading different types in C++ | Suppose we have the following class:
class Rational { // Represents rational number. n=1/2=d for example.
public:
int n = 0;
int d = 1;
};
Rational x = Rational();
x.n = 1;
x.d = 2;
Is it possible to do overloading such that 3 * x would give 3/2 instead of an error?
My teacher said that overloading happens only b... | You may write for example
Rational operator *( const Rational &r, int x )
{
return { r.n * x, r.d };
}
Rational operator *( int x, const Rational &r )
{
return { r.n * x, r.d };
}
You may overload operators for user defined types. For a binary operator at least one of operands must be of a user defined type.
... |
72,277,533 | 72,297,026 | The remote system does not have CMake 3.8 or greater |
Introduction to the problem
I'm trying to create a MacOS app that prints a "Hello World" in C++ using Visual Studio 2022 (latest release 17.2.0) on Windows and the CMake template so I can connect remotely (using SSH) to the MacOS, I've been following this official Microsoft tutorial
Problem ocurred
The problem is t... | This seems to be a Visual Studio bug. You can keep track of it here.
Workaround
It looks like Visual Studio always looks for CMake under local folder of currently connected via SSH user (i.e. ~/.vs/cmake/bin/cmake), no matter how you installed it. Then, when Visual Studio suggests to install it:
Supported CMake versio... |
72,278,141 | 72,278,653 | Using std::async with a method receiving a cv::OutputArray in order to assign it doesn't work | I have the following function:
void MyClass::myFunc(cv::OutputArray dst) const {
cv::Mat result;
...
dst.assign(result);
}
If I run it like this:
cv::Mat result;
myFunc(result);
otherFunc(result);
It works fine and otherFunc recieves result modified by myFunc.
But if I use std::async like this:
cv::Mat re... | The root cause is that passing arguments by reference (&) to a function to run via std::async is problematic. You can read about it here: Passing arguments to std::async by reference fails (in your case there is no a compilation error, but the link explains the issue in general).
And in your case you use cv::OutputArra... |
72,278,520 | 72,278,603 | Sort Algorithm creates error message when changing objects in vector | #include<vector>;
using namespace std;
int main() {
vector<int>Liste;
Liste = { 5,2,3,6,3,4,7 };
int n = Liste.size();
int i, j, k_1, k_2 ;
int m_1, m_2 ;
for (i; i = 0; i = n - 1) {
k_1 = i; ... | insert and erase methods of std::vector take an iterator as first parameter, not a simple integer, this is roughly the sens of the error returned by your compiler. It does not find any version of insert that takes an int as first parameter.
https://www.cplusplus.com/reference/vector/vector/insert/
Anyway you can use th... |
72,278,593 | 72,278,662 | Is this causing a dangling pointer when using map of pointers | This simple code generates a warning about "Object baking the pointer will be destroyed at the end of the full expression". What does that mean? Can I not use the object entry after I use get_map? And also why is this warning showing up
static std::map<std::string, int *> get_map() {
static std::map<std::string, ... |
Can I not use the object entry after I use get_map?
No, you cannot.
static std::map<std::string, int *> get_map()
returns a copy of the map.
auto entry = get_map().find("HEY");
returns an iterator pointing into the copy. The copy is destroyed immediately after entry is assigned (because the copy was not saved in an... |
72,278,918 | 72,279,288 | vector move operation vs element move operation | For the following example, why the vector move operation is not triggered? How do I know when I should explicitly use a move operator?
#include <iostream>
#include <vector>
using namespace std;
class Test {
public:
Test() {
std::cout << " default " << std::endl;
}
Test(const Test& ... | std::vector has an assignment operator that takes an std::initializer_list:
vector& operator= (initializer_list<value_type> il);
So when you wrote p = {Test()}; you're actually using the above assignment operator.
Now why a call to the copy constructor is made can be understood from dcl.init.list, which states:
An ob... |
72,279,026 | 72,279,266 | Execution speed of code with `function` object as compared to using template functions | I know that std::function is implemented with the type erasure idiom. Type erasure is a handy technique, but as a drawback it needs to store on the heap a register (some kind of array) of the underlying objects.
Hence when creating or copying a function object there are allocations to do, and as a consequence the proce... |
I know that std::function is implemented with the type erasure idiom. Type erasure is a handy technique, but as a drawback it needs to store on the heap a register (some kind of array) of the underlying objects.
Type erasure does not necessarily require heap allocations. In this case, it is likely the implementation ... |
72,279,087 | 72,279,200 | opengl won't overlap more than 1 texture | I'm trying to create an opengl program that creates a 2d square, and applies 2 textures on it.
I followed this tutorial: https://learnopengl.com/Getting-started/Textures
This is my fragment shader:
#version 330 core
//in vec3 Color;
in vec2 TexCoord;
out vec4 FragColor;
uniform sampler2D Texture1;
uniform sampler2D ... | glUniform1i set a value in the default uniform block of the currently installed program. You have to install the program with glUseProgram, before you can set the value of a uniform variable:
GLint t1_loc = glGetUniformLocation(Program, "Texture1");
GLint t2_loc = glGetUniformLocation(Program, "Texture2");
glUseProgra... |
72,279,095 | 72,279,177 | How to check if an object is an instance of a template class of multiple template arguments in C++? | I have the following class:
template <typename T, typename U = UDefault>
class A;
How to check whether types such as A<float> or A<float, int> are instances of the above templated class?
I tried modifying How to check if an object is an instance of a template class in C++? into:
template <typename T, typename U>
struc... | Your IsA class should be expected to take one template argument. The type you are testing.
template <typename Type>
struct IsA : std::false_type {};
template <typename T, typename U>
struct IsA< A<T,U> > : std::true_type {};
// ^^^^^^ The specialization of your one template argument.
Or put alternately, sin... |
72,279,211 | 72,279,228 | Can new still throw an exception? | I'm a new C++ programmer, so I never wrote C++ code for anything older than C++11. I was reading Scott Meyers "Effective C++, 2nd Edition" (I know it is old, but I think it still has some valid points).
In the book, according to "Item 7", new can throw exceptions which should be handled.
Can new still throw exceptions?... | Yes, on allocation new can throw a bad_alloc exception.
That is, unless you pass const std::nothrow_t& as the second parameter, where you'll be guaranteed a return value of nullptr
See details here
|
72,279,221 | 72,279,258 | Passing arguments to child boost::process | void mainParent()
{
string str = ".\\childProcess.exe";
boost::process::child c(str,bp::args({stringArg}) );
c.wait();
}
int mainChild(int argc, const char* argv[])
{
cout << "test == " << argv[0] << endl;
}
string stringArg ="text";
I tried: boost::process::child c(str,bp::args({stringArg}) );
but c... |
but cout << "test == " << argv[0] << endl; outputs its own path to the exe instead of the text I want
As it should be, because argv[0] is supposed to hold the path to the exe file. The 1st command-line parameter will be in argv[1] instead, and the 2nd parameter will be in argv[2], and so on. Use argc to know how ma... |
72,279,666 | 72,279,951 | Reading multiple lines from textfile in c++ | I am trying to make a login programme that reads and writes from a textfile. For some reason, only the first line of the textfile works but the rest wont be successful login.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool loggedIn() {
string username, password, un, pw;
cout... | while (read) is the same as while (!read.fail()), which is the wrong loop condition to use in your situation. You are not checking if both getline() calls are successful before comparing the strings they output.
You also need to move the return false; statement out of the loop. Since you have a return in both the if a... |
72,280,052 | 72,282,181 | How to copy an RGBA image to Windows' Clipboard | How might one copy a 32bit (per pixel) RGBA image to Windows' Clipboard? I've arrived to this function after a lot of trial, but no luck in having my image data "paste" at all. It does not appear in the Clipboard's history either.
Slightly editing it to use CF_DIB and the BITMAPINFOHEADER header has yielded a "copy" ... | At least in my experience, trying to transfer png data with a BITMAPV5HEADER is nearly a complete loss, unless you're basically planning on using it strictly as an internal format.
One strategy that does work at least for a fair number of applications, is to register the PNG clipboard format, and just put the contents ... |
72,280,094 | 72,280,715 | Is it possible to include files in macOS bundle without using Xcode? | So, I've been trying to include shaders inside macOS bundle for a while, and only way I have found, was adding them through Xcode.
It would be nice if it would be possible to do something like that but only with CMake:
| Well, It looks like I found a solution:
set(VS_SHADER_NAME "cgui_tri_vertex.vs")
set(VS_SHADER_PATH ${PROJECT_SOURCE_DIR}/resources/${VS_SHADER_NAME})
file(COPY ${VS_SHADER_PATH} DESTINATION "${PROJECT_NAME}.app/Contents/Resources")
|
72,280,166 | 72,281,307 | .pgm images don't fit seem to fit in array | Working on some basic image processing and I need to manipulate a P2 .prg image. If there are no comments then in line two there should be a width and height value. If we take the FEEP example from this website
https://people.sc.fsu.edu/~jburkardt/data/pgma/pgma.html
then we can see the value given is 24 and the array ... | In the .pgm formats, one line of text does not correspond to one line of the image.
The first width numbers are the first row of the image. Then the next width numbers are the second row of the image and so on. How many numbers are on one line of text is inconsequential.
That means when reading the file, you should ign... |
72,280,185 | 72,280,651 | Is this GCC 12.1 const problem a bug or feature? "Attempts to call non-const function with const object" | We're seeing C++ code, that compiles successfully in GCC 11.3 and Visual Studio 2022, have issues with GCC 12.1. The code is on Compiler Explorer: https://godbolt.org/z/6PYEcsd1h (Thanks to @NathanPierson for simplifying it some.)
Basically, a template class is deciding to try to call a non-const base class function ... |
Is this gcc 12.1 const problem a bug or feature
It's a bug. I filed a bug report and the issue has already been verified coming from this commit.
The ticket has been assigned and the resolution has a targeted milestone of version 12.2 - so we can hope for a quick fix.
|
72,280,650 | 72,280,697 | Running into "error: [...] is a c++ extension" | After running:
g++ --std=c++11 -ansi -pedantic-errors -Wall -o test_database test_database.cpp
I am receiving the following errors:
./database.h:40:10: error: 'auto' type specifier is a C++11 extension [-Werror,-Wc++11-extensions]
for (auto x:composerMap_) {
^
./database.h:40:16: error: range-based for loo... | From GCC manual:
-ansi
In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98.
Remove -ansi, just -std=c++11 -pedantic-errors is enough.
I also suggest adding -Wextra...
|
72,281,084 | 72,281,520 | How to get the type underlying std::complex<T> and use it in a class | I am writing a data processor, and would like to be able to perform real-to-real, and real-to-complex computations. The setup I have right now:
// class to hold various data types
template <typename T>
class DataArray
{
public:
DataArray(){};
T *ptr;
};
// Processing configuration
template <typename T>
class ... | One way is to define a helper template which Process can use to detect whether Tout is a std::complex or not, and if so then it can use Tout's value_type member, otherwise it can use Tout as-is.
For example:
namespace helper {
template<typename T>
struct value_type_of {
using type = T;
};
temp... |
72,281,629 | 72,281,675 | C++ Most effective way to grab a substring with a value in the middle of a long string | I want to find the most effective way to do something like this:
A big string containing all kinds of data, for example:
plushieid:5637372&plushieposition:12757&plushieowner:null&totalplushies:5637373
I want to make a function that would have the input to be, let's say "plushieposition", and I would have it find and r... | Use std::string::find() to find the starting and stopping positions, and then use std::string::substr() to extract what is between them, eg:
string extract(const string &s, const string &name)
{
string to_find = name + ":";
string::size_type start = s.find(to_find);
if (start == string::npos) return "";
... |
72,281,992 | 72,282,101 | Runtime error: reference binding to null pointer of type 'int' (stl_vector.h) c++ | I know that this error refers to undefined behavior (I think), but I've reread my code 20 times and I don't see what the UB is!?
I'm doing Leetcode 238. Product of Array Except Self and here's my code (btw I don't know if this solution is right):
class Solution { public:
vector<int> productExceptSelf(vector<int>& nums)... | You can replace vector<int> result; with vector<int> result(nums.size());
This will initialize all of the values of result to 0. It won't solve the problem, but it will get rid of the runtime error you're getting.
|
72,282,042 | 72,282,873 | Get every combination (order is important) in vector with given size and elements | I want to create every possible coloring in a vector for a given size of the vector (amount of vertices) and given possible elements (possible colors)
as an example:
for a graph with 3 vertices and I want to color it with 3 colors, I want the following possible vectors, that are gonna be my possible colorings:
0 0 0
0 ... | This is definitely possible. Refer to the below code. It also works with all the other ASCII characters. You can modify it in order to meet your demands:
#include <iostream>
#include <vector>
#include <string>
inline std::vector<std::string> GetCombinations(const char min_dig, const char max_dig, int len)
{
std::v... |
72,282,372 | 72,669,979 | ROOT(CERN): How to draw a figure with title in unicode | I'm trying to draw a scatter figure via root-framework(cern). I want to set the titles of the figure in chinese, but I failed. My code for setting the title is
TGraphErrors graph(x,y,x_err,y_err);
char title[]=u8"圖表標題;x座標;y座標";//chinese title
graph.SetTitle(title);
But in the figure, all the titles are shown in garble... | There is a dirty hack: instead of providing Chinese characters via TGraph::SetTitle(), you can place TMathText instances wherever you want your characters to appear:
gStyle->SetOptTitle(0); // no graph title please, we'll create our own
double x1[5]{0., 1., 2., 3., 4.}, y1[5]{1., 2., 3., 4., 5.};
TGraph* g... |
72,282,741 | 72,282,947 | How to use the member type iterator of std::list with a while loop to make simple changes to a list | I create and modify a simple list. I replace the element at index 1 of the list. How would I semantically accomplish the same thing with a while loop. The tutorial instructor remarked that the current code is quite ugly and a while loop would accomplish the same thing in a much more simple and pretty fashion. I can't f... | You can probably do this if iterators are required:
// ...
std::list<int>::iterator it = ++numbers.begin();
numbers.insert(it, 100);
std::cout << "Current element is: " << *it << '\n';
std::list<int>::iterator eraseIt = ++numbers.begin();
eraseIt = numbers.erase(eraseIt);
std::cout << "erasing at element: " << *erase... |
72,282,784 | 72,283,015 | Multiple linking of a static library across different shared objects | Currently I have a setup where there is a 3rd-party supplied shared library, libfoo.so. Internally this links in (without using something like --whole-archive) a static library (specifically Intel performance primitives) ipps.a. This is third party so cannot be modified.
I then build a separate shared library, libbar.s... |
What are the options to deal with this, given that I can't modify the third-party library?
Both you and the 3rd party developer have committed a sin -- you are exposing symbols from ipps.a in your own interface (this is the default on UNIX).
You should hide these symbols instead, using e.g. a linker version script. E... |
72,283,549 | 72,283,643 | What is a properly way to iterate a char* string? Getting "corrupt" values | When I was trying to iterate a number (transformed to binary with bitset library) I managed this solution
#include <iostream>
#include <bitset>
void iterateBinary(int num) {
char *numInBinary = const_cast<char*>(std::bitset<32>(num).to_string().c_str());
for (int i = 31; i >= 0; i--) {
char bit = numI... | The lifetime of the string returned by to_string(), and into which the pointer returned by c_str() points, ends at the end of the full expression.
This means after the line
char *numInBinary = const_cast<char*>(std::bitset<32>(num).to_string().c_str());
the pointer numInBinary will be dangling and trying to access thr... |
72,284,547 | 72,286,626 | How to encode and decode vector in google protobuff | I have following structure in main.cpp
typedef struct s1
{
uint8 plmn[3];
}tai_s;
typedef struct s2
{
tai_s tai;
}tailist_s;
std::vector<tailist_s> tallist;
I have folowing structure in main.proto
message tai_s
{
google.protobuf.BytesValue plmn[3];
}
message tailist_s
{
tai_s tai;
}
repeated taili... | for(int i1=0; i1<proto->tailist_size(); i1++)
{
mempy(tailist.tai.plmn, proto->tailist(i1).tai().plmn().value(), 3);
}
You are trying to decode a vector. Where is that vector? Where do you create the tailist you are trying to write to? You aren't adding the tailist to the vector and overwrite it in every iteration.... |
72,284,840 | 72,285,273 | why strcat_s causing problems | I'm facing problem that I get random chars output instead of getting first and mid and last name combined which is the purpose of the program and when I run the debugger it says that the problem in strcat_s but I don't know what's the problem with it
#include <iostream>
#include <string.h>
class name {
private:
cha... | Your logic for returning the full name is incorrect. You have a local variable temp and you are returning a reference to that variable. However, this variable is destroyed once show() function is completed. So, in your main function you have a reference but its pointing to something that is already destroyed. That's wh... |
72,284,958 | 72,285,121 | C++ Vector content is being deleted? | I've been trying to create a directed graph following https://www.youtube.com/watch?v=V_TulH374hw
class Digraph {
public:
Digraph();
void addNode(Node);
void addEdge(Edge);
void print();
private:
//This is a vector which contains a node source and a vector of node destinations
vector< tuple< ... | Your auto in the for loop needs to be a reference (auto&), and after the code I'll tell you why.
void Digraph::addEdge(Edge e){
Node src = e.getSrc();
Node dest = e.getDest();
// use references here
for(auto& node : nodes){
if(get<0>(node).getName() == src.getName()){
// now this modifies ... |
72,284,984 | 72,285,907 | Draw function with glDrawArrays() needs to be called twice for anything to show | This is a strange problem. I have a function:
void drawLines(std::vector<GLfloat> lines) {
glBindVertexArray(VAO2);
//positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)0);
glEnableVertexAttribArray(0);
//colors
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,... | glVertexAttribPointer expects a buffer bound to the GL_ARRAY_BUFFER binding point in order to establish an association between the generic vertex attribute and the buffer object to source the data from.
However, you bind the buffer with glBindBuffer(GL_ARRAY_BUFFER, VBO2) after the call to glVertexAttribPointer.
This i... |
72,285,375 | 72,286,042 | Qt: Can emitting signals cause an Stack Overflow (or memory leak)? What happens if their connected slot/thread is blocked? | When the target thread which is going to capture the signal is blocked, what will happen to the signal and the memory it occupies?
Do the signals go inside a queue?
Does the queue overflow and we lose some signals?
Do we get an stack overflow?
| In general it may happen that signals are produced faster than they are consumed. This can hapen only if you use queued connections. This happens typically in multithreaded code (uses queued connection by default) or if you set your connection with flag Qt::QueuedConnection.
If your connection is not queued, then this ... |
72,285,987 | 72,289,587 | fstream::write and fstream::read changing both reading and writing pointers | I am learning about how to write records on file and read it .
I created a class called student , the class has function like enterStudent , showStudent , printInsideFile (student info) ,...... .
when I try to write student info into the file , it works .
when I try to read all student info from the file , it works
wh... | The problem was not the ios::app
It seems that functions file.write() and file.read() change either reading pointer and writing pointer . Even if you use file<<"text"; or file>>array of chars; both of pointers are changing . I searched about it but didn't find explanation but i find the code of ostream::write and ist... |
72,286,056 | 72,287,425 | Template function deduction fail on std::conditional argument | Please, before marking this as a duplicate of This question read the entirety of the post
This piece of code fails to compile, with a template deduction error:
#include <iostream>
#include <type_traits>
template<typename T = float, int N>
class MyClass
{
public:
template<typename DATA_TYPE>
using M... | As the linked question, TYPE is non deducible. MyType<TYPE> is actually XXX<TYPE>::type.
You have several alternatives, from your code, I would say one of
Bar no longer template:
template<typename T = float, int N>
class MyClass
{
public:
template<typename DATA_TYPE>
using MyType = std::conditional... |
72,286,758 | 72,292,313 | Is it safe to disable threads on boost::asio in a multi-threaded program? | I read in this SO answer that there are locks around several parts of asio's internals.
In addition I'm aware that asio is designed to allow multiple threads to service a single io_context.
However, if I only have a single thread servicing a single io_context, but I want to have more than 1 io_context in my application... | It'll depend. As far as I know it ought to be fine. See below for caveats/areas of attention.
Also, you might want to take a step back and think about the objectives. If you're trying to optimize areas containing async IO, there may be quick wins that don't require such drastic measures. That is not to say that there a... |
72,287,201 | 72,287,415 | How to overload + operator in a Template array class to add every element with the same Index together | I somewhat successfully overloaded the + operator to add 2 arrays of the same size together.
This is my current code:
//.h
#pragma once
#include <iostream>
template<typename T, size_t S>
class MyArray {
public:
T dataArray[S];
T& operator[](size_t arrayIndex);
const T& operator[](size_t a... | In the declaration of the operator function:
MyArray<T, S> operator+(const MyArray& secondSummand) const;
When you use plain MyArray it's implied to be MyArray<T, S>. The template arguments T and S are the same as for both "this" class and the class of the function argument.
If you want to use different sizes for your... |
72,289,340 | 72,289,826 | 'const static' STL container inside reentrant function | Let's say, that this is a function that serves several threads. They read kHKeys that is not protected since Read-Read from the same memory-address is not a data-race.
But, on the 1st Read, kHKeys is constructed. It is possible that during construction, another thread enters reentrantFunction function.
Is it necessary ... | It is not a must to construct kHKeys before the threads start to use reentrantFunction.
As you can see here: static local variables, since C++11 is it guaranteed by the standard that a static local variable will be initialized only once. There is a specific note regarding locks that can be applied to ensure single init... |
72,289,530 | 72,291,507 | Moving through list elements | I need to move through list elements and add them to the set. However, while moving through list I need to skip elements that are already added to set. First element of list is added to set before moving through list.
For example:
{"Damir", "Ana", "Muhamed", "Marko", "Ivan","Mirsad", "Nikolina", "Alen", "Jasmina",
"Mer... | Here's a way to use the best data structure for this without losing the list or mutating it:
Linked list of indexes.
Linked lists react well to having nodes deleted. So, as you shift, traverse the index list, use the number stored in there to index into the name list. Add that name to the set and delete the node from t... |
72,289,873 | 72,289,912 | Type defined inside class not recognized as return type of method in implementation | I am surprised why a self-defined type with using inside a class is not recognized when I use it as the return value of a method of that same class.
In this example Pair is recognized well in the class definition but not in the implementation of createPair():
#include <utility>
class A
{
public:
using Pair = std::... | The problem is that to use the alias Pair we have to be in the scope of the class A which we can do by qualifying Pair with A using the scope resolution operator :: as shown below:
//--vvv----------------------->note the A:: part
A::Pair A::createPair()
{
return {0, 0};
}
Working demo
|
72,290,269 | 72,290,397 | How do I correctly destruct a derived object that was constructed using placement new | Say we have a C++ program with this sort of class inheritance:
class A {
public:
virtual ~A() {/* ... */}
};
class B : public A {
public:
virtual ~B() {/* ... */}
};
class C : public A {
public:
virtual ~C() {/* ... */}
};
And furthermore, there are specialized memory constraints which requires that B and C... | Run this and it may help a little:
#include <iostream>
class A {
public:
virtual ~A() { std::cout << "A\n"; }
};
class B : public A {
public:
virtual ~B() { std::cout << "B\n"; }
};
class C : public A {
public:
virtual ~C() { std::cout << "C\n"; }
};
int main()
{
A* ptr = new C(); // or A* ptr = new... |
72,290,542 | 72,290,792 | Why does gcc use the size-aware delete operator by default when optimizing? | If I define my own new and delete operators as shown below:
#include <cstdio>
#include <cstdlib>
#include <new>
void* operator new (size_t count)
{
printf("Calling custom new!\n");
return malloc(count);
}
void operator delete(void *p) noexcept
{ printf("Called size unaware delete!\n");
free(p);
}
int main(... | References are to the post-C++20 draft (n4861). I am also assuming C++14 or later, which introduced size-aware deallocation functions.
For your particular example, the delete expression is required to call the size-aware operator delete, since the type to be destroyed is complete. So GCC is behaving correctly. (see [ex... |
72,290,587 | 72,290,885 | Get path of file that is called | Suppose I've got following folder structure
/dir/dir2/dir3/program.exe
I want to obtain program.exe file path as it is called. E.g.
// program.exe
#include <iostream>
#include <filesystem>
int main(int argc, char** argv)
{
std::cout << std::filesytem::current_path() << "\n";
}
But this program.exe works differen... | You are looking for a folder with the working executable. Current path giving your a process current directory
To obtain executable path
For Windows you can use GetModuleFileNameA Win API function:
For examle:
char exe_name[ MAX_PATH+1 ] = {'\0'};
::GetModuleFileNameA(nullptr,exe_name,MAX_PATH);
For POSIX you can obt... |
72,291,244 | 72,293,774 | I am having trouble cloning a linked list, what is the problem in my code? | Structure of Node:
class Node{
public:
int data;
Node *next;
Node *arb;
Node(int value){
data=value;
next=NULL;
arb=NULL;
}
};
Now, I wrote the following code, but I am getting a segmentation fault runtime error. I can't find out what is causing this error.
Node *copyLis... | There are several mistakes in your code:
clonetail->arb=ptr->arb;
The instructions you provided are very clear that the next and arb pointers in the cloned list need to point at nodes in the cloned list, not at nodes in the original list.
ptr->next=clonetail;
You are modifying the next pointer of the nodes in the ori... |
72,291,344 | 72,291,553 | Perform Memory Allocation To Store Data Obtained In Interrupt Handler | I am writing a program that uses PortAudio to get audio input from the computer into my program. PortAudio, in their Writing a Callback tutorial, says that the callback is triggered as an Interrupt Handler, and explains that code written in the callback needs to not do:
memory allocation/deallocation, I/O (including f... | Generally to avoid dynamically-allocated memory, we'll employ the use of various 'static containers.' Things like a circular buffer of pre-allocated and reserved data, or a blit buffer (two static buffers, where new data is added to one buffer, while previously-added data is processed from a second buffer. Periodically... |
72,291,579 | 72,292,335 | overflow instead of saturation on 16bit add AVX2 | I want to add 2 unsigned vectors using AVX2
__m256i i1 = _mm256_loadu_si256((__m256i *) si1);
__m256i i2 = _mm256_loadu_si256((__m256i *) si2);
__m256i result = _mm256_adds_epu16(i2, i1);
however I need to have overflow instead of saturation that _mm256_adds_epu16 does to be identical with the non-vectorized code, is... | Use normal binary wrapping _mm256_add_epi16 instead of saturating adds.
Two's complement and unsigned addition/subtraction are the same binary operation, that's one of the reasons modern computers use two's complement. As the asm manual entry for vpaddw mentions, the instructions can be used on signed or unsigned int... |
72,291,750 | 72,291,972 | How to calculate time taken to execute C++ program excluding time taken to user input? | I'm using the below code to calculate the time for execution. It works well when I take input from ./a.out < input.txt. But when I manually write my input it also includes that time. Is there a way to exclude the time taken by the user to input?
auto begin = chrono::high_resolution_clock::now();
// my code here ha... | A straightforward approach would be to "Freeze time" when user input is required, so instead of creating the end variable after the input lines, create it before the input lines and restart time calculation again after the input:
double total = 0;
auto begin = chrono::high_resolution_clock::now();
// code that needs t... |
72,291,832 | 72,318,543 | How do you upload a file using Emscripten in C++? | I'm trying to upload a file to a server. I have been successful in downloading data using Emscripten's Fetch API with a GET request, but so far have been unsuccessful with POST requests.
Here is my current implementation: (the file is being opened and read as expected, but the server is not receiving the file)
void upl... | You need to make sure that the request header has:
"Content-Type", "multipart/form-data; boundary=[custom-boundary]\r\n"
...where [custom-boundary] is a string of your choice.
Then in the request data, you start with that custom boundary, followed by "\r\n", then you have another header, such as:
"Content-Disposition:... |
72,292,118 | 72,488,349 | find memory allocated between time A and time B which remains unfreed at time C | I know that Visual Studio allows you to compare memory between two time snapshots in order to find leaks, using the debugger-integrated Memory Usage diagnostic tool. However is there a way to filter out of the diff any memory that was allocated after another time point (B) between start time (A) and end time (C) ?
Tim... | Assuming the target platform is Windows since VS2019 is mentioned, I've found a tool similar to what you are looking for.
https://www.codeproject.com/Articles/11221/Easy-Detection-of-Memory-Leaks
It is pretty old but still compiles.
Code from MemoryHooks can be used for new/delete override implementation. (void* operat... |
72,292,461 | 72,293,189 | how to return a template list in C++? | I am learning C++ in school and in my homework, my task is to create the FooClass for these:
int main()
{
int x[] = {3, 7, 4, 1, 2, 5, 6, 9};
FooClass<int> ui(x, sizeof(x) / sizeof(x[0]));
std::string s[] = {"Car", "Bike", "Bus"};
FooClass<std::string> us(s, sizeof(s) / sizeof(s[0]));
}
then modify th... | Your constructor is not copying the source elements into the array that it allocates. And, you need a destructor to free the allocated array when you are done using it.
And, your print() method is not static, so it should act on this instead of taking a FooClass object as a parameter.
Try this:
template <typename T>
c... |
72,292,600 | 72,293,093 | Maxheap giving wrong result | I wrote the following code to build a maxheap from a already existing array the downadjust function makes the array a max heap but it is not producing results as desired
Please check the code and tell me where am I going wrong also it would be very helpful if someone suggest what changes to the downadjust function will... | Result for 5 1 9 2 11 50 6 100 7 is valid heap 100 11 50 7 5 9 6 2 1.
Perhaps you wanted 50 11 sequence and other ordered pairs of child nodes, but heap construction does not provide strict mutual ordering of children (as binary search tree does).
To make minheap, you just need to change two comparisons:
if (j + 1 <= ... |
72,293,698 | 72,294,254 | What is the use of a custom unique_ptr deleter that calls delete? | In the C++ samples provided by NVidia's TensorRT library, there is a file named common.h that contains definitions of structures used throughout the examples.
Among other things, the file contains the following definitions:
struct InferDeleter
{
template <typename T>
void operator()(T* obj) const
{
... | From the history I see it was for a while
template <typename T>
void InferDeleter::operator()(T* obj) const
{
if (obj)
{
obj->destroy();
}
}
Then they declared destroy() methods deprecated:
Destructors for classes with destroy() methods were previously protected. They are now public, enabling use... |
72,293,711 | 72,293,765 | How to static assert whether all types of a tuple fulfill some condition? | I have some type traits SomeTraits from which I can extract whether a type T fulfills some condition, through SomeTraits<T>::value.
How would one go over all the types of a given std::tuple<> and check (through say a static assert) whether they all fulfill the above condition? e.g.
using MyTypes = std::tuple<T1, T2, T3... | As a one liner (newlines optional), you can do something like:
// (c++20)
static_assert([]<typename... T>(std::type_identity<std::tuple<T...>>) {
return (SomeTrait<T>::value && ...);
}(std::type_identity<MyTypes>{}));
Or you can create a helper trait to do it:
// (c++17)
template<template<typename, typename...> cl... |
72,294,123 | 72,306,568 | Task with inserting elements to list - tough a little | This is just a continuation of several past questions.
My function should return std::vector<std::set<std::string>>
A group of names should be classified into teams for a game. Teams should be the same size, but this is not always possible unless n is exactly divisible by k. Therefore, they decided that the first mode ... | One wrong thing in your check function: you only check the names in the current team to skip that, but you should skip any name that was already put in a team.
I already gave you an alternative on another question, so the check function isn't needed (erasing from the list).
Also, when iterating over a list, you should ... |
72,295,582 | 72,300,454 | How to create a new terminal and run a command in it? | I have a function like this
void smbProcess(){
string smbTargetIP;
cout<<"Target IP: ";
cin>>smbTargetIP;
string commandSmb_S = "crackmapexec smb " + smbTargetIP;
int smbLength = commandSmb_S.length();
char commandSmb_C[smbLength + 1];
strcpy(commandSmb_C, commandSmb_S.c_str());
system(... | Add "xterm -hold -e" to commandSmb_S
void smbProcess(){
string smbTargetIP;
cout<<"Target IP: ";
cin>>smbTargetIP;
string commandSmb_S = "xterm -hold -e crackmapexec smb " + smbTargetIP;
int smbLength = commandSmb_S.length();
char commandSmb_C[smbLength + 1];
strcpy(commandSmb_C, commandSmb... |
72,296,089 | 72,296,137 | i'm making a console game (on cmd), when i touch the screen with my mouse. how do i make it ignore the mouse clicks |
literally just that. in this pic when i clicked here. the car stopped coming down.
you can find the original code in this link from github.
#include<iostream>
#include <windows.h>
#include <time.h>
using namespace std; //don't hate me for it i started coding a day ago.
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE... | In your console options (the top left button), go to Properties and turn off the "QuickEdit Mode" setting. This is a Windows feature where clicking the mouse suspends whatever program is running and lets you select text from the screen. You don't want that for your program.
|
72,296,440 | 72,308,158 | How to prevent std::min and max to return NAN if the first element of the array is NAN? | Is there a way to make min/max (std::min_element) ignore all NANs? I mean, it seems to ignore NANs in the middle but not if the first element is NAN.
Sample:
template <typename T> inline void GetMinMax(const T* data, const int len, T& min, T& max)
{
min = *std::min_element(data, data + len);
max = *std::max_ele... | The safest path is to remove all the NaNs values from the range before applying any min-max standard algorithm.
Consider a possible implementation of std::min_element1:
template<class ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last)
{
if (first == last) return last;
ForwardIt smallest = first... |
72,296,686 | 72,296,722 | How do I return a string with variables and characters in c++? | I have a string function that I would like to output the following cout lines.
string print_ticket(void){
if(sold_status == true){
cout<<seat_number<<" "<<seat_number<<"sold";
}
else{
cout<<seat_number<<" "<<seat_number<<"available";
}
}
The problem is the f... | Use ostringstream, available when including <sstream>:
string print_ticket(void){
std::ostringstream sout;
if (sold_status) {
sout << seat_number << " " << seat_number << "sold";
}
else {
sout << seat_number << " " << seat_number << "available";
}
return sout.str();
}
|
72,296,737 | 72,296,779 | How can I set a var for the url in libcurl | I followed a tutorial to fetch a webpage. It worked but they manually set the URL.
I tried changing it to use a URL from a var, but that did not work.
I get an error in the terminal
"Couldn't resolve host name"
I tried main(char*) which gave the same error.
I can't seem to find anything online for this.
How can I make ... | "$website" is just a string, a piece of text. The variable should be referenced as website, and since the function is expecting a pointer to an array of characters, you use the c_str() or data() method of the class.
curl_easy_setopt(curl, CURLOPT_URL, website.data());
|
72,296,860 | 72,301,649 | Saving a nested initializer list as a variable for vector construction | I'm currently initializing a vector like this:
struct Foo{
Foo(double a, double b){
a_ = a;
b_ = b;
};
double a_;
double b_;
};
std::vector<Foo> foo_vec{{1, 2}, {2, 3}};
This correctly constructs a vector with two initialized elements. I'd like to pull this initialization out to a const global variabl... | Why do you want to mess with initializer lists? Just copy a vector:
const std::vector<Foo> default_vec{{1, 2}, {2, 3}};
std::vector<Foo> foo_vec{default_vec};
|
72,296,910 | 72,301,754 | Why allocation and sort of std::pair is faster than std::vector? | Today I just tried to solve a problem in programming. I noticed that allocation and sorting of the vector<vector> are much much slower than vector<pair<int, pair<int, int>>. I took some benchmarks and came to know that nested vector code is 4x slower than nested pair code for the given input (https://pastebin.com/izWGN... | A std::pair or std::array has a fixed size known at compile time and will include the objects directly in the class itself. A std::vector on the other hand has to deal with dynamic size and needs to allocate a chunk of memory on the heap to hold the objects.
For small objects the std::pair or std::array will be better ... |
72,297,845 | 72,298,054 | How to check if an object is an instance of template class of multiple template arguments and that one of said arguments fulfills some condition? | From How to check if an object is an instance of a template class of multiple template arguments in C++? I got the following trait to check whether a type is a particular template instantiation of a templated type of several template arguments:
template <typename T1, typename T2>
struct A
{
};
template <typename Type>... | You were on the right track:
#include <type_traits>
#include <iostream>
template <typename T1, typename T2>
struct A
{
};
template <typename Type, typename=void>
struct IsA: std::false_type
{
};
template <typename T1, typename T2>
struct IsA<A<T1, T2>, std::enable_if_t<std::is_same_v<T2, int>>>
: std::true_type
... |
72,297,871 | 72,297,985 | How to implement one loop with different frequencies | Assume the following while loop runs at 1kHz. What is the proper way to run another piece of code inside this loop but with different frequency (i.e. say 500Hz) without multithreading.
while (1){ // running 1kHz (i.e. outer loop)
do stuff
if (){ // running 500Hz (i.e. inner loop)
do another stuff
... | The easiest way is something like this:
int counter = 0;
while (1) {
// do stuff
if (++counter == 2) { // inner loop
counter = 0;
// do other stuff
}
}
Note that in a spin-loop like this there's no guarantee that the outer loop will run at 1kHz; it will run at a speed determined by the CPU spee... |
72,298,100 | 72,298,770 | How to add the READONLY style to a wxTextCtrl text box in C++ | was wondering how to add the REARONLY style to a TextCtrl in C++ for the wxWidgets framework. Im a complete noob to C++ and wxWidgets and couldn't find an comprehensible answer online. All I want to do is have a basic on screen text box holding a label text for an input text box below it. So, if im just ignorant to a b... | m_txt_box = new wxTextCtrl (this, wxID_ANY, "Test", wxPoint(100, 500), wxSize(30, 30),
wxTE_READONLY);
long style = 0 is wxTextCtrl constructor parameter after wxSize size. Required style is wxTE_READONLY.
|
72,298,249 | 72,298,310 | Why is it OK to assign a std::string& to a std::string variable in C++? | class MyClass:
public:
MyClass(const std::string& my_str);
private:
std::string _myStr
In the implementation:
MyClass::MyClass(const std::string& my_str):
_mystr(my_str)
How can you assign a reference (my_str is const std::string&) to a non-reference variable (_mystr, which is std::string)?
In my mental model... | In your case, you do not make an assignment, actually.
This line:
_mystr(my_str)
Is invoking the copy constructor of your _mystr member.
The copy constructor received a const std::string& (my_str, in your case), and constructs a clone of the object it refers to into your member _mystr.
But to answer your question in a... |
72,298,569 | 72,298,708 | How would I find the height of each node and assign it postorder in a binary search tree? | I have a templated class with an additional Node class with a height attribute. I want to be able to validate the height of each node after a new node has been inserted. My insert node function is working well, I am just confused on how I would change the height of each node after a new node is inserted.
template <typ... | The height of a node is defined as the maximum of its child nodes' heights plus 1.
Although your question title speaks of "post-order" (a term related to recursion), your code is not actually recursive. Normally, a post-order update happens after a recursive call.
Anyway, with your iterative solution the height can sti... |
72,298,630 | 72,299,030 | Recursive concept/type_traits on tuple-like types | Say I was trying to implement a concept meowable that
Integral types are meowable.
Class types with member function meow are meowable. This is in the final target but the current question doesn't focus on it.
Tuple-like types with only meowable elements are meowable.
std::ranges::range with meowable elements are meowa... |
Why this behavior? (compiler bug or something like "ill-formed NDR"?)
This is apparently a bug of GCC-trunk and Clang-trunk, the issue here is that GCC/Clang doesn't properly handle the template partial specialization based on the concept initialized by the lambda. Reduced
template<class>
concept C = [] { return tr... |
72,298,677 | 72,298,703 | C++ : second child class is unable to inherit the properties from the parent class |
Write a c++ program using inheritance to display the count of apples and mangoes in a basket of fruits.
Make three classes fruit, apple and mango. Fruit as the base class and apple and mango as child classes.
The fruit class should contain all the variables and two functions to input values and calculate the total num... |
When show_mangoes() function is called it is returning the previously declared value of the mangoes i.e. 0
The problem is that you never used m1.input_fruits() for m1 while for a1 you did use a1.input_fruits(). And since you never called input_fruits on m1 its data member mango still has the value(0) from the in-clas... |
72,298,878 | 72,298,929 | Initialize array on the heap without specifying its length | I was reading Bjarne Stroustrup's Programming Principles and Practice Using C++ (second edition). On page 597:
double* p5 = new double[] {0,1,2,3,4};
...; the number of elements can be left out when a set of elements is provided.
I typed the code above into Visual Studio 2022, and I get red underlines saying that "i... |
May I ask if it is fine to define array in such way?
Yes, starting from C++11 it is valid. From new expression's documentation:
double* p = new double[]{1,2,3}; // creates an array of type double[3]
This means in your example:
double* p5 = new double[] {0,1,2,3,4};
creates an array of type double[5].
Demo
Note
... |
72,298,972 | 72,299,071 | How to use Insert in Set for Custom Data Type ? C++ | class Game()
{
void add(set<Velocity> & v);
}
class Velocity()
{
private:
// Member Variables
public:
// Constructors and methods
}
void Game::add(set<Velocity> &velocities)
{
Velocity v;
v.setVelocity();
v.setSource();
velocities.insert(v);
}
As you can see I have a custom class called Game ... | In std::set...
sorting is done using the key comparison function...
You need to look toward something like this:
bool operator<(const Velocity&, const Velocity&);
class Velocity {
friend bool operator<(const Velocity&, const Velocity&);
private:
unsigned velocity_value;
// ...
};
bool operator<(const Veloci... |
72,299,026 | 72,300,411 | Convert if constexpr based C++17 templatized code to C++14 | I am working on downgrading a project written in C++ 17 to C++ 14. While downgrading, I came across a piece of code involving if constexpr and I wish to convert it to C++ 14 (From what I know, if constexpr is a C++ 17 feature).
Boost's is_detected is used to check if a given type has star operator or get method.
#inclu... | How about a solution exploiting tag dispatch?
The idea is to move the code from your branches to three auxiliary functions.
These functions are overloaded on the last parameter, whose only purpose is to
allow you calling the right one later on:
template <typename T>
constexpr const auto& deref(const T& value);
templat... |
72,299,327 | 72,302,561 | Why do we need to specify namespace if we also need to include standard library headers? | Completely new to C++, but have done some work in C. Have just seen the Hello, World example:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
My question is why we must specify that cout is from the standard library, when I have already included the declarations for cout fro... | Generally namespaces prevent name clashes between different modules or libraries. Now you might say that the std namespace is the standard that everyone uses so nobody should name their variables, classes or functions to clash with the standard.
But that is short sighted. What is used in todays standard is not the same... |
72,299,536 | 72,299,612 | Reference over array into array of reference | I have an array std::array<T, N> arr for some T, N and I'd like to get an array of reference over arr's elements like so std::array<std::reference_wrapper<T>, N> arr_ref.
But as a reference needs to be set at its initialization, I did not work out a solution.
Therefore I would like to do something like that:
std::array... | #include <array>
#include <functional>
#include <utility>
#include <cstddef>
template<typename x_Item, ::std::size_t x_count, ::std::size_t... x_index___>
auto wrap_impl(::std::array<x_Item, x_count> & items, ::std::index_sequence<x_index___...>)
{
return ::std::array<::std::reference_wrapper<x_Item>, x_count>{ite... |
72,300,721 | 72,300,795 | How to sort diferent type of lists with template in C++ | In my homework my task is to create the FooCl class for these:
double d[] = {1.3, 0.7, 2.4, 1.5, 6.2, 5.7, 8.6, 9.1};
FooCl<double> itemsD(d, sizeof(d) / sizeof(d[0]));
std::string s[] = {"C++", "Haskell", "Python", "Java"};
FooCl<std::string> itemsS(s, sizeof(s) / sizeof(s[0]));
itemsD.mySort();
... | One way is to use std::sort as shown below:
void mySort()
{
//--vvvvvvvvv------------------------------------>use std::sort
std::sort(mItems, mItems + mItemsSize);
}
You can even write your sort functionality/implementation which will include the use of mItems and mItemsSize.
|
72,300,831 | 72,381,813 | Is there a (portable) way to detect layout change in C++ classes? | For example say I have a class Foo with a typical serialization pattern.
struct Foo {
int a;
bool b;
template <typename Archive>
void serialize(Archive & ar) {
ar & a;
ar & b;
}
};
Now suppose somebody comes along and adds a field.
struct Foo {
int a;
bool b;
std::string... | There is cool library in boost: boost pfr. I never used it in real project (just some toys), but seems to work quite well:
struct Foo {
int a;
bool b;
template <typename Archive>
void serialize(Archive& ar, const unsigned int)
{
boost::pfr::for_each_field(*this, [&ar](const auto& field) { a... |
72,301,113 | 72,302,798 | does mkl_vml_serv_threader in the gprofile means MKL is not running sequentially | We're running an application that's in the process of being MKL BLAS enhaced. We've been told not to hyperthread.
In order for multithreaded (so-called parallel?) version to not be considered during compilation, i.e. to disable hyperthreading but only wanting MKL sequential vectorization, we removed the threaded librar... | By default, Intel® oneAPI Math Kernel Library uses the number of OpenMP threads equal to the number of physical cores on the system and it runs on all the available physical cores until and unless we mention some options which are mentioned below.
Intel compilers like icc(latest) have a compiler option -qmkl=[lib] and ... |
72,301,682 | 72,301,781 | c++ Array class template with template parameters | i have Created an Array class template with template parameters <element type, size > and
array class members, input, sort, and output functions.
but code does not work below what might i be doing wrong?
#include <iostream>
using namespace std;
template <class T, int n>
class array {
T mass[n];
public:
... | You have some typos in your code. In particular, you have use [ instead of { and mas instead of mass. These are correct and highlighted using comments in the below code:
template <class T, int n>
//----------------------------v------------------->[ changed to {
void array < T, n > ::sort(){T x; int p = 1, m = n;
... |
72,302,070 | 72,302,201 | Set the bounds of an array after object initialisation in cpp | I'm working on an image renderer in C++ that I wrote from scratch (I don't want to use anything but standard libraries), but I'm having some trouble when trying to store the image. The class I use to store images looks like this:
class RawImage
{
private:
RGB pixels[][][3] = {};
public:
int widt... |
Set the bounds of an array after object initialisation in cpp
The size of an array never changes through its lifetime. It's set upon creation. Technically this isn't a problem for you because you can initialise the array in the constructor.
But, size of an array variable must be compile time constant, so you cannot a... |
72,302,797 | 72,302,831 | Why &x[0]+x.size() instead of &x[x.size()]? | I'm reading A Tour of C++ (2nd edition) and I came across this code (6.2 Parameterized Types):
template<typename T>
T* end(Vector<T>& x)
{
return x.size() ? &x[0]+x.size() : nullptr; // pointer to one-past-last element
}
I don't understand why we use &x[0]+x.size() instead of &x[x.size()]. Does it mean that ... | &x[x.size()] would result in (attempting to) take the address of x[x.size()]. However x[x.size()] attempts to access an out of bound element; depending on the API of Vector<T>::operator[] for the particular T, a number of bad things could happen:
| Vector<T>::operator[] semantics |
| ===========================... |
72,302,914 | 72,303,868 | Creating list of unique_ptr using initialization list and make_unique fails in GCC 5.4 | I am using GCC 5.4 for compiling a test program in C++ 14.
#include <type_traits>
#include <list>
#include <iostream>
#include <memory>
int main()
{
int VALUE = 42;
const auto list_ = {
std::make_unique<int>(VALUE),
std::make_unique<int>(0),
std::make_unique<int>(0)
};
}
GCC 5.4 fa... | You can use:
const std::initializer_list<std::unique_ptr<int>> list{
std::make_unique< int >( 42 ),
std::make_unique< int >( 0 ),
std::make_unique< int >( 0 )
};
Demo (old gcc-5.4 tested).
|
72,304,199 | 72,304,328 | No matching Constructor Error For Initialization in c++. Whats wrong with my constructor? | I have a class in a header file as follows:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class ShowTicket {
public:
bool is_sold(void){
if (sold_status == true){
return true;
}
else{
return false;
... | By the looks of it, you only want to supply two arguments, but your constructor requires three:
ShowTicket(const char* row, const char* seat_number, bool sold_status){
sold_status = false;
}
The body of the constructor makes be believe that you want to initialize a newly created ShowTicket with sold_status set to ... |
72,304,669 | 72,305,262 | Z-Function and unique substrings: broken algorithm parroted everywhere? | I am not a huge math nerd so I may easily be missing something, but let's take the algorithm from https://cp-algorithms.com/string/z-function.html and try to apply it to, say, string baz. This string definitely has a substring set of 'b','a','z', 'ba', 'az', 'baz'.
Let's see how z function works (at leas how I understa... | When you add a character x to the beginning of a string S, all the substrings of S are still substrings of xS, but how many new substrings do you get?
The new substrings are all prefixes of xS. There are length(xS) of these, but
max(Z(xS)) of these are already substrings of S, so
You get length(xS) - max(Z(xS)) new o... |
72,304,983 | 72,309,003 | Casting structs to add definition to a shared-memory block in a SIMD application | I am building an application that requires the use of a large block of shared memory space of type double. This block needs to be byte aligned to ensure proper loading into SIMD registers. For example
double *ptr_x = (double *)_mm_malloc(sizeof(double) * 40, 32);
Internally, there are several calculations that use the... |
Is there a preferred way to performing this mapping?
It’s subjective. C++ books say the preferred one is reinterpret_cast like you are doing. Personally, I think C-style casts like (Position*)( ptr_x + 16 ) is more readable.
Also if you have these things at sequential addresses, consider defining a larger structure w... |
72,305,082 | 72,305,353 | Using a self calling function within a while loop C++ | I am new to C++ and I am exploring the behavior of self calling function calls used inside a while loop. Here is the code I wrote
#include <iostream>
using namespace std;
void self_calling_function(int);
void self_calling_function(int i){
cout << "Inside function :" << i ;
while(i < 5){
i++;
... | Looking at your comments i think you wanted the recursive calls to end once 5 is reached. This can be done by make the parameter of the function to be a reference type as shown below:
//-----------------------------v----->i is an lvalue reference to non-const int
void self_calling_function(int &i){
cout << "Inside... |
72,305,152 | 72,320,526 | Erro trying to build qml lib to Android | I'm using a qml lib with a qt c++ projetc, and work well in linux and windows, but when I try to build to Android I receive this error:
make: *** No rule to make target 'install'. Stop.
09:40:07: The process "/home/ysaakue/Android/Sdk/ndk/21.3.6528147/prebuilt/linux-x86_64/bin/make" exited with code 2.
Error while bui... | Apparently the problem was because this project is a lib, and in the default build steps has some to copy the files to target device, and in my case it isn't required, so I disabled(using the QtCreator interface as bellow) the last two stets and the problem was solved. (for now at least).
|
72,305,314 | 72,306,718 | How to link libraries in cmake | I am trying to pass my c++ project that I was developing in Linux to windows.
I am using cLion so a cMake.
this is my Cmake
cmake_minimum_required(VERSION 3.10) # common to every CLion project
project(PackMan) # project name
set(GLM_DIR C:/libs/GLM/glm)
set(GLAD_DIR C:/libs/GLAD/include)
include_d... | You are doing that wrong way. You should use find_package instead hard-coding paths.
This should go more or less like this:
find_package(PkgConfig REQUIRED)
pkg_search_module(GLFW REQUIRED glfw3)
add_library(mainScr
scr/Carte.cpp
scr/Enemy.cpp
scr/MoveableSquare.cpp
scr/Palette.cpp
... |
72,305,432 | 72,306,849 | Ignore commemts while parsing txt file C++ | I have a large text file and I am parsing using string stream. Text file looks like this
#####
##bjhbv
nvf
vbhjbj
vfjbvjf
*bj
*bvjbv
.
.
.
.
+FILE
data I want to parse from here to
.
.
.
.
-FILE
till here
#shv again comments
.
.
How can I parse only between +FILE to -FILE? I can parse inside off it, but i just want... | As you see in the comments, you can discard above +FILE. you can use flag and condition method. Where use,
while(some_condition)
{
//ignore comments
if(!std::find("#"))
{
continue;
}
bool flag=false;
if(!std::find("+FILE"))
{
flag=true;
}
if(!std::find("-FILE"))
{
flag=false;
}
if(flag)
{
..
... |
72,305,519 | 72,305,758 | Does the C++ standard guarantee that when the return value of 'rdbuf' passed to the stream output operator, he conent of the buffer gets printed out | Consider the following code snippet:
std::stringstream ss;
ss << "hello world!\n";
auto a = ss.rdbuf();
std::cout << a; // prints out "hello world!
The variable a is a pointer to an object of the type std::stringbuf. When it is passed to the stream output operator <<, with GCC9.4, the content of the stream buffer poin... | A std::basic_stringbuf is derived from a std::basic_streambuf. Cppreference describes its use:
The I/O stream objects std::basic_istream and std::basic_ostream, as well as all objects derived from them (std::ofstream, std::stringstream, etc), are implemented entirely in terms of std::basic_streambuf.
What does that m... |
72,305,685 | 72,306,619 | Erasing list elements step by step | I want to erase list elements one by one. Before removing any of list elements I want to see the whole list.
#include <iostream>
#include <list>
int main()
{
std::list<int>numbers{0,1,2,3,4,5,6,7,8,9};
auto it=numbers.begin();
for(int i=0;i<10;i++){
for(auto j:numbers)
std::cout<<j<<" ";
... | The issue is with these two lines
it=numbers.erase(it);
it++;
The function, list::erase, returns an iterator pointing to the element that followed the last element erased. Here, your code removes the item from the list and sets it to the next element in the list. Then the instruction it++ advances the iterator one mor... |
72,306,477 | 72,306,597 | How to parse floating point number using sscanf | This works well, outputting 1 3
std::string s("driver at 1 3");
int c, d;
sscanf(
s.c_str(),
"%*s %*s %d %d",
&c, &d );
std::cout << c <<" "<< d <<"\n";
But this fails, outputting 6.95129e-310 6.... | You have a bug in your format string. You should increase the warning your compiler outputs: https://godbolt.org/z/Pfd414o45
#include <string>
#include <cstdio>
#include <iostream>
int main() {
std::string s("driver at 1 3");
double c, d;
sscanf(
s.c_str(),
"%*s %*s %f %f",
&c, &d )... |
72,306,529 | 72,319,993 | DLLNotFound when using DLLImport with shared library | I am creating a .NET Framework 4.0 application that use a DLL when launch on Windows and a shared library wrote in C++ when launch on Linux (debian version 10).
The C# codes looks like that :
[DllImport("graf")]
private static extern int Method1();
On Windows, everything is fine, and the application works very well.
O... | My problem came from the fact that 1) my library was badly compiled (Makefile problem); and 2) I had to use the keyword extern "C" { in the definitions of my functions.
See What is the effect of extern "C" in C++? for more details.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.