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 |
|---|---|---|---|---|
64,311,322 | 64,311,348 | vector<vector<float>>::size_type or vector<float>::size_type when dealing with vector<vector<float>>'s size()? | code_1:
std::vector< std::vector<float> > grid (5, std::vector<float>(3, 1));
std::vector< std::vector <float> >::size_type rows = grid.size();
or
code_2:
std::vector< std::vector<float> > grid (5, std::vector<float>(3, 1));
std::vector<float>::size_type rows = grid.size();
Should I use code_1 or code_2 ? and why ?
t... | Given that std::vector< std::vector<float>>::size returns value of type std::vector< std::vector <float>>::size_type, why would you use it to initialise a variable of type std::vector<float>::size_type?
That said, those are the same type, so it makes little difference. The type is std::size_t, so you might as well use ... |
64,311,502 | 64,311,605 | How return "int" value in a template c++, with strings as parameters | I'm learning c++ for the first time.
I want to develop a template to calculate length of a const char*, char[] without having to redefine the same function.
I have tried,
template <class N> N length(N str){
int pos = 0;
while (str[pos] != '\0'){pos++;}
return pos;
}
But I got an error, since I should ret... | There are functions to do that but if you want to use templates, here is a function.
Note that u return N and u ask how to solve this problem while u should return size_t.
#include <iostream>
template <size_t N>
constexpr size_t length(const char (&arr) [N]){
return N-1;
}
int main(){
char arr [3] = "me";
... |
64,311,520 | 64,323,379 | C++ Segmentation fault -- Self-balancing Tree insertion | I'm trying to solve a self-balancing tree problem on Hackerrank (https://www.hackerrank.com/challenges/self-balancing-tree/problem) and I keep getting a Segmentation fault in the last 3 test cases. I saw that this same problem had been posted before and tried to apply the same approach (check for nullptr) to my case, b... | Thanks to everyone who tried helping me out on this one, it turns out there is no limit to how dumb I can be. I believe I've figured out what I had done wrong.
The problem in this question lies on the section that checks if the right subtree is disbalanced and, if so, performs the necessary rotations. On the code piece... |
64,311,624 | 64,312,050 | Qt5 no polish characters after reading from QNetworkReply | I need to get data from this url https://www.nbp.pl/kursy/xml/lasta.xml. The problem is that response contains broken polish characters (????? instead of śćąęó).
My console and GUI is fully capable of showing polish characters and only this one content string is broken.
I have no idea what to do with this. I'm using CL... | This works.
std::string DataDownloader::downloadData() const
{
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(this->url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
QTextCodec* codec = QTextCodec::cod... |
64,311,696 | 64,312,134 | C++: invalid conversion from 'int' to 'int*' | I have the following code:
#include <iostream>
using namespace std;
void A(int m, int array[]) {
int change=array[0];
for (int i=0; i<m; i++) {
array[i]=array[i+1];
}
array[m-1]=change;
}
void B(int m, int array[]) {
int change=array[1];
for (int i=1; i<m; i++) {
array[i]=array... | In both of your function calls you are passing a value present in the array, in function definition it's array declaration which is more or less pointer only. Try sending the array by reference and it will work.
change this ->
B(m,array[m]);
to this
B(m,array);
|
64,311,845 | 64,312,019 | C++ std::memory_order_relaxed confusion | I was reading this article from GCC Wiki about C++ memory barriers (and its awesome).
It was pretty straightforward until I got to this point:
The opposite approach is std::memory_order_relaxed. This model allows for much less synchronization by removing the happens-before restrictions. These types of atomic operations... | Relaxed ordering is relative to the ordering of operations with regard to other memory accesses, not ordering relative to the atomic being relax-modified. In your first case, the fact that you can see 10 in x doesn't mean anything with regard to the value of y. And vice-versa.
But your second case is different, because... |
64,311,903 | 64,311,979 | searching strings for certain letters...why is for loop not looping through all letters of string? | I have a file of a bunch of words and want to extract the ones that contain a 'q' or 'Q'. I have a function called isQWord that scans a string for these letters and, if it does contain these letters, puts the word into a vector called qwords. The function also does a few other things, but I've omitted these parts becau... | Inside your isQWord() function, you are breaking your for loop after the first iteration no matter whether the rest of the word contains a Q or not. You are not scanning that entire string. You need to move the return false statement after the loop ends without finding a Q.
You are putting too much responsibility on t... |
64,312,039 | 64,312,116 | How to get warning for implicit conversion to lower precision? | void func( int radius ) { ... }
which is called like this:
func( 12.4 ); // by user expecting the float to be processed, not realizing there's an implicit conversion
Is there any way to get a warning in such a case from the compiler or runtime environment?
| If you delete the overload of func that accepts a double argument:
void func(double) = delete;
your user will get a hard error:
func(12.4); // error, user can't choose to ignore it
which is even better than a warning.
Here's a demo.
|
64,312,104 | 64,312,231 | what`s the difference between !root and root!=NULL | here is my code.
vector<int>k;
void h(TreeNode *root) {
if(root)return;
if (!root)k.push_back(root->val);
if (!root->left)h(root->left);
if (!root->right)h(root->right);
}
vector<int>k;
void h(TreeNode *root) {
if(root==NULL)return;
k.push_back(root->val);... | No, !root is exactly the opposite of root != NULL.
!root
will perform an implicit conversion of root to bool, then invert the result. Here the reference says:
The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other valu... |
64,312,490 | 64,312,941 | how to pass float* array to C method from python script whose memory allocation takes place in C layer | I am trying to call C methods from Python script, C method calls inturn the C++ method. I am allocating array inside the getResults() method using malloc(). Now the issue is how to pass the arguments to float* oresults in python script whose memory allocation takes place inside the C layer.
This is io.c
int getResults(... | The float* oResults parameter is passed by value, so it is impossible to return an allocated pointer in that parameter. Instead, use a float** oResults.
Also, float_values = POINTER(c_float) is a type, not an instance of a type. So byref(float_values) is equivalent to the invalid C &(float*). Instead, you want an in... |
64,312,577 | 64,313,029 | Get number of arguments in a class member function | I am trying to get the number of parameters in a class member function.
template <typename R, typename ... Types>
constexpr std::integral_constant<unsigned, sizeof ...(Types)>
FuncArgCount(R(*f)(Types ...))
{
return std::integral_constant<unsigned, sizeof ...(Types)>{};
}
class TestClass
{
public:
TestClass()... | First, you have to overload for pointer to member. Pointers to member aren't actually pointers, they are separate type representing an offset within type.
template <typename R, typename T, typename ... Types>
constexpr std::integral_constant<unsigned, sizeof ...(Types)>
FuncArgCount(R(T::*)(Types ...))
{
return s... |
64,313,224 | 64,313,651 | C++ type index hashing causes undefined behaviour | Following the example on https://en.cppreference.com/w/cpp/types/type_index and compiling with -fsanitize=address,integer,undefined reveals an undefined behaviour. Code is:
struct A
{
virtual ~A()
{}
};
struct B : A
{
};
struct C : A
{
};
int main() {
std::unordered_map<std::type_index, std::string> type_names;... | Unsigned integer overflow is not undefined behaviour, however UBSan still has an option to check for it because it is often still a bug. But not in this case. This warning is provoked by a totally innocent hash function. It is supposed to have unsigned integer overflows.
You can silence this warning.
You can also repor... |
64,313,394 | 64,313,459 | c++ non virtual function acts like virtual function | Probably, i misunderstood c++ polymorphism(virtual function).
Please point me what i miss.
the source code is below
#include <iostream>
using namespace std;
class A {
public:
virtual void print(void) {
cout<<"class A"<<endl;
}
};
class B : public A {
public:
void print(vo... | If a function with a given signature is declared as virtual in a top-level base class, then the function is virtual in all derived classes no matter if it is marked with the keyword virtual (override, final) or not:
virtual function specifier
Then this function in the class Derived is also virtual (whether or not the ... |
64,313,543 | 64,313,957 | C++ equivalent of C# Convert | In C#, there is a class with static methods for type conversions:Convert.ToUInt16(). Is there a C++ equivalent of these methods. I know a few, like to_string from string.h, but it would be better if all of these type conversions were in one place.
|
if all of these type conversions were in one place
Conversions to or from std::string are in namespace std, whilst conversions between arithmetic types are casts.
std::cout << std::to_string(1.2)
int i;
auto num = "1"s;
std::from_chars(num.begin(), num.end(), i);
std::cout << i;
std::cout << static_cast<std::uint16_t... |
64,313,634 | 64,333,053 | Compiling for macOS arm64 arch | I am using macOS 10.15.7 to build a simple hello world C++ program for macOS arm64 architecture (not iOS). I have Xcode 12 installed. I tried the following:
xcodebuild -project TestApp.xcodeproj clean build ARCHS=arm64 EXCLUDED_ARCHS=""
But received the following error:
/Applications/Xcode.app/Contents/Developer/Platf... | The SDK for macOS Big Sur wasn't released as part of the public Xcode 12.0 release, it only contains the SDK for Catalina (macOS 10.15).
To target macOS Big Sur (and macOS on Apple Silicon), you need the beta SDK (Xcode 12.2 beta).
|
64,313,909 | 64,314,236 | How to design the return type of getData()? | #include <variant>
#include <iostream>
typedef unsigned char uint8_t;
enum class typeFlag {
kFloat32 = 0,
kFloat64 = 1,
kUint8 = 2
};
class NDArray;
template<typename T>
class TBlob{
friend class NDArray;
public:
TBlob(): dptr_(nullptr) {};
TBlob(size_t size): dptr_(new T[size]) {};
... |
A single non-template function (or class member) cannot have a return type dependent on some runtime value (dtype_ in your case), that's the core of the error. The compiler tries to deduce a single return type and fails, since different code paths return float *, double * and uint8_t *.
It isn't true that your operati... |
64,315,243 | 64,315,318 | How do I check the contents in a vector using google-test? | std::vector<uint8_t> vector1(10);
std::vector<uint8_t> vector2(10);
std::fill(vector1.begin(), vector1.end(), 2);
std::fill(vector2.begin(), vector2.end(), 2);
EXPECT_EQ(vector1, vector2);
Does the EXPECT_EQ() above check that the contents in vector1 and vector2 are equal? If not, how do I check that
that the conten... | EXPECT_EQ uses operator == to compare objects, and operator == for std::vector (quote from cppreference):
Checks if the contents of lhs and rhs are equal, that is, they have the same number of elements and each element in lhs compares equal with the element in rhs at the same position.
So the answer is yes, it will c... |
64,315,287 | 64,315,386 | Need to iterate over entire object except for first two elements. Is there a design pattern? | I have a std::vector that I would like to iterate over each object except the first two. A foreach loop would be perfect if I didn't want two . i.e. for(const auto i : items)
Possible solutions I've thought of are erasing the first two and re-adding at the end
const auto firstEle = myVec[0];
const auto secEle = myVec[1... | I usually go with a conventional loop for these things:
// verify myVec.size() > 2
for(auto it = myVec.begin()+2; it != myVec.end(); ++it) {
// work
}
If you want C++11 lambda magic, then
std::for_each(v.begin()+2, v.end(), [](auto& element) {
// do stuff
});
will do it.
|
64,315,495 | 64,315,653 | How to change makefile diagnostic message when compiling [ GNU ARM GCC, Eclipse make.exe] | I'm building a program for STM32F4 by using GNU-ARM-Gcc and Eclipse_make.exe to build the project. Everything works fine but the diagnostic message show on the terminal when compiling is too long and very hard to see. When each *.c file is compiled, the Terminal gives me a diagnostic message (see the paragraph below) c... | So make by default echo's each line it runs - your compiler line in the makefile:
$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR)
$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@
Will output the execution line what you can do is:
$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR)
@ec... |
64,316,116 | 64,316,416 | C++ , create structure with an optional value | I need to create structure with an optional value :
typedef struct pkt_header{
unsigned short Packet_Type;
unsigned short Unprotected_Payload_Length;
unsigned short Protected_Payload_Length; // optional (present/not present)
unsigned short Version;
} PKT_HEADER;
How can i sometimes use pkt_header->P... | Beware. Structs can have padding, members are not necessarily adjacent in memory. Moreover reinterpreting something as a PKT_HEADER when that something is not a PKT_HEADER object is not allowed. Instead of casting:
PKT_HEADER * header= (PKT_HEADER*)recvbuf;
you probably should use memcpy. Having said this, now to you... |
64,316,138 | 64,316,604 | String concatenation not working while concatenating with character | I attempted the following:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as one 1 or 11.
11 is read off as two 1s or 21.
21 is read off as one 2, then one 1 or 1211.
Given an integer n, generate the nth sequence.
I actually wrote some code to sol... | str += "1" + s[s.size() - 1];
Does not mean
str += "1";
str += s[s.size() - 1];
But
str += ("1" + s[s.size() - 1]);
where the right-hand-side expression is not at all what you wanted.
The expression "1" is not a char, but a string literal containing the two characters {'1', 0} (it's a C string, so there is a null t... |
64,316,293 | 64,320,796 | Computing apparent magnitude with Armadillo (C++) | I'm looking for someone very expert in using Armadillo (C++). I am a wannabe astronomer and I'm trying to compute the ab apparent magnitude m_ab of a SSP (simple stellar population, a group of chemically homogeneus and coeval stars) in a specific filter of a telescope.
The input of the function compute_ab, which does t... | There are a few problems with this code and maybe a few operations that are not doing what you want.
You are coping the the input vectors, which can be very costly and is completely unnecessary. Change
mat compute_ab(vector <long double> waves,vector <long double> sed, vector <long double> fwaves,vector <long double... |
64,316,534 | 64,317,167 | How to make a function to adress doubly linked list node? | I made an inmplementation of doubly linked list as class in C++
In main.cpp I'm pushing objects of other class into this list like this
list.insertBack(ClassA(name, description));
But after that I need to change a certain field of this object, for example perform a method that changes population. For that I need to so... | You just need to provide a operator[] for your class:
template<class T>
class List {
// your private interface
public:
// your other public interface
T& operator[](unsigned int i)
{
Node* n = this->head;
for (; i>0; --i)
{
n = n->next;
}
return n-... |
64,317,304 | 64,330,564 | Running CMake from CreateProcess returns FileTracker FTK0001 error | After updating my windows 10 to 1903, executing the following cmake command using CreateProcess:
command: cmd /C "cmake -G "Visual Studio 15 2017 Win64" -DCMAKE_TOOLCHAIN_FILE="D:/vcpkg/scripts/buildsystems/vcpkg.cmake"" ..
code: CreateProcess("C:\\Windows\\System32\\cmd.exe", command, NULL, NULL, FALSE, NULL, 0, worki... | I found the answer: the Child Process Debugging extension produces this problem after the update. Disabling this extension fixes the problem.
|
64,317,405 | 64,317,688 | How to do the multiplication of small decimal numbers typed in QLineEdit? | I am trying to calculate the forces between two charges(Coulomb's law) in c++ qt. I have 3 lineedits where the user can type numbers (the first lineedit is related to Point Charge 1(q1), the second lineedit is related to Point Charge 2(q2) and the third lineedit is related to the distance between two point charges(r)).... | You should _NOT use the function abs, because that returns an integer, and as consecuense small decimal values will be rounded to Zero
use instead qFabs
here the doc:
qreal qFabs(qreal v)
Returns the absolute value of v as a qreal.
https://doc.qt.io/qt-5/qtmath.html#qFabs
|
64,317,582 | 64,318,131 | How to read = separated data from file | I have a data file that contains key value pairs separated by an = character.
Example data file is like below.
A = 1
B = 2
C = 3
D = 4
I want to read only some keys from the data file. For example, I only want to read A and C keys in this example. I used a for loop and getline to do this but unable to get data.
Belo... | Starting from the second getline(), the key value will be what is left in the line of the previous called until the next = in the following line.
This example will make it easier to understand.
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// pretend file stream
std::istringstream data("A... |
64,317,833 | 64,319,733 | How to compile and run a hello world JUCE program? | I cloned https://github.com/juce-framework/JUCE
I first uncommented find_package(JUCE) in /GuiApp' CMakeList.txt.
Then I ran cmake .. . -B cmake-build-dir -D JUCE_BUILD_EXAMPLES=ON
on the top level directory.
It says:
-- Checking for modules 'webkit2gtk-4.0;gtk+-x11-3.0'
-- No package 'webkit2gtk-4.0' found
-- No... | Clone this repository: https://github.com/juce-framework/JUCE
alsa and webkit2gtk are required dependencies which were absent on Ubuntu 18.04 in my computer. You too may have to install as follows:
sudo apt install libwebkit2gtk-4.0-dev libasound2-dev
In the examples/CMake folder in this repository there is a folder ... |
64,317,851 | 64,321,489 | Yocto recipe for an application that uses opencv and cpp | I created a recipe for a cpp application using opencv to stream an image. But The build fails with following error :
Log data follows:
| DEBUG: Executing shell function do_compile
| shot.cpp:1:10: fatal error: core.hpp: No such file or directory
| 1 | #include "core.hpp"
| | ^~~~~~~~~~
| compilation ... | I think you need some modifications on your recipe:
[...]
inherit pkgconfig
DEPENDS = "opencv"
[...]
And you will need to add a RDEPENDS and FILES variable:
[...]
DEPENDS = "opencv"
# Add the runtime dependencies
RDEPENDS_${PN} = "libopencv-core libopencv-imgproc libopencv-highgui libopencv-videoio libopencv-imgcodecs... |
64,318,146 | 64,318,811 | How can I simplify my long if else statement | I hope someone could help me to simplify this expression. As shown below there are 2 values that will be checked. Acoording to both of these values, I have to update an image.
I tried some stuff but everything leads back to this long if else statement
I am not sure whether this has been asked before since I am not sure... | Here's one approach:
std::string direction = val ? val < 0 ? "left" : "right" : "center";
std::string orientation = secondVal ? secondVal < 0 ? "back" : "front" : "center";
setIcon(direction + "_" + orientation + ".png");
|
64,318,535 | 64,319,369 | is there something similar to target_include_files in cmake | Is there any way to add files in the same manner as target include directories but for individual files?
My use case is this. I'm using a lot of templates and concepts and my header files are getting bulky. I really liked having implementation split from definitions so want something like so:
.h file
template <typename... | TLDR: for user to use a template, user has to see it all.
is there something similar to target_include_files in cmake
No, there is not.
Is there any way to add files in the same manner as target include directories but for individual files?
The only way is:
create an empty directory (somewhere within CMAKE_CURRENT... |
64,318,759 | 64,318,871 | Memory leak when declaring string | I'm working on a C++ console application that is required to have 0 memory leaks. However, I'm very new to memory leaks and I wonder why this is already causing a memory leak, while there is barely any code:
int main()
{
std::string httpResult;
_CrtDumpMemoryLeaks();
return 0;
}
This is the given memor... | Consider this:
int main()
{
std::string httpResult;
_CrtDumpMemoryLeaks();
std::abort();
return 0;
}
This code has a memory leak, because on calling abort destructors of objects with automatic storage duration are not called. _CrtDumpMemoryLeaks(); cannot look ahead to know if resources will be cle... |
64,318,989 | 64,319,040 | How to delete class object in C++? | I have a class called City the objects of which depend on 3 variables: string name, int area, int population and a constructor for this.
I have a destructor which looks like this City::~City() {}
In main.cpp I'm creating an object like this: City city1 = City("New York", 123, 100000)
After that I want to delete the obj... | If you declare a City object like this:
{
City city1 = City("New York", 123, 100000);
// ...
then the correct code to delete this object is:
}
Since c++ has deterministic destruction of objects with automatic storage duration (as is the case for city1), it will be correctly cleaned up as soon it goes out of scope... |
64,319,147 | 64,320,688 | C++ ifstream nested loops | I am working on a numerology project where i have to input a name and add values assigned to each letter of the name. I have already got it working for a single word using a loop to run through the characters.
I now want to read through a list and get an output with the name_value..
code without the while loop or ifstr... | You have not mentioned the path correctly with the required file option. If you not give file option then as well it works.
I have tried same code with fully qualified path and its running with below change:
ifstream input_file("C:\\Users\\Debug\\names.txt", ios::in);
I got the below output:
15
11
8
|
64,319,785 | 64,338,038 | X11 - XCB: Window information not up-to-date? | I'm using XCB to create my x11 window and, somewhere in the code, I want to move it.
I make a little test to print the window position (0, 0), then move it, and print the position again (200, 100).
Saddly, I have always x:10 and y:10.
Here the code:
// g++ -o test test_xcb.cpp -lX11 -lxcb
#include <xcb/xcb.h>
#include ... | The short version: You are ignoring the interaction with the window manager.
The long version:
First, the position that GetGeometry gives you is relative to the parent window. With a reparenting window manager, the WM will add a frame window around your window to draw window decorations to (titlebar, close button, ...)... |
64,319,931 | 64,341,148 | Auto connection of vs code c++ debugger on process startup | I'm really interested in godot as game engine and the possibilities to use c++ to develop in it. I've stopped on gdnative approach, because it faster and easier (and also gives me a possibility to work with CMake instead of SCons). I've already arranged small project based on gdnative_cpp_example with the only differen... | If you came here for the automatic debugger start, then maybe tenfour's comment on the question could help you, but because main reason for this question was little bit different (find the way to debug godot projects with both c++ and gdscript at the same time), I've found different solution, so if someone came here fo... |
64,320,046 | 64,321,039 | Issue when trying to stock a socket into a structure | I'm trying to store a socket into a structure. I thought this would be straight-forward but the fact that socket don't have constructor (as I understood) make this thing very tricky for me.
Here's what I tried:
struct participants_name {
participants_name(tcp::socket);
chat_participant_ptr _participant;... | The error is caused here
this->participants[chat_participant] = participants_name(std::move(socket_));
not because the participants_name object on the right side of the assignment couldn't be constructed, but because the new entry in the map
std::map<chat_participant_ptr, participants_name> &participants;
can't be ... |
64,320,533 | 64,320,682 | The elements in an array seems to be changing, array's first half sorted and second half is randomized | This program is designed to give out randomized numbers depending on how many the user inputs as the size of array. The rand() is working and gives outputs elements depending on the user.
The problem is when it comes to the part where it is getting sorted the elements of the array seems to be changing from a different ... | int setArray[] = { NULL }; creates an array with one element. If you try accessing anything but setArray[0] you have undefined behavior, which is what you see.
Since the number of elements aren't known at compile-time, use a std::vector<int> instead.
#include <vector>
// ...
std::vector<int> setArray;
Then, when the... |
64,320,707 | 64,320,879 | C++ Allocate a dynamic 2d array in function | gals and everything in between, first off, I want to say sorry for noob/duplicate question.
TL;DR I want to allocate memory for a 2d array of chars, however I can only do so when the program calls alloc(). Any help is appreciated.
Since you guys love code, here is what I have:
#include <iostream>
using namespace std;
... | *(add)[i] does not look quite right, it indexes the add variable and dereferences the pointer afterwards. Those parentheses have no effect.
Try the opposite order, i.e. (*add)[i]
|
64,320,748 | 64,320,894 | Compile error initializing struct member with enum class | Following program giving compilation error as following
// Example program
#include <iostream>
#include <string>
enum class Animation: int{
Hide=0,
Show,
Flicker
};
struct Icon {
int id;
char name[10];
Animation currentAnim;
Animation nextAnim;
int isActive;
};
static struct Icon IconList[]= {
... | The braces around the nested initializer lists may be omitted in aggregate initialization,
The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent ... |
64,321,024 | 64,321,394 | Displaying 3D points in OpenGL by reading in textfile | I am trying to plot 3D points by reading in a series of coordinates contained in a text file but I don't seem to get any output.
I personally think that either I am doing something wrong while reading my text file or in void reshape
Here is my code so far:
#include <glut.h>
#include <iostream>
#include <fstream>
#incl... | Your points are clipped by the near an far plane of the Viewing frustum of the perspective projection. Alle the geometry which is not in between the near and far plane is clipped:
Increase the distance between the near and far plane (gluPerspective) and change the look at (gluLookAt) the scene:
glMatrixMode(GL_PROJECT... |
64,321,965 | 64,347,695 | Using GTest/GMock Matcher in EXPECT_EQ | I know that matchers are used for EXPECT_CALL, but sometimes I wish I could use matcher to check that 2 objects are the same with EXPECT_EQ (e.g. FloatNear instead of EXPECT_FLOAT_EQ).
Can this be done or not?
| Yes, you can use matchers with EXPECT/ASSERT_THAT, see:
EXPECT_THAT(42.f, ::testing::FloatNear(41.5f, 0.5f));
|
64,322,035 | 64,322,100 | push object to vector after passing through conversion function | I desire to insert a conversion function (probably a std::function) to modify an object that is being pushed onto a std::vector. I would like the object to construct in-place, and pass through the function without additional copies being constructed.
Let's say I'm doing this:
std::vector<foo> foo_array;
foo_array.pus... | The syntax needed here is:
std::function<foo&&(foo&&)> convert{[](foo&& f) -> foo&& { return std::move(f); } };
Or, fully generic lambda fn:
auto fn = [](auto&& f) -> decltype(auto) { return std::forward<decltype(f)>(f); };
std::function<foo&&(foo&&)> convert{fn};
If this code is on a hot path, you may like to avoid ... |
64,322,088 | 64,324,070 | c++ Windows 10 Get an Ip for a connected client | I have set up a working WinSock2 Socket were a client can connect, how can I get the IP address of a connected client.
| The client's IP address is reported by accept() when the client is first accepted. It can also be queried from the client SOCKET at any time using getpeername(). Both functions fill in a sockaddr_... struct that you must allocate and pass in, based on the address type assigned when you created the server socket using... |
64,322,107 | 64,322,264 | Are there exceptions to the command line arguments passed to the main function? | I am playing with command line arguments and implementing a very basic calculator which takes input before execution rather than at runtime. It works for 4 operations, but I am stuck at the power operation and after hours identified the fault. Here is the C++ code:
#include <iostream>
#include <sstream>
#include <cmath... | In windows shell (Batch script), a caret (^) is an escape character (see more here: What does symbol ^ mean in Batch script?). So if you want it to be seen as a normal character by the shell, you need to escape it...with itself!
So you'd run:
calc.exe 3 ^^ 3
You can test this by using echo in the shell. You can run ec... |
64,322,949 | 64,323,006 | Printing out end sum after executing for loop | This is a simple for loop i just want to declare a variable storing the final value of sum which can be used outside the for loop.Just printing cout<<sum;(outside for loop) gives an error that variable sum was not declared in this scope.
for (int score=1,sum=0;score<6;score++){
int required;
... | int sum = 0;
for (int score=1;score<6;score++){
int required;
cin >> required;
sum+=required;
}
cout << sum << endl;
|
64,323,037 | 64,323,241 | Makefile Mark Dependency, Compile and Link | I have a modular implementation of barriers done in openmp. I have a test harness that I would want to link. The directory looks like so:
Project/
-Tests
-openmp_tournament
-test_openmp_tournament.cpp
-OpenMP
-tournament.cpp . //barrier implementation
-tournament.h
Now both .cpp files have... | Why can't the compiler find your header file? Well, we should always start from the assumption that the compiler is right, and you're doing something wrong :). So, take a look at the compile line that works:
g++ -c -MMD -MP -Wall -Wextra -I../../OpenMP/ -fopenmp ...
then the one that fails:
g++ -MMD -MP -c ...
... |
64,323,217 | 64,323,257 | Min/max values of a templated type | I have a rather basic question. Suppose I have a templated function:
bool is_max(std::uint32_t val) {
return (val == std::numeric_limits<uint32_t>::max());
}
However, to make my function flexible, I'd like to use templates:
template <typename T>
bool is_max(T val) {
return (val == ???);
}
The std::numeric_limits ... | The way to handle this is to continue using std::numeric_limits, and add template specializations for all of the desired input types.
Quoting cppreference:
Implementations may provide specializations of std::numeric_limits for implementation-specific types: e.g. GCC provides std::numeric_limits<__int128>. Non-standard... |
64,323,378 | 64,323,420 | Already defined in .obj even when using extern and #ifdef | I have three files like this:
head.h
#ifndef HEAD_
#define HEAD_
extern int f();
#endif
mycpp.cpp
#include "head.h"
int f() {
return 5;
}
myMain.cpp
#include <iostream>
#include "head.h"
#include "mycpp.cpp"
int main()
{
std::cout << f() << std::endl;
system("Pause");
return 0;
}
Running this cod... | The general rule is: never #include a .cpp file. Only header files should be included.
Besides that, extern in a function declaration is redundant here. On a variable declaration, extern marks the statement as a declaration rather than a definition. But on function declarations this isn’t necessary, and the function ha... |
64,323,799 | 64,323,880 | Comparing std::variant type instances | Here is my code:
struct A{};
struct B{};
typedef std::variant<A, B> Record;
Record Get() {
return Record {A()};
}
void Test() {
if (Get() == Record{A()}) {
}
}
I get an error:
In instantiation of function template specialization 'std::__1::operator==<A, B>' no matching function for call to object of ty... | You need to provide equality operators for every type the std::variant can hold.
bool operator == (A const &lhs, A const &rhs) {
return true;
}
bool operator == (B const &lhs, B const &rhs) {
return true;
}
Full example: https://gcc.godbolt.org/z/rjTfqE
|
64,324,233 | 64,344,546 | Posting multiple forms in ncurses: only last form is initially visible | I have a few sets of forms within my ncurses program. Each field has A_UNDERLINE enabled but I noticed that only the last form posted will show underlines until I navigate to it; the others are simply blank space.
I would like to ensure all the fields appear with underlines as soon as I refresh my pad.
Eventually, I in... | I was able to accomplish my goal of all fields being underlined by adding the following code immediately under post_form(form_two);
set_field_back(field[0], 0);
set_field_back(field[1], 0);
set_field_back(field[0], A_UNDERLINE);
set_field_back(field[1], A_UNDERLINE);
|
64,324,883 | 64,330,885 | Calculating sum of array with nonblocking operations | Every process need to calculate its partial sums and send them to 0 process, then to count sum of array
I wrote this code
double* a;
a = new double[N];
for (int i = 0; i < N; i++)
a[i] = 1.0;
int k = (N - 1) / proc_count + 1;
int ibeg = proc_this * k;
int iend = (proc_this + 1) * k - 1;
... | In short, you need to set all elements of reqs to MPI_REQUEST_NULL right after allocating it.
The longer answer is that MPI programs run as multiple instances of one or more source programs and each instance (rank) has its own set of variables that aren't shared. When you have:
if (proc_this != 0)
MPI_Isend... |
64,325,236 | 64,325,369 | Storing user information in an array | I'm currently working on an ATM program, the program prompts a user to enter their username and password so they can access their account. I've been asked to use an array to store this information, but I'm having trouble understanding exactly how to go about it. Here's what my professor has written:
In main initialize ... | Create an Account class to hold all information for one account in a single place:
class Account {
public:
std::size_t m_num;
std::string m_pin;
std::size_t m_balance; // alternative use double here
};
Then declare and initialize the array, an object of type Account[3], with braced initialization (C++11):... |
64,325,408 | 64,325,967 | The code does not assign value to an inherited function parameter and do not call function | The code does not reduce the default health value, just prints default value out. It does not call GetName() and GetHealth() functions that are inside the TakeDamage() function. The code can run without problem. Screen out put is below the code. Where is the problem here? How do I fix?
#include<iostream>
using namespac... | if (Total <= 0.f)
{
cout << GetName() << " has died" << endl;
}
else
{
Health -= Damage;
}
You don't change the health when Total is less or equal 0, which is the case when you call TakeDamage(100)
|
64,325,481 | 64,325,862 | Casting away constness - array and pointer types ambiguity in the standard | Below you can see three different variants of reinterpret_cast, which doesn't have the ability to cast away constness. The definition of "casting away constness" is in this section of the standard, and it specifically details pointer types, not array types. According to the standards, for multilevel pointers we keep ch... | Thanks to Language Lawyer for pointing this out, but because the C++17 draft states that if two types are similar they can be explicitly casted between using const_cast. A similar type is one where every level of the multilevel pointer/array type is the same, i.e. at i-th level we have one of the four:
“pointer to”, “... |
64,325,500 | 64,325,580 | C++ class has no member | I checked the suggested answer with a similar problem, added a default constructur but the problem remains:
Auto.h:
#include <string>
class Auto {
unsigned int ps;
std::string type;
public:
Auto();
void setPS(unsigned int ps);
void setType(std::string type);
};
and Auto.cpp:
#include <string>
#in... | It is not the default constructor, but you have a class declaration in your cpp file.
Auto.h
#include <string>
class Auto
{
unsigned int ps;
std::string type;
public:
void setPS(unsigned int ps);
void setType(std::string type);
};
Auto.cpp
#include "Auto.h"
void Auto::setType(std::string type)
{
... |
64,325,521 | 64,392,497 | FIX NewOrderSingle recieves Internal application error, contact support | Im developing a bot in c++ using QuickFix, using Remarkets to test my app but when I send a newOrderSingle y get "Internal application error, contact support."
I assume the application is myself, but i also tried to contact Remarkets without any answer.
The messages go like this:
Logon:
8=FIXT.1.1 9=124 35=A 34=1 49=us... | Got it right! I have yet to understand the deatils, when I become an expert in fix protocol y promisse I will come and explain, but for the moment i can give you the message that allowed me to buy Option futures.
8=FIXT.1.1 //Dictionary
9=220 //Body Length
35=D //... |
64,325,540 | 64,325,565 | Why is this character put into the vector as an integer? | I'm trying to put a character on the stack, but it is putting the ASCII integer value of the character. What is causing this and how can I get an actual character onto the stack?
Here is some simple code to show what I mean:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::stri... | std::to_string doesn't have a conversion from char, but it does have a conversion from int. So c will implicitly be converted to an int with the corresponding ASCII value, and this is converted to a std::string.
If you want to push_back the character c as a std::string, you can do:
v.push_back({c});
Here's a demo.
|
64,326,448 | 64,326,485 | How to use any variable in other member functions in c++ | class screen
{
public: screen(vector<int>v)
{
vector<vector<int>>seats(v[0]+1,vector<int>(v[1]+1,1));
// done some operations on v
}
bool check_seat(vector<int>v)
{
int row=v[0];
// I want to use seats vector in this function too. How to do that??
for(int i=1;i<v.s... | Currently, seats is a local variable in the constructor. You need to make it a class member instead:
class screen
{
public:
screen(const vector<int>& v)
: seats(v[0]+1, vector<int>(v[1]+1, 1))
{
}
// etc...
private:
vector<vector<int>> seats;
};
Note that I also changed your constructor ... |
64,326,871 | 64,327,231 | What happens to the reference of an object managed by a unique pointer that has been moved? | If I crate an object that is managed by a unique pointer such as:
auto pObjectA = std::make_unique<A>();
But I need this object as a parameter of another object:
auto pObjectB = std::make_unique<B>(*objectA);
If objectA is later moved with std::move, will the reference passed to objectB still be valid?
Edit:
class A
... | Yes, the reference passed to objectB will still be valid since std::make_unique<B>(*objectA) will copy the object referenced by unique pointer objectA and use the copy object as its property instead of storing the original object. Therefore, if objectA is moved using the function std::move, objectB's A object won't be ... |
64,326,993 | 64,359,825 | HDF5 (using C++ API): Writing individual fields of Attribute compound data erasing other fields | While writing individual fields of Compound data type of an Attribute results other fields data got erased. Is there any way we can write individual fields at a time to an attribute compound data?
Note 1: Writing data for individual fields of a compound data type works for Dataset
Note 2: I know writing all data fields... | I got the response from HDF5 forum. Writing parts of attribute values not allowed.
Only for reference: https://forum.hdfgroup.org/t/writing-individual-fields-of-compound-data-of-an-attribute-erasing-remaining-fields/7612
|
64,327,008 | 64,327,215 | force a strongly typed enum to participate in template overload resolution | As per this question - template argument deduction with strongly-typed enumerations - it seems challenging - if not impossible - to get strongly typed enumerators to participate in overload resolution.
if we have the following
#include <string>
#include <iostream>
void ExternalFunction(const std::string& tag, int valu... | You have written your code incorrectly.
OK, so EnumWrapper<>::DoSomething overrides VariableWrapper<T>::DoSomething. So it won't be called by directly calling DoSomething on any EnumWrapper object.
But that doesn't mean VariableWrapper<T>::DoSomething doesn't exist. It does exist, and you can still call it by a qualifi... |
64,327,140 | 64,327,198 | C++ undefine macros not working as expected | I have two programs to test the working of #undef, but it is not working as expected.
test1.cpp
#include<iostream>
#define AB 1
void display(){
#ifdef AB
std::cout<<"yes"<<std::endl;
#endif
}
int main(){
display();
#undef AB
display();
}
output: yes yes
test2.cpp
#include<iostream>
#define AB 1
int main(){
#ifde... | The two programs are not the same!
Preprocessor macros are parsed and replaced during the preprocessing stage, before the compiling stage even sees the source code. The preprocessor is a single-pass operation, top to bottom. #define and #undef are processed in the order they are seen, and can alter the source code th... |
64,327,678 | 64,328,056 | Application and meaning of end iterator decrement | int get(int key) {
if (m.count(key) == 0) return -1;
freq[m[key].second].erase(iter[key]);
freq[m[key].second].push_back(key);
iter[key] = --freq[m[key].second].end();
if (freq[minFreq].size() == 0) ++minFreq;
return m[key].first;
}
private:
int cap,... | list<int> li;
li.push_back(1);
li.push_back(2);
li.push_back(3);
li.begin() - pointer to ist element(as reference li[0]).
li.end() - pointer to null (element just after last element li[2]).
--li.end() - pointer to last element(li[2]). //your question
li.rend() - pointer to element just before the first element (before... |
64,327,681 | 64,328,423 | How to use templates for multiple data types (string, int, float)? | I am having a bit of trouble figuring out how to use templates for a C++ function that can accept three data types: int, float, and string. I need to be able to perform calculations on the input as if it were an integer as well. Can someone provide an example of this using these data types?
I was hoping for code that w... | Putting the specialised functions inside the class doesn't work because you get this error
error: explicit specialization in non-namespace scope ‘class Prime’
So this won't work:
#include <string>
#include <iostream>
class Prime
{
public:
template<class T1>
char calculate(T1 i)
{
std::cout << "ca... |
64,327,915 | 64,328,093 | Issue with C++, getting error quoting invalid pointer | I'm totally confused with my problem. This code works with CentOS 6, however when i'm using it with CentOS 8 with GCC 8.3.1 I get the error:- free(): invalid pointer
With the code I have, it doesn't make sense, because i'm not using the free command or delete.
When I try to debug it using valgrind or build it with a... | The program has at least one mistake:
unsigned char plaintext[sizeof(theString.c_str())];
strcpy((char*)plaintext,theString.c_str());
This does not create an array sized to sizeof(theString.c_str())) characters. That sizeof line is equivalent to:
unsigned char plaintext[sizeof(const char *)], which is more than likel... |
64,328,038 | 64,329,347 | Take the color avarage of each column of a picture using OpenCV with C++ on Visual Studio 2019 | I'm new using C++ and a need to compute the average of the red color in each column. Subsequently, I need to make a graph of the color density level per column.
This is the picture that i using, is a sample of a bone densitomery:
This is my code so far:
#include <opencv2/opencv.hpp>
#include <string>
#include <vector>... | You are trying to check row by row not column by column also the third for loop is not needed.
Here is the solution for each channel(red,green,blue) columns average and graph of the column averages for each channel.
Source:
Red Channel Graph for each column average:
Green Channel Graph for each column average:
Blue ... |
64,328,248 | 64,328,476 | std::strftime crashes with incorrect input | This is how i am using the function to extract date and time.
std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
but if the format text is not formatted properly the application crashes like
std::strftime(&stdstrSystemTime[0], stdstrSystemTime.size(), "%Y-%m-%d %:%... | It seems, that you are taking format string from outwhere, maybe from user input.
So as you cannot make your strftime not crash, you have to validate format string before you call strftime.
For example, you can:
Use regular expressions to find all sequences like
"%[^aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%]" (format let... |
64,328,347 | 64,328,528 | I would like to call an object in an object to other class in c++ | class Player {
public:
// something
double getVelPlayer();
private:
// something
sf::Sprite mPlayer;
};
class Game {
public:
// something
private:
void processEvents();
void update();
void render();
// something
};
void Game::update() {
sf::Vector2f movement(0.f, 0.f);
if(m... | Your Game class doesn't have a member variable called player and the Player you allocate in main isn't accessible from within a Game object.
Consider moving the Player into the Game class - and there's no need to use new:
class Game {
public:
// something
private:
void processEvents();
void update();
vo... |
64,328,509 | 64,328,628 | Clarification regarding the definition of a literal in C++ | I believe I have been given some confusing information, so I am looking for a clarification.
When talking about literals (literal constants), is every value that is typed into the source code directly by the programmer considered to be a literal?
e.g.
int x{5}; // Would the value of 5 in the initialized variable x be c... | There's lots of literals:
integer literals like 10, 012, 0xA
floating-point literals like 10.0, 10.0f
boolean literals like true, false
character literals like 't', 'e', 'n'
string literals like "ten"
null pointer literal like nullptr
user-defined literals like "10"h.
|
64,328,538 | 64,331,924 | Can we solve covering segments by points problem by sorting left start point | I have seen a lot of articles and solutions about this problem always sorted by the right endpoint
I try to solve it by sorting the left start point and I don't understand why it doesn't work in some cases,this is my code:
struct Segment {
int start, end;
};
bool comp (struct Segment s1 , struct Segment s2)
{
int... | Because some segment might start and end before segments[o] end, and you just miss it.
Segment array {(1:10), (2:3), (4:5), (6:7)} is sorted by the left end.
For i=0 you assign o=0 and compare 2,4,6 with 10 until i reaches 4.
Now you push 6 into points. But what about covering (2:3) and (4:5)?
|
64,328,801 | 64,329,145 | C++ Writing to a CSV file | The purpose of the code is to prompt the user to enter how many connections/nets & write to a CSV file.
The code runs and writes to the CSV file on the first column but after the user is prompted
to input the # of nets again, it writes on the same column instead of the next one which has the header
"Connector 2" or Col... | The problem you have is that you want to write the data column by column while the CSV format reads them row by row. One way to make your program work is to store the data until the user is done, and then store it row by row. Ex :
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespa... |
64,328,879 | 64,329,232 | What is the mistake in my code for the problem "Find Median from Data Stream"? | I'm been struggling to solve the question Find Median from Data Stream on LeetCode for the last 2 hours but couldn't find the mistake in my code.
My algorithm is to put two priority queues, the first one is a max-priority queue which stores the elements less than the median, and the second one is a min-priority queue w... | As Jerry Jeremiah commented the issue with the code,
in the line, if(x>num)min.push(x); you are completely ignoring the num and pushing x into the queue. You have to change that and your code will get accepted.
|
64,329,114 | 64,329,174 | In C++, what is the use of template parameter when it doesn't appear in the following class or function declaration? | Many times I see these types of codes.
What is the use of template in the code below?
I ask this because the template parameter T does not appear in the declaration.
template <typename T>
struct op_pointer_to_mat;
template <typename T>
struct op_pointer_to_col_vect;
Does it mean that the definition of op_poineter_to_m... | This is called a forward declaration. The class must be declared fully somewhere later. Could be the same file or a different header. It just lets the compiler know that the name Test is valid and the blanks will be filled in later.
template<typename Type>
class Test;
template<typename Type>
class Test
{
public:
T... |
64,329,454 | 64,329,841 | How can I access and erase every 2nd last element from a multiset? | I was lately trying to access every 2nd last element from a multiset container. Here I want to first print every 2nd last element from the container then erase it from the container. This process continues until the size of the container reaches to 1.
My so far approach for this process is given bellow-
int n;cin>>n;
m... | Find the answer of the question .Here as I am using multiset I accidently erasing all copies of (*it).So I just need to find the value first then erase from the set.
st.erase(find(*it))
|
64,329,757 | 64,329,915 | Is there a way to dynamically change the return-type of a function in C++ based on function parameter values? | I am working on a problem that requires me to return different return-types based on my function parameter values that I provide.
I want to do something like this --
In the code below, doSomething() is an already existing function (used by a lot of clients) which takes mode as a function parameter, and returns std::lis... | This cannot be done.
You can only have one function with a given signature. If you have calling code that already expects this to return a std::list<ReturnType>, that's it; you're done.
If you could guarantee that all existing calling code looks like
auto l = obj.doSomething(1);
then you could potentially change the ... |
64,329,877 | 64,330,043 | C++: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) | I tested with lists in C++ and created a simpliest class for it. I removed some checks and other methods to show only the important points.
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.00)
PROJECT(test)
SET(CMAKE_CXX_STANDARD 98)
ADD_EXECUTABLE(test main.cpp CList.h)
CList.h
#ifndef CLIST_H
#define CLIST_H
#incl... | Your code creates a stack overflow because it recursively deletes the next node from the destructor of the previous one. When you have a million elements this results in a million recursions. Stack size is limited to around 1-8MB on most platforms which even if each function call only used 8 bytes of stack (generally i... |
64,330,071 | 64,330,444 | Avoid manual creation of lambda to wrap the call to new[]: to be used as a generator function in std::generate | Short Version
Currently, I manually create a lambda function for the new [], as follows:
[](){ return new double[3]; }
This lambda is later used as a generator function in the call to std::generate:
std::generate(vec.begin(), vec.end(), [](){ return new double[3]; });
Can I avoid the creation of this lambda and use s... | The following:
#include <type_traits>
#include <vector>
#include <algorithm>
#include <memory>
template<typename T>
struct default_new {
typename std::decay<T>::type operator() (){ return new T; }
};
int main() {
size_t numElems = 10;
std::vector<double*> vec(numElems);
std::generate(vec.begin(), vec.... |
64,330,095 | 64,330,180 | Why this ref-qualified user defined convertion is called? | within following small code:
class A {
};
class B {
public:
operator A() const & {
return A{};
}
};
void foo(const A& a) {
}
int main()
{
B b;
A a1 = b;
A a2 = B{}; //<--- here
foo(b);
foo(B{}); //<--- here
}
Why the specified lines will not create compile error? My cast... | Because rvalues could be bound to lvalue-reference to const too. (They can't be bound to lvalue-reference to non-const.)
As the workaround, depending on your intent, you can remove the const qualifier as you said, or add overloading with rvalue-reference qualifier (and const qualifier if necessary as @HolyBlackCat sugg... |
64,330,132 | 64,330,614 | How to apply an icon to your file in visual studio? {Console C++ Application} | I have tried to apply an icon to my exe, but I don't know how to?
I am new to stack overflow and this is my first question.
| 1.Open the project and add .rc file
2.Right click Resource.rc->Add Resource->Icon->Improt in Recourse View. Then, import the icon that you want. The picture must be .ico format.
Then, you could find that the icon has been added.
Besides, if you have many pictures, you could open resource.h and change the value of ... |
64,330,497 | 64,345,899 | Building and running unit tests with Visual Studio build tools | I am adding unit tests to an existing C++ Visual Studio projects, using the Google Test adapter.
It's all running fine on my computer with Visual Studio 2019, but when I try to run them on the build server I get the following error
error : This project references NuGet package(s) that are missing on this computer. Use... | The problem is that your c++ project has missed the content of googletest nuget package. So the solution is to restore the whole nuget package in your c++ project.
Update 1
First of all, take a brand new backed up project and restore it to when the problem started.
Besides, msbuild -t:restore command applies to project... |
64,330,587 | 64,837,335 | Cannot convert OpenCV Mat to dlib arrray2D | I am using the following code to convert an cv::Mat into dlib array2D (which is required to track objects through dlib correlation tracker)
int main()
{
cv::Mat img = cv::imread("wine_plant.jpg");
dlib::cv_image<dlib::bgr_pixel> dlib_img(img);
return 0;
}
But while debugging I get the following error message.
Erro... | Your dlib version 19.7 seems too old. I also faced similar error on dlib 19.19 downloading from its website. It was fixed on github, but http://dlib.net/ did not contain the fixes when I used it. For me compiling from source solved it. Newer dlib version should fix this error.
These issues discuss this problem,
https:/... |
64,330,607 | 64,333,973 | Is volatile needed only once or on each derived pointers from a MMIO mmap'd address pointer? | I have a global base pointer to a memory space void *pAddr. In some methods, I cast that pointer to few structures to have a better way to access the memory.
class MyClass {
private:
struct MapMem {
uint8_t dummy1;
uint64_t dummy12;
};
void* pAddr;
MapMem* representationPointer;
void... | Since your mmapped address points to MMIO, it should be stored in a pointer-to-volatile variable. I.e.,
volatile void* pAddr;
Then, when you need to interpret this address as a pointer to MapMem, you should do the appropriate cast. If you try doing static_cast<MapMem*>(pAddr), you'll get compilation error: e.g. GCC wi... |
64,330,739 | 64,332,887 | How does C++ compiler implement the reverse call order of destructors in inheritance? | For example, we know that the following code will execute as detailed:
#include <iostream>
class Base {
public:
virtual ~Base() {
std::cout << "Destroying base" << std::endl;
}
};
class Derived: public Base {
public:
~Derived() {
std::cout << "Destroying derived" << std::endl;
}
};
int main()
{
Bas... | From the C++ perspective, constructors and destructors are special functions. They don't have return types, for instance.
The typical C++ compiler is likely to use still generate a fairly normal function, at least from its perspective. This keeps the linker simpler. But the function may contain a bit more than just you... |
64,330,743 | 64,331,121 | Does the c++ apps build for android run on top of JVM of on the Kernal | In android does the application built with c++ (and packages in apps Like Termux) run on top of the Dalvik JVM or directly communicate with the Linux Kernal
| This is explained partly in the Concepts section of the Android NDK documentation.
In brief: every Android user application needs to run the Android event loop in some capacity to receive events, participate in the application lifecycle, and display stuff on the screen.
What people call "native" c++ applications are ac... |
64,330,902 | 64,331,153 | Move object into unique_ptr | I have code similar to this:
#include <iostream>
#include <memory>
#include <optional>
class D {
D(int i) : i(i), private_member('p') {}
char private_member;
public:
D(const D&) = delete;
D &operator=(const D&) = delete;
D(D &&) = default;
D &operator=(D &&) = default;
static s... | Use std::make_unique, so something like this:
// non-const
auto d1 = D::try_create(10);
// accounting for empty option
auto d1ptr = d1 ? std::make_unique(std::move(*d1)) : std::unique_ptr<D>();
The resulting unique_ptr will either own a D or it won't depending on the std::optional. You have to make d1 non-const becau... |
64,330,932 | 64,331,318 | weird bug where if-else statment doesnt work properly | I have a really weird bug in my program. Im working with linked list in this program. The ead->next does show up as nullptr but the if statement is skipped. The weird part is that it doesn't go to the else statement after that. I got this info from stepping through the debugger. I marked the part of the function that h... | I just realized I did == instead of = in:
if (ead->next == nullptr) {// this is suppose to be true but it skips
ead == nullptr;
head == nullptr;
}
should be:
if (ead->next == nullptr) {// this is suppose to be true but it skips
ead = nullptr;
head = nullptr;
... |
64,331,299 | 64,331,697 | Is this defining a lambda function and assigning the function pointer to a value at the same time? | Still many C++ codes are so difficult for me to understand..
Below is a code snippet from dlib (http://dlib.net file : dlib/external/pybind11/include/pybind11/pybind11.h)
It's a member function definition of class cpp_function and I didn't try to understand the code(no time to do that..that's sad..). I can't understa... | rec->impl = [](function_call &call) -> handle
creates a lambda which takes one argument of type function_call and returns a handle, then assigns it to rec->impl.
As lambdas are basically unnamed structs, they also have unnamed types. Since rec->impl obviously exists already and is thus not templatized on the lambda typ... |
64,331,419 | 64,335,967 | Why not destory after calling std::move? | As seen in the following, I can still print "3" after the code printf("%d\n", p1.val);. Isn't the class p1 destroyed after std::move? code
The code is here:
class pointer
{
public:
int val;
int* my_pointer;
pointer()
{
val = 0;
my_pointer = new int;
}
pointer(pointer&& other)
... | So move semantics is basically doing a shallow copy from an element that is about to die (go out of scope).
Say that we have object, dying_obj, that we know is about to go out of scope (and hence have its destructor called), we can change its type to an rvalue with std::move like so:
other_obj = std::move(dying_obj);
... |
64,331,927 | 64,334,508 | C++/Tcl Can I retrieve Tcl file line number when a function recorded by Tcl_CreateCommand is invoked | I run a Tcl script from a C++ program using Tcl_EvalFile. I defined some custom commands (using Tcl_CreateCommand), so when they are found in the file a callback is called and then I can run some C++ code (TclInvokeStringCommand invokes the callback given to Tcl_CreateCommand, the callback type is int (*executeCmd)( Cl... | The information is only exposed at the Tcl level via the info frame command. (The internal C API for it is sufficiently horrible that it's never been made public.) This means you need to do something like this with Tcl_Eval():
// These can be cached safely per thread; reference management is a thing for another questio... |
64,332,371 | 64,332,469 | How can i insert multiple different values in single position of list in c++? | This code is from
geeksforgeeks
list<int> list1;
list1.assign(3, 2);
list<int>::iterator it = list1.begin();
advance(it, 2);
list1.insert(it, 5);
cout << "The list after inserting"
<< " 1 element using insert() is : ";
for (list<int>::iterator i = list1.begin();
i != list1.end();
i++)... | Check the reference.
You can use one of insert():
template< class InputIt >
void insert( iterator pos, InputIt first, InputIt last); (until C++11)
template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last ); (since C++11)
Example:
#include <iostream>
#include <vector>
#incl... |
64,332,731 | 64,335,891 | type casting boost multiprecision integer returns wrong answer | The issue I am facing is with boost multiprecision cpp_int type casting to a small integer type int16_t.
Typecasting unsigned integer value of 43690 to int16_t is supposed to return -21846, however what I am getting is 32767. Am I missing anything here?
Here is the sample snippet of code to reproduce the behavior
#incl... | Let's consider this line first:
int16_t d = static_cast<int16_t>(c);
This follows the conv.integral#3 clause of the C++ Standard about integer conversions between builtin types:
Otherwise [i.e. the destination type is not bool], the result is the unique value of the destination type that is congruent to the source i... |
64,332,990 | 64,333,711 | std::transform over QMap | I have to transform a QMap<QString, int>. I tried to use std::transform as it works for QList, but it's failed to compile.
#include <QCoreApplication>
#include <algorithm>
#include <QMap>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QMap<QString, int> map;
map["one"] = 1;
map["three"] = ... | A major problem is std::back_inserter(map2) wants to call push_back, which is not a member of QMap (nor std::map).
You also have the issue that the standard inserters want a value_type defined in the container, that QMap doesn't have. In older versions, QMap::value_type was used for a different meaning to std::map::val... |
64,333,453 | 64,334,520 | How can I isolate the compiled logic of a C++ program from the rest of the file header data? | I want to observe the difference in op code binary output of compilation between two versions of a very basic C++ program. For example, 2 + 2 = ?, with no libraries called. I expected the compiled output to be a tiny file of binary op codes with a few small headers, being new to compiled programs, but there are large h... | Seeing ld(1): GNU linker - Linux man page, you will find that you can use --oformat=output-format option to specify output format.
binary is a format that don't have headers.
Then, seeing gcc(1): GNU project C/C++ compiler - Linux man page, you will find that you can use -Wl option to pass options to the linker.
-nostd... |
64,333,949 | 64,333,998 | Accessing Base class protected data member vector in derived class give error 139 | It may have been answered somewhere, but I could not find the correct words to search.
I have base class
class B
{
protected:
std::vector<int> v;
public:
B(): v{} {}
void test()
{
v.push_back( 10 );
std::cout << v[0] << std::endl; // prints 10
}
};... | b and c are different instances and the vector v doesn't have any elements by default. Reading v[0] in this state is reading out-of-range and will cause error.
The B::test() function pushes something to the vector, so calling it will eliminate this error.
int main()
{
B b;
b.test(); // initialized vector 10
... |
64,334,066 | 64,334,315 | Understanding boost::asio::post with single callable - who executes? | I would like to know how I should understand boost::asio::post
In particular this overload that can just take a single callable, who/what/where executes it now (since I don't explicit pass it an io_service/io_context for example) ?
Does it just randomly (more or less) choose a running io_service (if there is one) ? I f... | Eventually, boost::asio::post will use get_associated_executor to look up a specialization of associated_executor. The default implementation will provide a static instance of system_executor, where the object will be invoked.
|
64,334,421 | 64,337,194 | C++/embedded Python: Can I retrieve Python file name and line number when a C++ function is called from Python | I run a Python script from a C++ program using PyRun_SimpleFile. I defined a custom module (using PyImport_AppendInittab, as done here), so it can be imported in my Python script and some C++ code gets executed by the Python script when functions from this module are used, this is done through a callback PyObject* MyFu... | You will need PyTraceBack_Here.
You can take a look at a traceback object's implementation here
Here is an example printig the traceback created by PyTraceBack_Here
#include <Python.h>
PyObject * mymodule_meth_test(PyObject * self) {
PyTraceBack_Here(PyEval_GetFrame());
PyObject * exc;
PyObject * val;
... |
64,334,687 | 64,334,980 | Why floor and ceil value giving different values for an integer in c++ | Below is the program I've written to find the exponent of 6, but I this its giving wrong output or I may be wrong somewhere, I'm unable to figure out here.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll t;
cin>>t;
cout<<log(t)/log(6)<<"\n";
cout<<floor(log(t)/log(6))<<... | The log function - like most floating point calculations - is imprecise. There is often tiny amount of error in the result. In your case, you did not get the exact 3, but some value slightly greater than 3. When you apply ceil or floor to such imprecise result, you may increase or reduce the amount of the error up to a... |
64,335,228 | 64,335,622 | What does `(i & (i + 1)) - 1` mean? (in Fenwick Trees) | While learning about Fenwick Trees, I found this implementation:
Source: https://algorithmist.com/wiki/Fenwick_tree
class Fenwick_Tree_Sum
{
vector<int> tree;
Fenwick_Tree_Sum(const vector<int>& Arg)//Arg is our array on which we are going to work
{
tree.resize(Arg.size());
for(int ... | If the bit pattern of i is like ...0111, the bit pattern of i+1 will be ...1000. Hence, i & (i+1) means i - (2^{number of trailing ones} - 1) and transforming all trailing 1s to zero. For example if i is even, i & (i+1) will be equal to i. On the other hand, -1 means, transforming all trailing zeros to 1 (including all... |
64,335,327 | 64,335,350 | what is the meaning of this syntax of size_t? | I found this line during debugging lzma decompression but I can not understand what is this line meaning???
SizeT inSizeCur = inSize, outSizeCur, dicPos;
I know that inSizeCur is variable of type SizeT which is assigned the value of inSize.
but what are , outSizeCur, dicPos??
| This line is declaring 3 variables having type SizeT. It is equivalent to:
SizeT inSizeCur = inSize;
SizeT outSizeCur;
SizeT dicPos;
|
64,335,548 | 64,335,961 | Can you make a bool return 1 if a variable is of a certain type? | class A {
protected:
int a;
public:
int getA() const
{
return a;
}
};
class B : public A
{
private:
int b;
public:
int getB() const
{
return b;
}
};
class C
{
private:
int c;
A* obj;
public:
C()
{
obj = new A[5];// obj is initialized with some values in the constructor, but i ... | You need at least one virtual function in the base class, otherwise there is no polymorphism. The canonical way is to define a virtual destructor:
class A {
// ...
virtual ~A() = default;
};
To use polymorphism, you can't have value types. You need pointers or references. So instead of A obj, you'd need to us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.