question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
66,029,411 | 66,029,580 | Convert Keypoints to cv::Mat in OpenCV with C++ for TriangulatePoints | I am new in the field of CV and trying to Triangulate Points between three Pictures but for the beginning, I want to Triangulate between two Pictures.
For that, I made these Steps:
Feature detection with AKAZE
Feature matching by NORM_HAMMING
Filter the Matches
Match the filtered descriptors with the KeyPoint Coordina... | pointmatrix1 pointmatrix2 should be 2xN matrices containing floats.
Right now they're 1xN matrices containing cv::Point2f elements;
Try something like this instead:
cv::Mat pointmatrix1(2, keypoints_matched_1.size(), CV_32F);
int column = 0;
for (auto& kp: keypoints_matched_1) {
pointmatrix1.at<floa... |
66,029,597 | 66,030,003 | How to calculate the sum of individual elements from two 2D arrays? | I want to write a function addArrays which will, as parameters, take two 2D arrays of type int and of dimensions 3x4, and it's job is to add individual elements of each index from the given arrays and display it in the console.
In main(), I created two 2D arrays arrA and arrB of appropriate sizes with intitialized memb... | You mention you know how to work with 1D arrays, it's the same for 2D arrays, only with one more dimension.
In a 1D array you use arrA[0] to access the first element of the array, in a 2D array you use arrA[0][0] to access the first element in the first line of the array, arrA[0][1] to access the second element in the ... |
66,029,806 | 66,030,033 | c++) i have error when putting 1D array in 2D array | whats the prob
#include <iostream>
using namespace std;
int main() {
int M; //height
int N; //length
cin >> M;
cin >> N;
int list[M][N], smaller[N];
string smaller_str;
for (int i = 0;i < M; ++i){
getline(cin, smaller_str);
for (int j = 0; j < N; i = i++) {
cin >>... | Unless you want to check for errors, you won't need to use getline in this case. Just read each elements via >> operator.
Also note that Variable-Length Arrays like int list[M][N]; is not in the standard C++. You should use std::vector instead of that.
Another point is the the i = i++ in the inner loop is wrong. It sho... |
66,030,034 | 66,030,140 | Allow to use only a defined set of structures values | I have C++ structure which should contain only a limited of values. For example:
struct Foo {
const int a;
const char* const b;
const bool c;
}
namespace allowed_values {
constexpr Foo first = {1, "asdf", true};
constexpr Foo second = {2, "fdsa", true};
constexpr Foo third = {3, "brrrr", false};
}
Is there some... | You can make the constructor private, so no other objects can be created. The objects you want to create must then be created by a friend or the class itself:
struct Foo {
const int a;
const char* const b;
const bool c;
private:
Foo(int a,const char* const b,bool c) : a(a),b(b),c(c) {}
public:
static Foo ... |
66,030,073 | 66,082,549 | Is it necessary to annotate the template specializations of an exported entity with export? | … or is it enough to declare them at the module interface unit?
test.cpp:
module;
#include <iostream>
export module M;
export
template<typename>
class T
{
public:
void foo() const
{ std::cout << "T" << std::endl; }
};
// export <-- NOT exported
template<>
class T<int>
{
public:
void foo() const
{ std::c... | Exporting affects only name lookup and linkage. Neither of those is relevant to any kind of template specialization or instantiation, so they never need exporting.
|
66,030,088 | 66,030,322 | Why is `std::uninitialized_copy/move etc.` not constexpr? | I was wondering why the uninitialized storage functions like
https://en.cppreference.com/w/cpp/memory/uninitialized_copy and https://en.cppreference.com/w/cpp/memory/uninitialized_move are not constexpr in C++20?
Going off of the "possible implementation" provided, wouldn't it only take converting
template<class InputI... | See P2283.
You're correct for uninitialized_copy, you just need to change the placement new to std::construct_at.
But for uninitialized_default_construct, you can't just use std::construct_at since that does value initialization and the algorithm needs to do default initialization. The paper suggests a new std::default... |
66,031,005 | 66,031,390 | C++17 what is the fastest way to convert list ( or other container ) to string cross platform | i have list of strings
std::list<std::string> list = { "--version", "--setcolor", "--setint" };
list.push_back("--command1");
list.push_back("--command2");
list.push_back("--command3");
basically list of commands which in the end like to convert them to string
the list, in the end, can contain up to 100 commands.
what... | Using std::string as an accumulator (e.g., "string buffer", as seen in Java or C#) is standard practice in C++ and there's nothing C++11/14/17/20 adds to make it "faster".
Simply add up the length of the substrings - and the delimiters between them - string::reserve enough capacity in your target string, then string::a... |
66,031,101 | 66,036,748 | How do I open a folder within the Code::Blocks IDE? | Is there any way to open a folder in the Code::Blocks IDE without creating a whole new Code::Blocks project itself?
What I mean by opening a folder is:
In VSCode:
I can click on File and then click on Open Folder... and it will list all the files in that folder in the explorers shown below:
So, is there any way to do... | CodeBlocks doesn't have this command. You can only add files contained in a certain directory and its subdirectories to a project using the command Project -> Add files recursively
|
66,031,565 | 66,032,614 | Acquiring the first column of a CSV file without reading entire rows in C++ | Let's assume that we have a header-less CSV file (I'm including a header row for clarification but the actual file doesn't contain it):
ID,BookTitle,Author,Price
110,book1,author1,price1
178,book2,author2,price2
917,book3,author3,price3
How can I acquire the ID column without having to read whole rows of data into mem... | For any future readers who might stumble upon this question:
@largest_prime 's answer is the reasonable one. If your row data isn't that large (which for 99.99% of times, this is the case), it makes perfect sense to read it all, acquire the ID data and finally discard the rest of the row data.
However, in that 0.01% o... |
66,031,721 | 66,032,133 | Need help understanding the constructor in my program (c++) | Alright everyone I am pretty new to programming in C++. I have being doing it for college for about 2 months now. I send my professor a copy of one of my programs to help me understand the different parts of it. He told me the program I have submitted would require a constructor. With that said my knowledge on construc... | A constructor is a member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) create. It is a special member function of the class.
How constructors are different from a normal member function?
A constructor is different from normal fu... |
66,032,367 | 66,034,229 | How to retrieve bearer token from header (rest sdk) | I have worked a few times with a REST SDK. I want to retrieve a Bearer token from the response headers, using C++.
Image from Postman:
I have tried this:
CMyClass::SomeMethod(const web::http::http_request& Request)
{
const web::http::http_headers& headers = Request.headers();
web::http::http_headers::const_ite... | The output you are seeing means that you are not passing char* string pointers to std::cout.
Assuming you are using Microsoft's REST SDK (you did not say), its web::http::http_headers class holds utility::string_t values, and utility::string_t is defined as std::wstring on Windows (despite what the documentation says),... |
66,032,442 | 66,033,242 | C++ template subclass and multiple inheritance ambiguity | I have two base classes A, and B, and a third class C that (virtually) derives from both of them. Each class exposes its own public shared_ptr type.
In another class I have two vectors where I want to add objects of type A to one vector, objects of type B to another vector, and objects of type C to both. This result... | The standard derived-to-base conversion sequences take the length of the inheritance chain into account when ranking conversion sequences, a close base would be deemed a better conversion sequence than a one that is further up the inheritance chain. And that in turn affects pointers and references too!
Sadly, since sma... |
66,032,637 | 66,094,281 | adding series of numbers [1-->5000] with tread C++? | I want to add a series of numbers [1-->5000] with threads. But the result is not correct.
The goal is only to understand the threading well, because I am a beginner.
I tried this:
void thread_function(int i, int (*S))
{
(*S) = (*S) + i;
}
main()
{
std::vector<std::thread> vecto_Array;
int i = 0, Som = 0;
... |
Your attempt #1 has a race condition. See What is a race condition?
Your Attempt #2 neglects the standard, which says about the thread function these words:
Any return value from the function is ignored.
(see: https://en.cppreference.com/w/cpp/thread/thread/thread )
Your attempt #3 has a race condition.
Concurren... |
66,033,022 | 66,035,569 | Understanding std::pmr::new_delete_resource | I recently started looking into allocators and the new pmr introduced in c++17.
Looking at the definition of std::pmr::new_delete_resouece on cppreference I read the following:
Returns a pointer to a memory_resource that uses the global operator new and operator delete to allocate memory.
That "global" is kinda confu... | NicolBolas already gave a pretty clear answer, but since there appears to be some confusion in the comments regarding the "static storage duration" which I feels needs some clarity.
The function called new_delete_resource() is defined, on cppreference, to have the following affect:
Return Value:
Returns a pointer p to... |
66,033,566 | 66,049,441 | Issues with wxwidgets and VSCode | OS: linux
IDE: VSCode
complier: CMake but I can use another if better results are given
Hello I am wanting to learn how to apply c++ for cross platform development. I have chose to use WxWidgets, however, after compiling I ran into an issue, I could not integrate WxWidgets. I tried using vcpkg because it seemed simpler... | Please do the following
Open the Terminal.
Do `cd </path/to/your/source/code>.
Do
g++ -o <your_binary_name> wx-config --cxxflags --libs *.cpp
Did it work?
Thank you.
BTW, CMake is not a compiler - its a tool to generate Makefile and project files for different IDEs.
|
66,033,893 | 66,036,371 | Efficient, DRY bi-directional lookup in both python and C++ | In our workflow, we have a few tables of integer ID <-> string name mappings (e.g., status/error codes, hardware IDs, etc.). We are trying to find the best way to write a bidirectional lookup library for these values in both C++ and python.
The interfaces might look like
namespace myproject{
namespace lookup{
ty... | There are two methods discussed already in other SO answers:
share enum between python and arduino
: write the C file from Python
Can Python load definitions from a C header file?: parse the C file to create Python values
|
66,034,306 | 66,034,458 | Why does this function not return or print anything? | "R3+2-1R2+1-1R2+0-2" is my input, I'm trying to figure out the total number of positive tests (value after + sign) in the string input. I think the function might be entering an infinite loop, but I'm not sure why...
int posiTests(string results)
{
//concatenator
string resultsc;
for (size_t i = ... | Here I've revamped the inner loops a bit to make sure j gets incremented correctly.
for (size_t j = 0; j < resultsc.size(); ++j)
{
if (resultsc[j] != '+')
{
continue;
}
while (j < resultsc.size() && resultsc[j] != '-')
{
if (isdigit(resultsc[j]))
... |
66,034,623 | 66,035,023 | Slow memcpy Performance | This may seem like a stupid/obvious question to some of you, but I'm still learning so please be gentle haha.
I'm writing an application without the CRT, so I have to implement my own memcpy function. After doing everything and getting it working, I noticed the application was performing significantly slower than it's ... | First thing first. Computers handle things in words. Typical word size is 4 or 8 bytes long (except on some 8 bit micros). If you can copy a word at a time, things will be much faster.
There are complications though. Many processors don't like misaligned access so each copy should on word boundaries.
Other optimization... |
66,035,253 | 66,035,645 | Template specialization for type traits where the type change depending on conditional | Assume we have a given class ABC that is templated with K and V:
template <typename K, typename V>
using ABC = AnotherClass<K, V>
I know that it is possible to implement type traits that check if a template T is of the given class ABC, eg:
template <typename T>
struct is_class_abc : std::false_type {};
template <type... | The partial specialization will not only check if the passed type is of the form ABC<K,V> but it also will try/need to deduce K and V. Now let's look at how this would work. Assume we pass the type trait should check ABC<K, V>. Since ABC is only a type alias, the actual type passed to this type trait will actually be o... |
66,035,554 | 66,035,793 | Elegant way to select a template implementation based on a variable of data types | I have a templated column reader
class ColumnIterator {
public:
};
template <typename DT>
class TypedColumnIterator : public ColumnIterator {
using data_type = typename DT::data_type;
public:
bool HasNext() { ... }
data_type Next() { ... }
};
class INT {
public:
using data_type = int32_t;
};
class DOUBLE... | With std::variant you could do it like this:
class ColumnIterator {
public:
};
template <typename DT>
class TypedColumnIterator : public ColumnIterator {
using data_type = typename DT::data_type;
public:
bool HasNext() { ... }
data_type Next() { ... }
};
template<class DT>
struct Column {
using data_type ... |
66,036,081 | 66,060,247 | Large Vectored Exception Handler in DLL is causing program to crash without debugger | I'm currently working on DLL (Windows 10, x64) which implements Vectored Exception Handler (VEH). It exports the function in sake of to be attached to an executable, nothing else. During attaching VEH it also calculates base offset with the following code snippet:
uint64_t GetModuleBase(const char *modname)
{
HANDL... | Ok, I was able to resolve the issue:
Picked up different debugger - x64dbg. Amazing debugger, which attaches to launched process instead of launching it in debug mode.
This allowed to identify stack overflow problem during process initialization.
I've applied the fast fix for this, cause I'm prototyping: modified .exe... |
66,036,753 | 66,052,191 | LLDB summary strings without quotes | Lets say that I have a c++ class that contains two c strings like below.
class PathExample {
char* partA; // Eg: "/some/folder/"
char* partB; // Eg: "SomeFile.txt"
}
I can make an lldb summary string for it:
type summary add PathExample --summary-string "${var.partA}${var.partB}"
However this adds unnecessary... | "Remove leading or trailing quote in the summary value" before adding to the output is a not supported by the summary string formatting options. We're trying to keep those options fairly streamlined, and that's a bit too much of a special purpose feature.
The thing that allows us to keep the summary string version fai... |
66,036,828 | 66,036,951 | Get class member by string | how to get class member by string?
have .h:
class configFile {
public:
class cfgVehicles {
public:
class base_car {
public:
int speed = 80;
FString displayName = "unknown";
};
class uazVehicle : public base_car {
public:
FString display... |
how i can get speed class member by string?
You generally cannot. There is no mechanism in the language to achieve this. In other words, the C++ language doesn't have sufficient introspection features. You cannot access things based on the names of variables using runtime strings because those names aren't stored any... |
66,037,102 | 66,037,302 | How can I count the number of occurrences in a string based on character letter? | My code is supposed to take user input of a file with a single string line and user input of the characters within that file and then count the number of occurrences of each character within that string. I have this code so far
Working code to count only one of the characters in the string. The two inputs & Output of t... | I would build a histogram (frequency) of the letters, then query the histogram:
// Assume ASCII encoding
int main()
{
std::string filename;
std::cout << "Enter filename: ";
std::getline(std::cin, filename);
std::ifstream data_file(filename);
if (!data_file)
{
std::cerr << "Error opening " << filename <... |
66,037,162 | 66,037,366 | Forcing C++ to prefer an overload with an implicit conversion over a template | I have a situation where I need overload resolution to prefer an overload with an implicit conversion over a template function with the same name.
Consider the following example:
#include <iostream>
#include <functional>
void call_function(const std::function<void()>& function)
{
std::cout << "CALL FUNCTION 1" << s... | If you want to change the overloads such that the former overload is chosen whenever there is an implicit conversion possible, with the latter being the backup, you can do this with SFINAE via std::enable_if:
#include <type_traits>
void call_function(const std::function<void()>& function)
{
std::cout << "CALL FUNCT... |
66,037,537 | 66,037,627 | Function returns a corrupted array | I have read some old questions and tested some ideas, but my issue still exists, so here is what I want:
I need a function that returns a simple array with a fixed size of 181 integer values.
After some tests I have this function:
int *Sonar::scan(int *distances) {
// Scanning
for (int i = 0; i <= 180; i++) {
... | The first element of the array is being overwritten with the pointer to the array when you do:
*distances = sonar.scan(distances);
That is because you dereference the array with *distances giving a reference to the first element. You then assign to that with what you return from the scan method (the pointer to the arr... |
66,037,687 | 66,038,048 | How to translate this portion of C++ code to Delphi | I trying to port the RefPack compression implementation to Delphi, but I'm having trouble to understand some portions of code:
hashtbl = NEW int32[65536];
link = NEW int32[131072];
hashptr = hashtbl;
for (i=0; i<65536L/16; ++i)
{
*(hashptr+0) = *(hashptr+1) = *(hashptr+2) = *(hashptr+3) =
*(hashptr+4) =... | In C++, integer literals can include a suffix to specify the data type of the literal. In this case, the L suffix is for long. Delphi doesn't have such suffixes, but you can use typed constants instead.
In C++, the assignment = operator returns a reference to the left-hand variable that is being assigned to. That re... |
66,037,727 | 66,040,901 | GetDIBits() sets destination pointer to NULL with no error | I am trying to put an application icon into a char array. The code below converts a HICON into a BITMAP, then attempts to extract the bytes from the BITMAP into a char array. As I step through the code, I observed that the second GetDIBits() modifies the destination pointer to NULL despite claiming 16 bytes were writte... | I think you did not guarantee that the hbm parameter of GetDIBits is compatible bitmap during the process of converting HICON to HBITMAP.
Try to use the following code and test :
#include <iostream>
#include <windows.h>
using namespace std;
HBITMAP getBmp(HICON hIcon)
{
HDC hDC = GetDC(NULL);
HDC hMemDC = Crea... |
66,037,729 | 66,037,830 | What does __gnu_linux__ stand for? | Background
We have some old C++ code that contains a section that is only compiled if the preprocessor symbol __gnu_linux__ is defined. Compiling on my Ubuntu 20.04 with GCC 9.3 is not a problem. Now, we're trying to port this to a Docker container based on Alpine Linux with GCC 10.2 and discovered that __gnu_linux__ i... | See gcc/config/linux.h:
#define GNU_USER_TARGET_OS_CPP_BUILTINS() \
do { \
if (OPTION_GLIBC) \
builtin_define ("__gnu_linux__"); \
So it's defined only on Linux s... |
66,037,954 | 66,038,102 | How to input vector members in the console while using a while loop? | I'm stuck trying to input all vector members into the console.
All members should be odd, and if the the vector size is equal to 10, the program has to stop with further inputs (which it does). Should I use a for loop instead of the while loop?
Wherever I put cout << input << endl, it either messes with the loop or jus... | input is not part of the vector. It's a value that you may or may not have placed into the vector. If you want to print the contents of x, you have to print the contents of x. When you exit the loop and x is filled up, use a for loop to iterate through x.
#include <iostream>
#include <vector>
using namespace std;
int ... |
66,038,016 | 66,038,498 | Why does using "constexpr" give primary expression error in codeblocks | I am getting expected primary expression before constexpr in codeblocks only. Is there a way to fix this? This is the code I am trying to test. I have set c++ 17 as the compiler. I am using GNU GCC Compiler. GCC (MinGW.org GCC-6.3.0-1) 6.3.0. I am not getting this error in Visual Studio.
#include <iostream>
#include <... | Your version of GCC does not support if constexpr. Support was added in version 7.
You can look up which C++17 features are supported on the GCC website; the line relevant for this question is "constexpr if". There are a lot of "7"'s – and even one "8" – in the column for the first version that supports each feature, s... |
66,038,154 | 66,038,172 | What is this pointer inside a class C++/ OOP concept called? | class Node {
public:
int data;
Node* next;
};
In this Node is a class, but I did not understand what Node* next is. Is it like a class constructor?
| It's not a class constructor, it's just a second public member-variable. It's of type Node* rather than of type int, but otherwise it's similar to the int data; line.
|
66,038,277 | 66,063,121 | Show accelerator key in menu | I am using Gtkmm 3.22.30 on Ubuntu and I have been trying to show accelerator keys in my application menu, without success. So far, I have been able to register an accelerator key to my menu items, but for some reason, they don't appear in my menu. I know this is possible, because I have seen it in Inkscape, which I be... |
add_accel_group(accel_group);
m_menu.set_accel_group(accel_group);
I think the same AccelGroup cannot be assigned to a window and a menu. I searched the docs for details on this and found nothing, but my tummy feeling says me you have to delete one of these lines. And in this example they use the AccelGroup only in ... |
66,038,297 | 66,038,373 | How can I use std::string for Const Char Parameter | I am trying to use the std::rename() function to move a .docx file, however, the name of the file may vary. How can I use a std::string within std::rename() so that it does not have to be a hardcoded filepath, like this std::rename(filepath, destination);?
| I don't know how you want to populate the strings in question, but here you go:
std::string fromName {"whatever you're going to do"};
std::string toName {"whatever you're going to do"};
std::rename(fromName.c_str(), toName.c_str());
|
66,038,400 | 66,038,446 | In what functions do I got to use std::? | this is my first post, I am a beginner. I'm learning.
I've read that using using namespace std is considered a bad practice and I kinda understood why, so I'm trying to use std:: every time.
I know I have to use it in cout and cin.
My question is, in what other functions do I got to use std::? Where can I see a list or... | The list is really big. But the compiler will warn you if you don't use it when you need it. It helps if you use a decent IDE. There are a bunch that are free to use, so it's just a matter of picking one.
Pretty much everything you might call needs some sort of namespace prefix, with std:: being the most common.
Note t... |
66,038,417 | 66,038,590 | How do implicit class construction work in C++? | I created the following code for educational purposes and encountered a scenario for which I expected an error to occur, but no error occurred. Here is the class,
#include <string.h> // strcpy_s and strcat_s, not available in "<string>"
#include <string>
#include <iostream>
class String
{
char *p;
int len;
p... |
Why does this line work, why did it not create an error such as "Cannot add const char * with String"?
Because your String class has an implicit constructor from const char*. That allows the compiler to convert string literals to objects of type String implicitly, when needed.
So, when processing the "left " + right ... |
66,038,773 | 66,039,020 | How can I calculate the total pay for this assignment? | I am trying to write this assignment for school where the program has to calculate the regular pay, overtime pay and total pay separately. I would like to also include a statement where it mentions that if the number entered by the user is negative, the program would tell the user that the number entered is invalid so ... | Here are the code changes I made and the comments explain why
#include <iostream>
using namespace std;
int main()
{
//By initializing hoursworked and hourlyrate as negative, it ensures that the while loops used in the cin is used at least once
double hoursworked=-1, hourlyrate=-1, regularpay, overtimepay, to... |
66,039,030 | 66,040,000 | C++ | How to make a vector which contains multiple objects of different classes | I am trying to code my first game engine in C++ which will be like how Unity's scripting works. I am trying to make a component system. Here is my problem:
I want to have a vector containing my component since I will maybe need to add some dynamically. Where the problem happens is when I want to add derived class of my... | I think that C-style conversion is undefined behavior.
As far as I know, all the component class(like SpriteRenderer, Rigidbody and so on) derive from Component in Unity. So we can use dynamic_cast which offers safe downcasting. If the casting succeeds it returns a valid pointer otherwise nullptr.
Here's an example of ... |
66,039,319 | 66,051,342 | How to find the value for a key in unordered map? | I am trying to do the below sample in unordered map in c++
my_dict = {'one': ['alpha','gamma'], 'two': ['beta'], 'three' : ['charlie']}
print(my_dict["one"]) // ['alpha','gamma']
I tried using find operator like below
int main ()
{
std::unordered_map<std::string, std::vector<std::string>> dict;
dict["one"].push_back("... | The failure you are encountering is due to it->second being a std::vector object, which cannot be printed to std::cout because it lacks an overload for operator<<(std::ostream&,...).
Unlike languages like Python that do this for you, in C++ you must manually loop through the elements and print each entry.
To fix this, ... |
66,039,546 | 66,039,710 | Cant push_back() non copyable object to vector reference C++ | I am having some trouble with a tiny piece of code that has me a little confused. I am currently working on a project where speed is important, hence my choice of c++.
I am trying to pass a vector into a function by reference. The vector is of type unique_ptr<int> and I would like to call push_back() on the vector to a... | This snippet fails to compile simply because you are passing a vector of unique_ptr by value to the appendToVectorVal function. passing a vector by value means you call the copy constructor of std::vector, which call the constructor of every element the vector holds. But the copy constructor of std::unique_ptr is delet... |
66,040,014 | 66,040,247 | Calculate sum of int input numbers only stop with non-numerical input | I am learning C++ with "C++ Primer", an example of "calculating the sum of input values" is below:
#include <iostream>
int main()
{
int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read
while (std::cin >> value)
sum += val... | Continuing from the comment, if you want to end collection of number input when the user presses Enter on an empty line, then you want to read input into a std::string using getline() and then parse the integer values from the string using std::stringstream which will allow you to handle multiple integers entered on th... |
66,040,039 | 66,064,238 | OpenMP support for Mac using clang or gcc | I am using Mac OS and I created a toy CMake project with OpenMP.
main.cpp:
#include <iostream>
#include "omp.h"
using namespace std;
int main() {
cout << "Hello, World!" << endl;
#pragma omp parallel
cout << "Hello OpenMP from thread " << omp_get_thread_num() << endl;
return 0;
}
CMakeList.txt:
cmake_m... | I have solved my problem by changing the default compiler to g++. (Note: I have already installed gcc/g++ and the OpenMP library from Homebrew.)
I did not change main.cpp and CMakeList.txt, but when I built the project, I use
mkdir build && cd build && cmake -DCMAKE_CXX_COMPILER=g++-9 .. && make -j
then the error clan... |
66,040,067 | 66,043,231 | What is the best practice if I want to forward a variable to be moved in C++? | #include <utility>
class SomeObject {
// ...Object Definition
};
void B(SomeObject& so)
{
SomeObject movedTo = std::move(so);
}
void A(SomeObject& so)
{
B(so);
}
int main()
{
SomeObject movedFrom;
A(movedFrom);
return 0;
}
For example, now I have two functions A and B. Function A may first do s... | void B(SomeObject& so)
{
SomeObject movedTo = std::move(so);
This is a bad design. Don't move from an lvalue reference parameter. That is going to miselead programmers who make reasonable assumptions based on the parameter type and won't expect the argument that they pass to be moved from.
In the second version, ... |
66,040,166 | 66,040,232 | C++ Shared_Ptr not sharing? | I'm a complete novice to smart pointers, much less C++, so bear with me here. My program attempts to construct classes with unique serial numbers. It does this by placing already-made serial numbers into a shared_ptr. In theory, this pointer should share the set to all of the classes, but it fails to.
This is my class ... | You seem to misunderstand the concept of shared pointers. They share ownership, not memory. Smart Pointers are all about ownership.
With a shared pointer, the memory it owns is kept alive as long as there are objects referencing it
( different with a unique pointer where only one can own this memory. if this single ref... |
66,040,432 | 66,040,729 | Tricky issue with accessing the data of a (complex) variable, defined as pointer (C++) | This is what I assume to know: When printing the variable "i" in the console, the command "std::cout << i" is usually used. If "i" refers to a pointer, I do "std::cout << *i". So far so good.
But in the (classical CUDA FFT) C++ example below, this doesn't work and I don't know why. Here's the code snippet (I don't want... |
which seems to me the address and not the data of the variable?
Yes, that's an address, most likely the (starting) address of your real or complex array d_DataSpectrum (please provide the declaration!). You are not dereferencing here, you simply try to cast to a pointer of cufftComplex. Keep in mind, that you want to... |
66,040,711 | 66,041,273 | What does void (M :: *pf)(int,int) = &M :: set_xy; do? | what does this code section do?
void(M :: *pf)(int, int)=&M :: set_xy;
(n*pf)(10,20);
| What you have there is a function pointer. But not a normal one, a member function pointer. There a few things different in member function pointers when compared to normal ones.
1. It states where the function comes from (which class/ struct holds it).
In your example void(M :: *pf(int, int)=&M :: set_xy;, M is the c... |
66,040,819 | 66,040,996 | Array with elements of different types | Is there any way to have an array consisting of different types in C++?
For example:
#include<iostream>
using namespace std;
int main() {
string cars[5] = {"BMW", "Audi", "Ferrari", "Lamborghini", "McLaren"};
return 0;
}
This is how we normally create an array in C++ with a type specified.
But can we create a... |
Is there any way to have an array consisting of different types in
C++?
Yes, you can use std::any (since C++17):
std::any arr[] { "BMW", 14, "Audi", 25, "Ferrari", 3, "Lamborghini", 7, "McLaren", 0 };
// (use vector or std::array instead)
You can also use a sum type like std::variant (since C++17) or std::tuple
|
66,040,953 | 66,043,220 | Inline constexpr and anonymous namespace variables? | I have the following problem. In a .hpp file I have a function Space::foo() that must use a namespace global variable, I thought of hiding it in an anonymous namespace. But now I wonder, do I risk having values defined in each translation unit with multiple copies or there will only be one? Thanks for helping. This com... |
do I risk having values defined in each translation unit with multiple copies
Yes. You'll have one definition of values in each TU. You can't declare it extern constexpr either because [dcl.constexpr]/1 says "The constexpr specifier shall be applied only to the definition of a variable".
Since the purpose seems to be... |
66,041,415 | 66,041,677 | Send type into function using templates | I have this function for finding key in map and return the right value with type:
template< typename T >
T Foo::findInMap(std::string key) {
std::map<std::string, std::any>::iterator it = options.find(key);
if (it != options.end())
{
return std::any_cast<T>(it->second);
}
return nullptr;
}
... | Returning a nullptr is not always possible. Modern C++ way of returning optional values is to use std::optional. You can use auto instead of the long iterator type name. Here's one way you can do it:
template< typename T >
std::optional<T> findInMap(std::string key) {
auto const it = options.find(key);
if (it !... |
66,041,982 | 66,045,383 | C# & C++ checksum calculation | I need your help with calculating checksum in C#. Code below is for application writen in C++. App is receiving packets from UDP. This is part of code where is receive and checksum calculation.
struct OPtoLSs {BlockReceivedS hdr; char data[0x100];}; //struct for received data
OPtoLSs mCKr;
#define hdrR mCKr.hdr.OPhdr
... | The server calculates the checksum only of the half of the received header and data. Sent checksum should lead to calculated checksum become 0xffff.
I assume you are sending to the server CommandKeyS structure and it's size is constant. I assume ChkSum on the server is of type _int16 and initialized to 0.
I dont know C... |
66,042,339 | 66,042,382 | How Can I Add An Include Path in GCC C++ | I can add include paths in Visual Studio easily but I couldn't find a way to do it in GCC? Any helps please?
| Use the -I command-line argument:
gcc -Ipath
|
66,042,456 | 66,043,317 | Stubbing class has already been declared | I am stubbing the class "myClass" and its 50+ members "myMemberFunction*" for a unit test.
I don't want to write the class name every time, so I tried the following:
namespace myNamespace{
myClass::myClass()
{
// constructor code
}
namespace myClass {
void myMemberFunction1()
{
// function ... | Classes and namespaces are two different things. You cant use namespace myClass and define all the members inside. You have to use <return type> myClass::<function> every time you define it outside the class.
You could use tools like Visual Assist, Intellisense to create the function definitions for you. But apart from... |
66,042,577 | 66,042,615 | why cout statement is not working after pointer initialization? | cout statement is not working after pointer initialization. And this code gives me a segmentation fault.
#include <iostream>
using namespace std;
int main()
{
int *p;
*p=12;
cout<<"NOW THIS STATEMENT WILL NOT WORK";//BUT WHY?
cout<<*p;
return 0;
}
| You didnt initialize the pointer:
int *p;
p points "nowhere", it is not initialized, its value is indeterminate. When you dereference it in the next line:
*p=12;
You cause undefined behavior, because p does not point to an int. There is no int where you could store 12.
If you want to store an int somewhere, you need ... |
66,042,616 | 66,042,710 | Memory leak with "new" operator and "&"? C++ | This will lead to memory leak:
int var = *new int(5);
This will not (if later freed):
int* var = new int(5);
Question: Will this lead to memory leak?
int& var = *new int(5);
Yes, I should use smart pointers instead but that is not the question :)
| It will cause a memory leak. What your doing there is allocating a block of memory, dereferencing the pointer and assigning it to the variable var. Dynamic memory allocation does not deallocate itself when gone out of the scope, instead the variable var will be destroyed, not the pointer that you allocated.
To delete i... |
66,043,078 | 66,043,776 | process terminated with status -1073740940 | background: I was writing a c++ program to solve this problem:
For a positive integer N, the digit-sum of N is defined as the sum of N itself and its digits. When M
is the digitsum of N, we call N a generator of M.For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of
256. Not su... | You may be writing past the end of your array during the computation and corrupting something. What happens for i = 99999? I don't think 100005 is quite enough to contain that. Let's check:
#include <stdio.h>
int main() {
int i = 99999;
int y = i;
int i_op = i;
while(i_op){
y += i_op%10;
... |
66,043,270 | 66,043,532 | The timing of std::cout output is strange | #include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
std::cout << "1";
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
std::cout << "2";
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
std::cout << "3";
std::this_thread::sle... | std::cout is buffered:
C++11 27.4.2 [narrow.stream.objects]/3 : The object cout controls output to a stream buffer associated with the object stdout
so you need to explicitly flush this buffer to get what you want. Here are some ways to do this:
1. Use operator<< with std::flush
std::cout << "1" << std::flush;
2. Us... |
66,043,680 | 66,043,925 | std::map erase preserving iterators | I'm implementing my own std::map, using a basic binary search tree.
The erase method is supposed to
invalidate the iterators referring to element removed and preserve the
validity of all other iterators
Yet here is what the BST "classic" delete algorithm is doing:
If node to be deleted A has two children, "replace" A... |
Is the algorithm I've found not suitable ?
Correct. The algorithm that you describe would not be suitable for implementing std::map.
|
66,043,793 | 66,047,617 | Stop bycatch of <stdio.h> definitions caused by C++ includes | In a comment to another answer, I was shown a code example that seemingly used printf and puts without including <stdio.h> but the online compiler didn't complain.[1] To understand what's going on, I copied it to my local IDE.
Reduced to relevant includes and output, it's basically this:
#include <string>
#include <map... | I am afraid you cannot.
The standard requires that the well known include files declare the relevant names, but does not prevent them to include other files/names, if the library implementation finds it useful.
Said differently, after including iostream you are sure that all the names belonging to it are correctly decl... |
66,043,842 | 66,049,373 | What is the runtime complexity of `boost::edge()` on an adjacency_list with vecS? | I have an undirected adjacency_list graph defined as this:
typedef boost::adjacency_list<
boost::vecS,
boost::vecS, boost::undirectedS,
boost::no_property,
boost::property<
boost::edge_weight_t, int, EdgeInfo>
> weighted_graph;
... | edge(v,u) searches for an edge. Why would you do this? If Since² you know the edges exist anyways, you should probably either:
be using an adjacency matrix instead
or already have a hold of the edge descriptor of the edge you knew existed (instead of searching for it)
Q. I was not able to find any documentation on t... |
66,043,855 | 66,044,001 | Can assignment operator be overloaded to return the value of a property of a class? | I wanted to return the value of a property of a class using assignment operator. I tried to fulfill this purpose. I searched a lot on the web but all of the websites I visited talked about how to overload assignment operator to do like a copy constructor of a class like this: class_t& operator=(class_t&);. Can anybody ... | You can’t overload operator = for this. What you can do instead is overload the implicit conversion-to-int operator inside the class:
operator int() const { return value; }
However, think carefully whether this is actually a good idea in your case. Implicit conversions should usually be avoided at all cost, because it... |
66,045,058 | 66,045,670 | How to check whether array elements entered by user are sorted or not in c++ | So it's a simple c++ program which takes 2 sorted arrays from user dynamically using new operator and sum ups their size to create a third array which is equal to the length of the both array sum..
Like final_arr = arr1_size +arr2_size;
Everything is working fine but the problem is that is that I am taking array values... | #include <algorithm>
// ...
// check if arr1 is sorted
bool input_is_sorted = std::is_sorted(arr1, arr1 + arr1_size);
See https://en.cppreference.com/w/cpp/algorithm/is_sorted
Of course you would better replace bare pointers with std::vector etc.
|
66,045,268 | 66,045,530 | Is it possible to override functionality with a mixin-like pattern in c++ | let's say I have the following classes:
class Base {
public:
virtual int do_something() = 0;
protected:
virtual int give_intermediate_result(int) = 0;
int m_some_shared_resources;
};
class Foo : public Base {
public:
virtual int do_something() override { return give_intermediate_result(1); }
protected... | template<class Base, template<class>class...Mixins>
struct Foo:Base{};
template<class Base, template<class>class M0, template<class>class...Mixins>
struct Foo<Base, M0, Mixins...>:M0<Foo<Base, Mixins...>>{};
struct Base{
virtual int A()=0;
virtual int B()=0;
virtual ~Base()=default;
};
template<class Base>
stru... |
66,045,440 | 66,045,726 | c++ pass multiple data types (including arrays of different dimensions) to function | i am trying to create a class that can handle tensors. In the constructor of the function i want to pass inputs of different data types (int, vectors...). I also want to pass arrays that always have different dimensions (1D, 3D...). For the constructor i figured out something like this:
template <class T>
Tensor(T inpu... | You could use constexpr-if:
#include <iostream>
#include <type_traits>
template <class D = double>
class Tensor {
public:
using content_dtype = D; // put it here for everyone to see
template <class T>
Tensor(const T& input) {
if constexpr (std::is_arithmetic_v<T>) {
if constexpr (std::... |
66,045,804 | 66,046,780 | How to build Shim from source | I'm trying to build shim from source but i'm getting the following error.
ld -o shimx64.so --hash-style=sysv -nostdlib -znocombreloc -T /home/john/git/shim/elf_x86_64_efi.lds -shared -Bsymbolic -L/usr/lib64/gnuefi -L/usr/lib64 -LCryptlib -LCryptlib/OpenSSL /usr/lib64/gnuefi/crt0-efi-x86_64.o --build-id=sha1 --no-undef... | Looking at the file list of the gnu-efi package, I see:
/usr/lib/crt0-efi-x86_64.o (not /usr/lib64/gnuefi/crt0-efi-x86_64.o)
/usr/lib/libefi.a (not in /usr/lib64)
/usr/lib/libgnuefi.a (not in /usr/lib64)
I think you need to set LIBDIR=/usr/lib and EFI_PATH=/usr/lib during make, rather than the defaults which are /usr/... |
66,046,233 | 66,046,274 | when we write void variable like void *p ; cout<<&p; cout<<p; so it give two different address but why? | C++ output give two different address
but why complier give two address instead of I am writing only one variable
void *p ;
cout<<&p<<p;
| void *p ; is an uninitialized pointer. So what you will have inside the pointer there is actual garbage. When you do &p, your returning the address of the pointer p. That's why they both return different values.
|
66,046,335 | 66,046,483 | Why is my output not showing the node containing 14 when I print? | Why is my output not showing the node containing 14 when I print it?
I guess I am missing some crucial principles in implementing a linked list:
#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode *next;
ListNode(int d,ListNode* p=NULL) //constructor
{
value=d;
... | You did not add the node with the value 14 to the list. That is neither node in the list points to the node created in this declaration
ListNode* t=new ListNode(14);
The only what you did is set the data member next of the node to the address of the node with the value 19.
ListNode* g=ptr;
ptr=t;
t->next=g;
Here the... |
66,046,887 | 70,526,285 | How to use TensorFlow C++ api as a shared library with bazel? | Now I can build TensorFlow C++ api as a shared library refer to make shared libraries with Bazel at Tensorflow, libtensorflow_cc.so and libtensorflow_framework.so file can be locate at bazel-bin/tensorflow.
I am not familiar with bazel, how should I use those TF shared library with bazel to write C++ code, could you pl... | Bazel is just a tool like make or cmake. For compiling your code using bazel, you have to create a build file BUILD. Suppose that your code is at, e.g., tensorflow/tensorflow/test/code.cpp:
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
using namespace tensorflow;
...
create a ... |
66,046,969 | 66,074,526 | Default working .clang-format file for Visual Studio | I want to use the Clang C++ syntax in Visual Studio 2019 (not Code) with a few modifications. I created a .clang-format file and copied it to my project. Visual Studio recognizes the file, but prompts me with a ton of unrecognized keys (e.g.
YAML:87:19: error: unknown key 'IndentCaseBlocks'
). Is there a recommended ... | Alright, none of the automatically created files worked, so I decided to go through all the keys manually after all. It turned out there weren't that many invalid keys as I had feared. Here is a list of the keys that I had to comment out to get the .clang-format working in Visual Studio 2019:
# AlignConsecutiveBitField... |
66,047,256 | 66,047,558 | C++ Template Wildcard-like construct (or: How can I make Wildcards with a Template) | So, as you might have already imagined, I'm trying to use wildcards in C++. But first, let me give you an example of what I mean:
Lets suppose we have a Human class and a Pocket class. The Pocket class has an arbitrary other class as an type argument. To visualize this better, let's write some code (in Java:)
Human.jav... | You have three key differences between Java and C++ to cope with here: the type system is different, templates are not generics, and vectors are not arraylists.
The type system:
In Java, every instantiation of Pocket<E> still derives from Object, so there's some common base type to store a reference to.
In C++, every ... |
66,047,535 | 66,047,727 | Disadvantages of using a function pointer as an UI-Button callback | I am currently creating my own GUI-Library based on SFML.
At the moment i am working on a Button. So when creating a button you also have to specify a callback which is a function, executed on the button click.
Now, I'm answering me what the disadvantages are of using just a pointer to a function as a button-callback, ... | It's a tricky problem!
Function pointers are simple to implement on the sender side, but they are difficult to use on the receiver side because they they don't have any context.
One issue is that a function pointer cannot point to a member function. That's why you often see (C-style) frameworks pass an arbitrary void *... |
66,047,652 | 66,047,792 | How to provide a copy constructor for the overloaded lambda trick | I have the following code which extends the overload trick with lambda to also accept a variant. However the variant is not the issue in the example.
https://godbolt.org/z/GxhaPr
#include <memory>
#include <variant>
#include <functional>
template <class ...Fs>
struct overload : Fs... {
template <class ...Ts>
o... | The reason your code fails to compile is not because overload's default copy constructor doesn't work. It's because the templated constructor is basically a catch-all. Any and every constructor argument will match it, so it will always get called.
You can use some SFINAE on the overload constructor to make sure it does... |
66,047,692 | 66,048,079 | Is a temporary struct an r-value or an x-value? | I wanted a clarification regarding C++ value categories.
struct Foo {...};
void do_something(Foo{});
Is the Foo{} above a r-value or an x-value?
I understand that there is a hierarchy of value categories, and that r-values are actually either an x-value or a pr-value. I also know that the standard says that "temporary... | From https://eel.is/c++draft/basic.lval (accessed 04/02/2021):
Every expression belongs to exactly one of the fundamental
classifications in this taxonomy: lvalue, xvalue, or prvalue. This
property of an expression is called its value category.
This answers your question of whether gl-value and r-value are categories... |
66,047,783 | 66,047,948 | How do I best handle conversion into template type from const char * | I have a template function, within which I need to convert a const char * to my template value.
I know for a fact that this const char * was originally read from a ascii text file. My current code looks like this:
template <typename T>
bool Get(T &value, std::string const &query, T const &default)
{
... |
Is there a way I can convert the char* to my type T seamlessly,
No.
There is no way to make conversion from string to a type automatically work with all types. Such conversion has to be implemented for each class. Typically, it is done by implementing the stream extraction operator >> for std::istream. The built in t... |
66,048,186 | 66,049,692 | C++ To C# Marshaling of Nested Structs with Union | I have to use C++ .dll with C# code. I need to call a method:
THERMALSDK_API short PASCAL GetIRHeaders(HANDLE handle, IRF_IR_FILE_HEADER_T* header, IRF_IR_DATA_HEADER_T* addedInfo, unsigned long *curPos);
To do so, i've created a simple wrapper:
public class COXAccessor : ICOXAccessor
{
[DllImport("ThermalCamDll",... | Forget the union, it does nothing in this case but add padding at the end. The padding is obviously important, but you can just pad it yourself by counting the bytes and ensuring your structure is at least 128 bytes (which is what the second union part sets it as).
This will simplify your definition greatly, no more Fi... |
66,048,276 | 66,048,546 | how can I print dynamic array in c++ I need explanation to this question | This is the question my teacher gave me:
Construct a structure Employee that consists of the following fields:
ID, name, degree, age
A function that creates an object (a variable of Employee type), fills it from the user the, then returns it.
A function that receives an object (a variable of Employee type) and prints ... | A function can have parameters and return a value. So here, fillin should return an Employee object, and print should take an Employee (or better a const reference) parameter:
Employee fillin()
{ Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
... |
66,048,386 | 66,048,444 | C++17 Check if all elements in vector start with substring using lambda no loop | i have vector
std::vector<std::string> v = {"--d","--e","--f"};
i don't want to go with the loop rout
for (auto it = v.begin(); it != v.end(); ++it){
...
}
is there any more elegant way to check if all elements in the vector start with "-" ?
can use c++17
| You can use std::all_of:
#include <algorithm>
bool startWithDash = std::all_of(v.begin(), v.end(),
[](std::string const & e) { return not e.empty() and e.at(0) == '-'; });
This will work in C++11 and newer.
|
66,048,509 | 66,049,466 | array members of structs in dart:ffi | I'd like to use Bob Jenkins rng in my flutter projects
https://burtleburtle.net/bob/rand/isaacafa.html
here we have a struct with 2 static buffers in it
/* context of random number generator */
struct randctx
{
ub4 randcnt;
ub4 randrsl[RANDSIZ];
ub4 randmem[RANDSIZ];
ub4 randa;
ub4 randb;
ub4 randc;
};
type... | Came up with something:
keep the original struct but add 2 extra pointers for the buffers
struct randctx
{
ub4 randcnt;
ub4 randrsl[RANDSIZ];
ub4 randmem[RANDSIZ];
ub4* rslptr;
ub4* memptr;
ub4 randa;
ub4 randb;
ub4 randc;
};
typedef struct randctx randctx;
randctx* create_context() {
randctx* ctx ... |
66,048,513 | 66,048,598 | Should I reference elements of arrays when working with them? | Let's say we want to implement bubble sort using the following code:
void bubbleSort(int arr[], int n){
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n;j++){
if(arr[i]>arr[j]){
swap(arr[i], arr[j]);
}
}
}
}
Should there be an & before arr[i] and arr[j] in th... |
Should there be an & before arr[i] and arr[j] in the swap function
Depends on the types of the arguments that swap accepts.
If you're asking about std::swap of the C++ standard library, then: No, there shouldn't be operator &.
and what would be the difference?
The unary & operator is the addressof operator. The res... |
66,049,139 | 66,049,388 | freopen() does not read / write to existing file, niether creates new file in vscode | I am trying to read input and output from two separate text files in C++.
Code(test.cpp):
#include<bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int x = 6 ;
cin >> x;
cout << x;
}
input.txt:
1
... | Okay, I get what is happening here. In the launch.json file, the "cwd" value is the path of the current working directory of the process being launched or debugged, this is where the input files are read from and output files and written to by default.
You should set it to the directory where the files you are working ... |
66,049,700 | 66,049,732 | Does a function returning the value of a pointer to a new[] array leaks memory after returning the result? | I've read that we need to delete pointers after pointing it to a value address created with the keyword "new". But I need to get the values inside of an array and return it to a variable, so I wrote this function:
GLfloat VertexArray(Vertex<GLfloat> v1, Vertex<GLfloat> v2, Vertex<GLfloat> v3) {
GLfloat *ArrayPtr = ... | Yes it's bad. It's a memory leak because the allocated array is never deleted (as you said).
Here's a version that doesn't leak
GLfloat VertexArray(Vertex<GLfloat> v1, Vertex<GLfloat> v2, Vertex<GLfloat> v3) {
return v1.x;
};
No allocation is needed for the function you wrote, because the only value you are return... |
66,049,997 | 66,050,129 | Why doesn't passing a function with default parameters to a templatized constructor and storing it using a lambda as std::function<void()> work? | Take this simplified example:
Command.h:
class Command {
public:
template<typename Func>
Command(Func newToExecute) : toExecute([&newToExecute](){newToExecute();}) { }
void callFunction(); //defined in Command.cpp -> calls function with toExecute();
private:
std::function<void()> toExecute;
};
Main.cpp... | Your second version doesn't take the address of test. The type of that &test is void (*)(int), not void (*)().
This is also why you can't construct a std::function<void()> from test directly.
|
66,050,455 | 66,050,930 | How can I use a changing int value to call different functions on an Arduino? | I am programming (kind of) a stopwatch with start buttons and a 4-digit seven-segment LED display on my Arduino Uno.
With functions like this one I can put numbers on the SevSeg without problems:
void Zahl_1()
{
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
digitalW... | The problem here is you're not calling any function. To call a function you do:
function();
In your example you are missing the parentheses.
Another thing I want to point out is your use of if statements. It's more efficient and a better practice to use switch statements when doing stuff depending on the value of a va... |
66,051,544 | 66,051,893 | Forward Iterator - Const version issue | I can't seem a way to fix this issue. I have implemented a templated forward iterator that I'd like to also use as const_iterator in my ForwardList class. What I tried so far is using an alias, and insert const as template argument, but it doesn't seem to work.
This is my forward iterator:
template<typename T>
... | The below makes your forward_iterator<const T> point at a Node<const T> while the forward_iterator<T> will point at a Node<T>. Both should point at a Node<T> whether T is const or not itself:
template<typename T>
class forward_iterator {
private:
Node<T>* m_iterator;
I find it easier to create the iterator as a cl... |
66,051,940 | 66,052,047 | How to call parent constructor in child classes constructor? | I have searched for it and this seems to be the only way of calling a superclass constructor in C++:
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: Sup... | A base class constructor must be run to initialize the base before you can enter the body of the derived class constructor. The Member Initializer List is the only way to initialize the base class. If you have complex requirements for the parameters, use helper functions to compute the parameters.
Example:
class SuperC... |
66,052,178 | 66,052,197 | C++ Calling a string from a struct stops the program | I'm a beginner in C++. I appreciate any suggestions in which could improve my code but what I'm really looking for is an explanation as to why my current code isn't returning what I want.
#include <iostream>
#include <string>
using namespace std;
struct MATRIX {
float values[1][1];
string names;
};
MATRIX get_ma... | You have to specify the number of elements, not the maximum index, to declare arrays in C++.
With this declaration
float values[1][1];
Only values[0][0] is avaliable.
The declaration should be
float values[2][2];
|
66,052,957 | 66,873,935 | Unforgettable Factory and multiple levels of inheritance and hierachy | I've been experimenting with the factory implementation described here:
http://www.nirfriedman.com/2018/04/29/unforgettable-factory/
The example uses "Animal" as a base and "Dog" and "Cat" as the derived classes that are registered with the factory. But now suppose I wanted to add a "Lion" class that derives from Cat.... | I ended up tweaking the factory class slightly by remove inheritance from Base in the Registrar class. I changed this:
template <class T> struct Registrar : Base {
to this:
template <class T> struct Registrar
Going back to my example above I now use the factory like so:
struct Animal
{
virtual void speak() = 0;
... |
66,053,060 | 66,053,769 | Accessing elements by letter inside templated math vector structure | I have a Vector3 structure that I define using a union, such that I can access individual elements by both a variable and array:
struct Vector3 {
union {
struct {
float x;
float y;
float z;
};
struct {
float arr[3];
};
};... | You can do away with unions and C style arrays.
Godbolt
#include <cassert>
#include <array>
template <class TFloat, std::size_t Size>
struct Vector
{
std::array<TFloat, Size> array;
};
template<class TFloat>
struct Vector<TFloat, 3>
{
std::array<TFloat, 3> array;
const TFloat& x = array[0];
const TFl... |
66,053,248 | 66,054,787 | How to handle QTModbusTcpClient request in QTModbusTcpServer | I'm trying to create Modbus TCP server with QT libraries.
I have problem, because I can't find a way, to create correct response for request from Modbus Client.
As I understand it, after starting the application, the server listens for incoming messages all the time, but I can't find in documentation correct function t... | You must set the server address with modbusDevice->setServerAddress(1) before calling connectDevice()
The parameter is the server instance. You can have at most 255 instances per IP address
modbusDevice->setConnectionParameter(QModbusDevice::NetworkAddressParameter, "127.0.0.1");
modbusDevice->setConnectionParameter(QM... |
66,053,422 | 66,054,408 | Name followed by :: must be a class or namespace name | I have reviewed numerous articles on this subject both here and elsewhere on the internet and have developed my code to conform with what I've learned. Unfortunately, that doesn't seem to solve this problem. Here are the pieces of the puzzle:
The defined class:
class FileData {
private:
char* filename;
public:
... | You have declared OpenListFile() as an instance method, not as a static method. FileRec is an instance of the FileData class. You need to use the . operator to access members of an object instance, eg:
FileData FileRec;
std::fstream ListFile;
...
if ((ccode = FileRec.OpenListFile(ListFile, fspec3)) != 0) {
// ...
... |
66,053,425 | 66,099,294 | WINAPI Network Discovery without SMBv1 | I need to get a list of available shared folders on the local network, the way they appear in the "Network" tab in File Explorer. Earlier, I used combination of NetServerEnum/NetShareEnum functions to obtain it, but they are using SMBv1 protocol, which is now disabled by default in windows, so now i'm getting error 123... | You can use windows shell api and use FOLDERID_NetworkFolder to get the KNOWNFOLDERID of "network".
The following sample can get folders, nonfolders, and hidden items in the "network" folder.
#include <windows.h>
#include <Shobjidl.h>
#include <Shlobj.h>
#include <iostream>
void wmain(int argc, TCHAR* lpszArgv[])
{
... |
66,053,608 | 66,053,950 | Perfect forwarding trickery | If your object has multiple parameters and can take l or r value references the number of constructors jumps quickly. Can a little template trickery simplify the situation or does this cause issues that I am not aware of OR am I over-thinking it and there is standard way of simplifying this?
// In the following context... | The simplest way to do this in your specific case would be to do:
class Original
{
std::string val1;
std::string val2;
public:
Original(std::string v1, std::string v2) noexcept
: val1{ std::move(v1) }
, val2{ std::move(v2) }
{}
};
This is often good enough for constructors. It potentially d... |
66,053,703 | 66,089,629 | Vertex skinning artifacts with specific glTF models | I recently implemented vertex skinning in my own Vulkan engine. Pretty much all models render properly, however, I find that with Mixamo models, I get skinning artifacts. The main difference I found between "regular" glTF models and Mixamo models, is that the Mixamo models share inverse bind matrices between multiple m... | So basically the mistake I made was relatively simple. It was caused by casting the joints to the wrong type. When a glTF model uses a byte stride of size 4 for the vertex joints, the implicit type is uint8_t (unsigned byte) and not the uint16_t (unsigned short) which I was using.
|
66,053,905 | 66,054,728 | Reproducible results with parallel_for and random numbers possible? | I have code which involves some heavy computations so I use the parallel_for loop in Visual Studio C++. This works fine and the code runs much faster in comparison with a normal for loop.
My problem is that I want reproducible results but the computations involve random numbers. I can use a fixed seed but this does see... | The reason is because you have undefined behavior. You call the static random number generator from multiple threads at once.
Make it thread_local (it also becomes static when you do):
thread_local std::mt19937 mt(seed);
Note: I don't know the <ppl.h> library, but making a variable volatile is pointless as long as the... |
66,054,013 | 66,055,789 | The variable I initialised as 0 randomly turns into a -1? | I am trying to make vector based QuickSort implementation. However I ran into an out of range exception and I cannot figure out whats wrong with my code.
void myQuicksort(std::vector<int>& values, int first, int last);
int largest(std::vector<int>& values)
{
//using Quicksort
int first = 0;
int last = valu... | As pointed out by Thomas Sablik and Andreas Wenzel, the main problem is in the second call to myQuickSort() and it should be
std::swap(values[pivot], values[cnt2]);
myQuicksort(values, first, cnt2 - 1);
myQuicksort(values, cnt2 + 1, last); // <-- passing cnt2 - 1 here discarded the pivot
because you just swapped val... |
66,054,256 | 66,054,373 | Splitting a paragraph line by line in c++ | Hello I am a cs140 student so I am not the most experienced. I have an assignment and basically I have to find the longest line in a string vector. First I have to take paragraph as input. How do I take the input from a file and split it line by line into a string vector? Please go easy on me
| Well you don't usually read the text and then split it line by line. Instead, you read the text line by line in the first place, using the getline function
std::string line;
std::getline(std::cin, line);
You can choose to store all the lines in a vector of strings, however, in order to find the longest string, you don... |
66,054,267 | 66,060,964 | How do you use the MySQL Connector/C++ and XDevAPI while using XAMPP to run MySQL? | I am trying to access a MySQL database in my C++ code. I have a feeling I may have messed something up along the way, so I'll outline what steps I took and my setup:
I installed MySQL Connector/C++
I installed MySQL XDevAPI
I installed XAMPP and set it up to run a MySQL server
I created a database with some tables in ... | As far as I can tell, XAMPP is now based on MariaDB and not MySQL. The MySQL X DevAPI Connectors use the X Protocol (port 33060, by default, on a MySQL server instance) which isn't available on MariaDB.
MariaDB supports the classic MySQL protocol (port 3306), but you can't use X DevAPI clients over that protocol.
So ei... |
66,054,666 | 66,054,846 | memory_order_relaxed and visibility | Consider two threads, T1 and T2, that store and load an atomic integer a_i respectively. And let's further assume that the store is executed before the load starts being executed. By before, I mean in the absolute sense of time.
T1 T2
// other_instructions here... // ...
a_i.s... |
Is it guaranteed that T2 sees the value 7 after the load?
Memory order is irrelevant here; atomic operations are atomic. So long as you have ensured that the write "happens-before" the read (which you stated to be true in the premise of your question), and there are no other intervening operations, T2 will read the v... |
66,054,672 | 66,054,720 | Control output of c++ program using makefile | I have an executable called print-word-length.cc that takes prints the length of words using from a *.txt file.
So in my makefile, ./print-word-length </dir/dictionary.txt prints out words in the dictionary.
How would I go about just printing the first 10 lengths of words in dictionary.txt?
I've tried head -n 10 ./prin... | This isn't a makefile question, it's a shell scripting question. You solve the problem by writing a shell command at your shell prompt, then you just put that same solution into your makefile.
The head utility prints the first lines it reads from standard input or from a file. It doesn't run a command that you give i... |
66,054,774 | 66,055,199 | Pass thread arguments by reference gives me access violation | I looked up how I can pass thread arguments by reference and I found std::ref so I used that:
void Watermarker::markDirectory(const std::string& targetDirectory, const std::string& watermarkPath)
{
std::vector<std::thread*> threads;
cv::Mat watermarkImage = loadImage(watermarkPath);
if (watermarkImage.data... | The problem is that you're changing watermarkImage from multiple threads at once in the mark function, making your program have undefined behavior.
Suggestion: Take it as a const& and copy it in the thread.
void Watermarker::mark(const std::string& targetDirectory,
const std::filesystem::path& im... |
66,054,860 | 66,055,094 | Overloading function call operator () for indexing and assignments of a template object | I am attempting to create a template for a matrix data structure and I would like to have concise and intuitive way to index and assign elements (i.e. 'A(i,j)' returns an element and 'A(i,j)=x' assigns a value to this element.)
Based on other forum threads, I saw that by returning an array element by reference, a funct... | The formula used for indexing into data is incorrect.
Update your function to return data[0] always but print the index. The output will make it clear that you are not using the right index.
T& operator() (int i, int j) {
int index = (i-1)*(this->cols) + j;
std::cout << "Index: " << index << std::endl;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.