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 |
|---|---|---|---|---|
65,074,005 | 65,075,132 | Save a matrix in QSettings | I'm working on my qt chess game, in particular on persistence, so when the MainWindow is closed I have to save the int matrix, which represents the board state. I already wrote the function and it's working well with a matrix that I give for the test
MainWindow::~MainWindow()
{
int boardState2[8][8] = { {-5, -3, -... | The c++ keyword extern can help you. Using extern you can use the global matrix which is defined in other cpp file.
|
65,074,057 | 65,214,875 | How to organize unit tests in googletest efficiently | I am currently thinking about restructuring the unit tests in my project. I use Googletest as testing framework. My project consists of several shared libraries that are built and tested together.
As the number of unit tests grow, I find the organization of unit tests in google test getting harder and harder because I ... | If you look at the samples provided in the sources, the test macros shouldn't be present in header files.
According to this answer :
The RUN_ALL_TESTS() macro run all instances of test class dynamically, which means it got the test cases during run time.
So basically, your main should include only the gtest headers, ... |
65,074,080 | 65,155,189 | UDP Multicast is not working for linux Debian | Hi I have a UDP Multicast problem in my c++ code or in the Linux Debian environment.
I'm using boost 1.67.
Note: I'm using my code in both Windows and Linux. But in Linux it does not work but in Windows it works.
I can see the Multicast packages with netcat in Debian, so the multicast stream is there! Multicast is enab... | Actually I found that if I bound the multicast port to the nic IP 192.168.0.1 then it only worked in Windows. But if I bound the multicast port to the IP 0.0.0.0 it also worked in Linux.
Then I just joined the group with:
Socket->set_option(boost::asio::ip::multicast::join_group(Multicast_Address));
|
65,074,940 | 65,075,006 | Avoid memory leak with delete in C++ | I have the following code :
class A{
A(){};
};
class B{
A **a;
public:
B(){
a = new A*[10];
}
~B(){
delete[] a;
}
};
int main()
{
B* b1 = new B();
//delete B;
return 0;
}
I would like to know what is the proper delete for dynamic object b1 in main? ... |
we don't need to add a delete in main since the object B as a dynamic array of pointers and calls the destructor on return. Is that right?
No, that's wrong.
If you allocate something with new and don't deallocate that pointer with delete, then the allocation will leak.
P.S. B is very unsafe because it is copyable, bu... |
65,075,379 | 65,077,124 | Infinite loop after input | so I've been doing my homework and I stumbled upon a problem. After I input part of the date for my program it just goes into an infinite loop. The idea is to create an array that consists of structure entries. I'm not sure where the problem seems to be coming from since it just starts printing out "Your choice: " with... | Use cin.ignore() when you are about to use getline after using cin. Because cin leaves the null character in the buffer.
|
65,075,535 | 65,075,604 | Derived Get/Set Methods | Imagine I have this code:
class A {
public:
void GetInt() { cout << number << endl; }
void SetInt(int n) { number = n; }
private:
int number = 0;
};
class B : public A {
public:
void GetInt() { cout << number << endl; }
private:
int number = 0;
};
int main() {
B b;
b.SetInt(5);
b.GetInt(); // Pr... | The simple way to get what you ask for is this:
class A {
public:
void GetInt() { cout << number << endl; }
void SetInt(int n) { number = n; }
private:
int number = 0;
};
class B : public A {
// don't hide methods inherited from A
// don't add members that are already present (as private member of A)
... |
65,075,590 | 65,075,863 | How to call a random function of a class in c++? | I am trying to create a command-line game in C++. I am new to it and just started learning.
My game consists of a player class and a dragon class. The classes are declared in separate header files.
What I would like to know is, if there is a way to call a random function of a class after declaration.
Like
// ignore the... | I am a beginner myself and I am sure there are much easier/better solutions than mine.
You can try it with cases.
int random_val = rand();
int nr = random_val % 3;
switch (nr) {
case 0: bar.func1();
break;
case 1: bar.func2();
break;
case 2: bar.func3();
break;
defau... |
65,075,867 | 65,076,282 | terminate called without an active exception when calling pthread_exit in segmentation fault handler | How are you?
I am going to fix the segmentation fault in a worker thread on Ubuntu 18.04.
My code is the following.
#include <thread>
#include <signal.h>
#include <string.h>
#include <pthread.h>
#include <opencv2/opencv.hpp>
void sigsegv_handler(int signum, siginfo_t *info, void *data)
{
printf("The thread was cra... | The simple answer is you can't do this:
void sigsegv_handler(int signum, siginfo_t *info, void *data)
{
printf("The thread was crashed\n");
pthread_exit(NULL);
}
First, per 7.1.4 Use of library functions, paragraph 4 of the C 11 standard:
The functions in the standard library are not guaranteed to be reentran... |
65,075,871 | 65,076,083 | Sharing common code between derived classes in C++ | I'm having trouble when trying to share common code between derived classes in the below example:
class BaseWrite {
public:
virtual void setup() {}
};
class Write : public BaseWrite {
public:
void show() {
cout << "Show Write" << endl;
}
virtual void print() {
cout << "print Wri... | If CompWrite has access to all public functions in SpecialWrite then a multiple inheritance could solve the problem, but both classes inherit from Write so the inheritances must be changed to virtual, the CompWrite class will look like:
class CompWrite : public Write, public SpecialWrite {
If the setup() function is t... |
65,076,094 | 65,079,117 | Passing float[] from C++ to Java using JNI | I am attempting to "pass" (i.e. copy) a raw float array from C++ to Java.
The C++ structure holding the source array:
struct foo_cpp {
float a[16];
};
The Java class holding the destination array:
public class foo_java {
public float a[];
public foo_java() {
a = new float[16];
}
}
The C++ fun... | The code mentioned in the question turned out to work as expected. The float values where correct and it was a classic case of misinterpretation / layered problems.
However, as @Michael pointed out in the comment: A call to ReleaseFloatArrayElements() is necessary to prevent leaking memory.
I've created a blog post reg... |
65,076,447 | 65,076,525 | Custom Class std::map Weird Behavior | I'm getting a weird behavior when searching for a key in a map with a custom class I created as keys.
It seems that it doesn't find the keys although they are present in the map.
Anyone knows the reason for this?
Code (can run it here):
#include <iostream>
#include <map>
using namespace std;
typedef short int dimensi... | Your operator< is flawed:
bool operator<(const Point &other) const {
if (m_x < other.m_x) return true;
return (m_y < other.m_y);
}
For example
{0, 3} < {1, 2} -> true
but
{1, 2} < {0,3} -> true
The operator< must implement a strict weak ordering. You forgot to consider the case when (m_x > other.m_x) wh... |
65,076,600 | 65,076,879 | Passing object to a function in lambda std::thread (C++): attempt to use a deleted function | I'm trying to do something like this:
class A {
private:
std::mutex my_mutex;
public:
void A_function(){
some work with the mutex;
}
};
void B_function (A a){
a.A_function();
}
int main () {
A a;
std::thread t([&a]{
B_function(a); // error here
});
t.joi... | std::mutex is not copyable, therefore, you naturally cannot copy an object of type A, which has a subobject of type std::mutex.
As a workaround, you can pass an argument to B_function by reference instead of by copy:
void B_function (A& a)
{
a.A_function();
}
Don't know though whether it suits your needs to work ... |
65,076,611 | 65,076,687 | Why new visual studio take string literals as pointer to constant? | I have this constructor for my class student.
student::student( char* rollno , char* name , date dob) :
rollno(rollno), name(name),dob(dob)
{
}
When I write
student s1( "l1f18bscs0322" , "usama" , { 13,7,1998 });
in main, it accepts it in my university I think because its using Visual studio 2013, but It gives e... | Because it is!
The type of a string literal, in C++, is const char[N] (where N is the length of the string including its null terminator). That decays to const char*, not char*.
In earlier versions of C++ (pre-2011), you were permitted to "forget" the const for compatibility with C, though doing so was deprecated (and ... |
65,077,006 | 65,077,092 | How should I write a copy constructor to initialise another object? | Say, as a simplified example, I have a class object House which also has an object Kitchen.
Here is the header file:
class Kitchen {
private:
int width;
int height;
int length;
public:
Kitchen(int width, height, length); // default constructor
};
class House {
private:
int h... | Firstly, your "default constructor" in Kitchen is not a default constructor, it is a user-defined constructor. It should initialize the members, and also I would re-enable copy and move behavior following the rule of five.
class Kitchen {
private:
int width;
int height;
int length;
public:
... |
65,077,105 | 65,080,995 | How to run different while loops without breaking any | How to run two different while loops without breaking one?
The program does two different collects of values from a PLC (Programmable Logic Controller) via while loop.
And this collects should be at the same time, but when I try to run both of the loops, they break... The first loop simply stop returning any value, whi... | Your program needs to connect, read and disconnect from two devices, however, it can only have one connection open at a time. Thus, the connections are mutually exclusive. You could use a mutex for that.
Your code suggests, that one connection should be polled indefinitely with a certain timeout, and the other on reque... |
65,077,574 | 65,077,850 | C++ - Longest palindromic prefix in the word | I am a beginner in C++, so it may be a stupid mistake. So, I wrote the following code to find longest palindrome in any word:
#include<bits/stdc++.h>
#include<string>
using namespace std;
bool IsPal(string str)
{
int length = str.length();
if (length < 1) return true;
else if (str.at(0) == str.at(length-1)) {st... | Here
for (int j = 0; j < n; j++)
{
string sub = x.substr(0, j);
You are taking substrings of the input strings starting from the first character till the j-th and j goes from 0 till n.
However, n is the number of test cases, wich is 8 in your example (output is 7 because of j < n). You probably want j to loo... |
65,077,814 | 65,078,258 | What is the difference between non-type template parameters in C++17 and C++11? | Consider this code:
using func = int (*)(int, int);
template<func F>
void do_something(int first, int second) {}
int something(int first, int second) { return 42; }
void f()
{
constexpr auto function = something;
do_something<function>(10, 20);
}
Which is compiled and run with C++17 standard compatible compil... | The relevant difference is in the requirements on allowed template arguments (not template parameters) in [temp.arg.nontype].
C++11:
A template-argument for a non-type, non-template template-parameter shall be one of:
...
a constant expression that designates the address of an object with static storage duration and ... |
65,077,900 | 65,078,039 | Last symbol is duplicated in LZW | I tried implementing LZW encoding/decoding and ended up with the following code
#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
using Index = std::int16_t;
void encode(std::istream &input, std::ostream &output) {
Index index{0};
std::unordere... | As @NathanOliver pointed out in the comments
changing the decode loop to
while (input.read(reinterpret_cast<char *>(&k), sizeof(Index))) {
fixes it.
|
65,078,748 | 65,078,825 | How to check if a template pair has value | i'm coding a trie structure in C++ with a template snippet:
pair<char,T>
I have a method void empty() in which I want to check, whether the root's second value is not set (value is equal to default constructor value or in detail: values would store other pair types.). I know that the default constructor would apply 0 ... | A std::pairs member cannot be "not set".
You can use std::optional to model an optional value.
"...value is equal to default constructor..."
Of course you can check if the current value equals the initial one:
std::pair<int,int> x;
if (x.first == 0) {
std::cout << "value of x.first is that of a default construct... |
65,079,143 | 65,081,473 | Reverse For loop skips over completely if there is only one entry? | I have an array I am reverse looping through. However, it seems if there is only one entry in my array, it doesn't loop at all.
for (uint8 i = fileNames.Num() - 1; i --> 0;)
{
//Do stuff
}
Can anyone tell me why that is? Or what I can do to fix the loop conditions?
| The code you posted means the same thing as the following:
uint8 i = filenames.Num() - 1
while ( (i--) > 0) {
//do stuff
}
If filename.Num() is 1 then the loop body does not execute because 1 - 1 is not greater than zero.
This expression i --> 0 is not idiomatic C++ and has no place in real code. It is a programmin... |
65,079,377 | 65,079,869 | I'm trying to overload << operator and print out emp.name | I am trying to make a linked list. I have 3 classes - Employee, ListOfEmployee, and NodeofEmployee. All of the functions are stored in a header file.
Employee class
class Employee {
friend class NodeofEmployee;
public:
Employee();
Employee(string n, double s);
private:
string name;
... | So there are (at least) two errors here
ostream& operator <<(ostream& outputStream, const ListOfEmployee& e) {
NodeofEmployee *newpptr = e.head;
while (!e.head) {
outputStream << newpptr;
}
return outputStream;
}
The first error is the newpptr is not an Employee, it's a NodeofEmployee pointer.... |
65,079,471 | 65,091,766 | C++ 17: Using alias template bug in gcc? | Snippet:
#include <functional>
template <typename T>
struct CallableTrait;
template <typename R, typename... Args>
struct CallableTrait<std::function<R(Args...)>>
{
using ReturnType = R;
};
template <typename Callable>
using CallableTraitT = CallableTrait<decltype(std::function{std::declval<Callable>()})>;
tem... | The issue is tracked here gcc-bugzilla
|
65,079,491 | 65,079,851 | from std::vector of 3 into a pcl::PointCloud<PointXYZ>::Ptr? | I have a point cloud of obstacles, because I used vectors of vector in my binary tree, I'd like to insert the values in std::vector of 3 elements into a pcl::PointCloud::Ptr object to do clustering.
std::vector<std::vector<float> > points;
typename pcl::PointCloud<PointXYZ>::Ptr cluster(new pcl::PointCloud<PointT>);
//... | Most likely something like
for (int j=0; j<points.size(); ++j) {
std::vector<float> &vec = points[j];
for (int i=0;i<vec.size();i+=3)
cluster->push_back(PointXYZ(vec[i], vec[i+1], vec[i+2]));
}
I am assuming every 3 value in the inner std::vector<float> is a point.
|
65,080,168 | 65,080,600 | How to set a value at memory offset from a const void pointer? | I have a pointer returned from a function
rs2::video_frame frame = frames.get_color_frame();
const void* data = frame.get_data();
I know that this pointer is an array of RGB values (i.e. 3 chars) of size frame.get_data_size().
How can I modify certain pixel colors given that
int bpp = frame.get_bytes_per_pixel();
int ... | You would have it easier if you would have an object oriented approach:
struct Pixel {
short red;
short green;
short blue;
};
Let your frame work with an std::vector<Pixel> pixels; which is returned by reference. std::vector<Pixel>& get_data();
pixels[y * width + x].red = newRed;
pixels[y * width + x].gree... |
65,080,222 | 65,080,290 | Compile error while sorting array of custom structs | I made this simple example for sorting an array of my custom struct s. It has an operator< function, and, according to cplusplus.com, this is all that's needed to sort.
#include <algorithm>
struct s {
int number;
bool operator<(s& other) {
return this->number < other.number;
}
};
int main() {
... | std::sort takes iterators as parameters not elements of the array.
Consider that this cannot work to sort an array:
int a[] = {1,2,3,4}; // the array
std::sort(1,4); // pass first and last element to sort...urks
Pointers to elements in c-arrays are iterators, you can get them conveniently with std::begin and st... |
65,080,316 | 65,080,586 | How to switch SQL Database at runtime with model | So I connect to a database like this:
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("database.db");
db.open();
QSqlTableModel model;
This works fine the model points to the db connection. which is the default connection. See the constructor here:
QSqlTableModel::QSqlTableModel(QObject *parent = nullpt... | Yes, you must create another model since the model is based on the database passed by the constructor.
|
65,080,354 | 65,080,402 | expected primary-expression before β.β token | I am fairly new to classes. I created a class called Counter which basically creates a counter object and has certain data members and function members associated with it.
The header file for the class is:
#ifndef c
#define c
#include <iostream>
#include <string>
#include <vector>
using std::vector; using std::string... | What is c? You've defined it as nothing and then you use
c.log_.push_back(...)
Which the preprocessor changes to
.log_.push_back(...)
I'm not sure what you're trying to do but the error clearly states it's looking for an expression before the period, where it appears you have none.
|
65,080,626 | 65,080,883 | How to cin to a back_inserter or any inserter in c++? | So I was thinking of simplifying this snippet
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> A;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) {
int tmp;
cin >> tmp;
A.push_back(tmp);
}
}
And because ... | You could read into a temporary variable.
for (int k, i = 0; i < n; i++) cin >> k, back_inserter(A) = k;
# or nicer:
for (int i = 0; i < n; i++) {
int k;
cin >> k;
back_inserter(A) = k;
}
You could provide the missing overload and read into temporary variable in it:
template<typename T>
std::istream& op... |
65,081,259 | 65,081,785 | Payload data with aligned unique_ptr | I have unique_ptr<T> which is always aligned to 4096 - means the lowest 12bits of the pointer value are always equal to 0. My intension is to store a byte of payload data / metadata "in within the pointer itself". I mean to create a class which will have a move converting constructor like:
template<typename T>
struct P... | You could create something similar to unique_ptr but storing the pointer as a std::uintptr_t and cast and filter out the payload when needed.
Here's an outline what it could look like:
#ifndef __cpp_aligned_new
#error "Requires Dynamic memory allocation for over-aligned data (http://www.open-std.org/jtc1/sc22/wg21/docs... |
65,081,377 | 65,081,423 | Why can't my class access its own privately declared variable of another object | I am getting the following error
game.cpp:19:35: error: βPlayer Game::p1β is private within this context
19 | Point playerMove = tictactoeGame.p1.makeMove();
| ^~
In file included from game.cpp:1:
game.hpp:12:10: note: declared private here
12 | Player p1;
Followed by 3... | As the commenters have pointed out, the lines of code causing the error are within the main function, which, as a standalone function, cannot access private variables of the class. Only methods of the class can access private variables.
|
65,081,466 | 65,115,211 | Is it true that ill-formed program does not always lead to UB (either at compile time or at run time)? | Follow-up for:
Difference between Undefined Behavior and Ill-formed, no diagnostic message required
What is the C++ compiler required to do with ill-formed programs according to the Standard?
Is the following table correct?
===== leads to UB ====
program compile time run time
well-formed ... | If a program is ill-formed, a conforming implementation which has adequate resources to process it would be required to issue a diagnostic. Once an implementation has done so, anything it might do after that would be outside the Standard's jurisdiction. Some possible outcomes would be:
Terminate processing after out... |
65,081,568 | 65,081,644 | How std::shared_ptr is deallocated? | When does memory deallocation occur in the code below?
#include <memory>
int main()
{
auto p = std::make_shared<int>(5);
std::weak_ptr<int> wp = p;
p = nullptr;
return wp.lock() == nullptr ? 0 : 1;
}
As follows from this post std::make_shared performs one heap-allocation. Does this mean... | (Had to edit the answer since I have not read the question properly).
Yes, the memory itself will be around in your snippet, since you have allocated a single block for both control block and the object via make_shared call.
|
65,081,686 | 65,085,321 | Calling A Loop Inside Of A Form | When I call a for (;;) loop it just makes my program not respond.
Im attempting to call a loop for keypress checking.
Such as
for (;;)
{
if (GetAsyncKeyState(VK_NUMPAD0) & 1)
{
UpdateTest(); // <- A void that I created to update some words
}
}
I've called this function inside of Form_Load - and it stops... | You cannot add an infinite loop to the processing of the UI. This will cause the UI to stop processing subsequent messages and then lose response. Instead, handle the keydown event.
Do I place the event's inside of Form_Load?
No. You could add the KeyEventHandler like:
C#:
public Form1()
{
InitializeC... |
65,081,765 | 65,082,035 | What determines whether a constexpr function is a constant expression? | (compiler used is gcc with c++17 as far as I know (difficult to find this in visual studio))
#include <iostream>
using namespace std;
void increment( int& v )
{
++v;
}
int constexpr f()
{
int v = 0;
increment( v );
return v;
}
int main( )
{
cout << f( ) << '\n';
}
The above code gives the error... | Both programs are "ill-formed no diagnostic required", per [dcl.constexpr]/6:
For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression,... |
65,081,802 | 65,099,771 | Qt5 MySQL driver not loaded - Windows | I want to connect to a MySQL database, only every time I try I get this error:
QSqlDatabase: QMYSQL driver not loaded
I tried to install MariaDB-Connector-C and MySQL-Connector-Cpp, but neither of them worked, I also tried to copy the file libmariadb.lib in the application build folder but it still gives error and I d... | After I did everything I described in the edit I solved it. Basically I went to QtCreator, added a new library to the project (C:\Program Files\MySQL\MySQL Connector C 6.1\libmysql.lib) and now everything works properly!
|
65,081,969 | 65,189,380 | Python 3 Import error AttributeError: '_ModuleLock_' object has no attribute 'name' when script invoked from c++ | I am having a problem with embedding python script in my c++ code. It's very similar to this one: Python 3 Import error AttributeError: '_ModuleLock_' object has no attribute 'name' although there was no c++ code involved. Btw that issue was never resolved. Here is standar c++ code, nothing unusual there:
PyRun_Sim... | Ok so after a few days I finally resolved the issue. It turned out to be similar to the issue with IDLE. In my case it was tracing function that tried to access arguments of each function call at print them, thus tried to use repr function before the object had been initialized.
|
65,082,918 | 65,087,105 | openmp optimization with return condition | I'm new to OpenMP parallel programming and finding it difficult to optimize my function, which should return -1 in case a column is empty.
Here is my function.
The source matrix has some values, and norm_matrix is constructed as a diagonal matrix where each column holds the maximum value from the corresponding column o... | When norm_matrix[col * size + col] == 0 you would get a dividing by zero error on the statement (1 / norm_matrix[col * size + col]);. Assuming that when the flag = -1 you should exit the parallel region completely, you should use #pragma omp cancel for
int statistic_norm_matrix(double* source_matrix, double* norm_matri... |
65,083,094 | 65,083,129 | Question about template's value_type usage in Stroustrup's book example | In Stroustrup's "A Tour of C++" there is a code snippet
template<typename C>
using Value_type = typename C::value_type; // the type of Cβs elements
template<typename Container>
void algo(Container& c)
{
/* (1) */
Vector<Value_type<Container>> vec; // keep results here
// ...
}
Why we need this using, h... | The reason is this declaration:
Vector<Container::value_type> vec;
is not actually valid, and is an error. Instead you need to write:
Vector<typename Container::value_type> vec;
which is more verbose.
The purpose of the alias template Value_type is to make it more convenient to use a member type alias of Container wi... |
65,083,141 | 65,128,640 | Dereferencing a temporary pointer to initialize a reference member variable | I am working with an external library which can hold large data structures. Calls to it return pointers to objects which it manages:
class ExternalLib {
public:
int* GetLargeObject() { return &large_object; };
private:
int large_object = 1;
};
I am trying to write a wrapper for this external library which can hol... | A temporary is materialized when binding a reference when the initializer is a prvalue or when type of the initializer differs from the type of the reference by more than cv-qualifiers but can be converted to it (unless of course that conversion is user-defined and yields a reference). (This case is rejected in the ca... |
65,083,496 | 65,083,812 | How to put variadic arguments to vector of elements with inheritance? | I use c++ 17 and have the next set of classes
class A {
public:
virtual void fun() = 0;
};
class B : public A {
public:
void fun() override {
}
};
class C : public A {
public:
void fun() override {
}
};
I would like to have a function process that accepts variable list of variables and returns a ... | This is a good use case for fold expressions.
#include <memory>
#include <iostream>
#include <vector>
class A {
public:
virtual void fun() = 0;
};
class B : public A {
public:
void fun() override {
}
};
class C : public A {
public:
void fun() override {
}
};
template <typename T, typename... Arg... |
65,083,544 | 65,083,627 | Format no such file or directory | I was trying to use the C++ format utility (std::format). I tried to compile this simple program:
#include <format>
int main()
{
std::cout << std::format("{}, {}", "Hello world", 123) << std::endl;
return 0;
}
When I try compiling with g++ -std=c++2a format_test.cpp, it gives me this:
format_test.cpp:1:10: fat... | According to this: https://en.cppreference.com/w/cpp/compiler_support there are currently no compilers that support "Text formatting" (P0645R10, std::format). (As of December 2020)
The feature test macro defined by that paper is __cpp_lib_format (also listed here), so you can write your code like this to check:
#if __... |
65,083,936 | 65,099,318 | Program does not read string correctly | I recognize the user's appdata folder and add the name of the vbs script there
SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pAPPData);
SHGetPathFromIDList(pAPPData, szAPPData);//appdata path
std::string cometa = szAPPData + slashrat += vbsname;//fullpath
LPSTR scometa = const_cast<char*>(cometa.c_str());//string t... | YAAAAAAY,i fixed it.
1.converting string to char*
char* ccometa = new char[cometa.length() + 1];
strcpy(ccometa, cometa.c_str());
converting char* to tchar
TCHAR Tccometa[512];
_tcscpy(Tccometa, A2T(ccometa));
Profit:D
|
65,084,116 | 65,085,308 | How to set up and dereference a generic pointer for a derived class object for an expression parser? | I could not find a solution to the following problem -
I have a base class
class foo{
public:
foo *lhs, *rhs;
foo() {}
};
I derive a templated class :-
template <typename T>
class bar : public foo {
public:
T x;
bar(x){this->x = x;}
}
Then I do the following -
void main(void)
{
bar <std::string> ... |
Is there a way to access objects of the derived class using pointers of type base class?
Yes, it is called a downcast. You usually want to avoid it since it needs you to store type information about each object, which defeats the purpose of upcasting to the base class in the first place. It can be done by dynamic_cas... |
65,085,354 | 65,115,379 | Whisper simulator for RISC-V: C++ Program either gets caught in infinite loop or get aborted | I have a multi-file (3 .cpp files and 2 .h files) C++ code that uses new, new[], delete, and delete[] operators to allocate large chunks of memory and performs some floating point operations (requires division by sqrt()). The program compiles and runs well with regular g++ and produces the required output. I now want t... | Thanks Scheff, Peter Cordes for providing some accurate pointers. It indeed turned out that I had made out-of-bounds-access error in my code as detected by Valgrind; though I have to admit I bothered the developer of Whisper Simulator and he was kind enough to help.
The steps for resolution are as follows:
Remove bug ... |
65,085,757 | 65,086,089 | Converting tm to time_t on windows in UTC - _mkgmtime returning -1 | I am trying to parse UTC ECMA date format strings into a std::chrono::system_clock::time_point on Windows.
My plan:
Use scanf to load the string into a struct tm
Use _mkgmtime to turn that into a time_t (I am using _mkgmtime for this, because it uses UTC time, unlike something like mktime, which uses local time).
Use ... | In a tm structure the member tm_year is the number of years since 1900. Feeding in 2020 means you're actually providing year 3920.
It looks like _mkgmtime hates that year. On my system _mkgmtime64 doesn't appear to work either. It should fit in a 64 bit time_t, but definitely out of range for the 32 bit version. I can'... |
65,085,965 | 65,085,990 | Why my program keeps looping even when I put a break statement | I am trying to make a log book program but I encountered this problem. It always loops even when there is a break statement.
Here is the part where I use a break statement on while loop but it keeps looping endlessly.
void userPrompt(){
while(true){
cout << "[1] Log in\n";
co... | All of your break statements are inside of a switch. So they are breaking out of the switch and back into the while loop (which then loops endlessly).
The switch statement will fall-through to the other case statements unless you place the break, so those break calls are just terminating that particular case.
You need ... |
65,086,114 | 65,086,860 | C++17 -- mapping types of member variables to std::optionals | How could I take some structure:
template<typename T>
typedef struct something_t {
int x;
int y;
T z;
} something_t;
And create a utility type (possibly combined with some macros) which maps it to the same-shaped structure, but full of std::optionals instead. In other words, how would I write the partial struct ... | If you control the definition of something_t, you can change it this way:
template <template<typename> typename Wrapper, typename T>
struct new_something_t {
Wrapper<int> x;
Wrapper<int> y;
Wrapper<T> z;
};
Then define a alias:
template <typename What>
using Id = What;
Now your original something_t<T> becomes ... |
65,086,382 | 65,086,635 | Inlining struct member | I have a struct Foo which contains a nested struct Bar. These structs only contain POD types. My problem is that the size of Foo is larger than it would have been if I copied all the members of Bar:
#include <iostream>
#include <string>
struct Bar {
double a;
long long b;
int c;
};
struct Foo {
Bar b;... | We must allow the member to be a potentially-overlapping subobject. There are two ways: 1. Instead of using a member, inherit from Bar or 2. Use the attribute [[no_unique_address]] (C++20).
Technically, being potentially-overlapping is sufficient to allow the compiler to re-use the padding. However, unfortunately being... |
65,087,134 | 65,093,209 | How to design an "Awaitable" base class? | The C++ standard library in many places offers a kind of "awaitable" API: e.g. std::future and std::condition_variable can instantly "try" to get their value, "wait" undefinitely for their value, "wait_for" a certain std::chrono::duration, or "wait_until" a certain std::chrono::time_point is reached. I am struggling to... | I think your third way might be the way to go. In doubt, you have to apply some effort to limit possible misusage.
You can also take a look at the acyclic visitor pattern:
https://en.wikipedia.org/wiki/Visitor_pattern
Acyclic Visitor C++
For some scenarios, the implementation way provided by Andrei Alexandrescu (can re... |
65,087,455 | 65,088,100 | Kill a process created with _spawnvp() | The Windows version of a program starts a process with
char * argv[..];
intptr_t childHandle = _spawnvp( _P_NOWAIT, "executable.exe", argv );
which works. The documentation says: "The return value from an asynchronous _spawnvp (_P_NOWAIT specified for mode) is the process handle." and thus I assume there should be als... | _spawnvp returns a process handle, if you use it with the _P_NOWAIT argument. Using the Win32 API you can terminate the process:
UINT exitCode = 0;
intptr_t handle = _spawnvp(_P_NOWAIT, "executable.exe", argv );
if(TerminateProcess((HANDLE) handle, exitCode))
{
// successful termination
}
|
65,087,491 | 65,087,998 | Trying to find all prime numbers in a list | the output
The program is checking every number in the list and should output if is prime or not. Probably I just don't get the prime algorithm right.
Currently outputs that no number is prime.
void primList(struct node* stnode)
{
struct node* pr = stnode;
int i;
... | In general such questions (seeking debugging help) are discouraged, see on-topic.
In this case the minimal change to fix this code would be:
void primList(struct node* stnode)
{
struct node* pr = stnode;
int i;
bool primNum = true;
if (stnode != NULL)
... |
65,087,919 | 65,088,078 | How to include bigger board into smaller one? c++ | id like to include smaller pieces, like in a pic below, into this board, and i have no idea how.
void O()
{
for(int i = 0; i<2; i++)
{
for(int j = 0; j<3; j++)
cout<<"O";
cout<<endl;
}
}
void Draw()
{
system("cls");
int z = 10;
for (int i = 0; i < height; i++)
{
if ... |
Figure out how many lines your board display is.
Figure out how many characters your board display is.
Create a loop that repeats for the number of lines you have.
In the loop, look at the line number and determine which type of line it is. Write a separate inner loop for each type of line.
If it's the first, second t... |
65,088,081 | 65,088,171 | I cant get the right result from my code, getting odd outputs | I'm trying to write a dice algorithm and count the number of every number that could my dice could roll, but getting odd and wrong result. what is the problem with this code.
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
cout << "Enter the number of dice: ";
int n;
int number[5];
... | Firstly, isnt it simpler and easier to do
number[dice-1]++;
instead of 6 if's.
To fix the problem u have to move number array before Main (if u declare it in Main it has random numbers inside it), U can also do this before running first loop, instead of replacing array declaration.
for (int i=0; i<6; i++)
numbers[i... |
65,088,392 | 65,092,559 | Executing a function on a specific thread in C++ | I have a class which has some of its functions thread-safe.
class A
{
public:
// Thread Safe class B
B foo;
// Thread specific class C
C bar;
void somefunc()
{
// uses foo and bar
}
}
class C
{
public:
C()
{
m_id = std::this_thread::get_id();
}
// ... |
I was thinking of executing somefun by submitting somefun to the thread identified by m_id.
That is not how threads work in general. You can't ask just any thread to stop what it is doing and call a certain function. The only way that it makes sense to submit anything to a thread is if the thread is already running c... |
65,088,775 | 65,089,127 | Random string generator in c++ returns the same value in loops | I have a function that generates random string in my program and that works as I want, but only separately from loops.
When I use it in loop in main(), it returns the same string every time (let's say 20 for example).
Here is that function:
string randomString()
{
string c;
int r = NULL;
int num = 7;
srand(time(NULL));... | As the commenters pointed out, srand() sets up the random number generator, and seeds it with it's initial value. As such, it should only be used once per program, befor any uses of rand().
In this case, the call to srand() should be taken out of randomString() and put somewhere before the first call to rand(), probabl... |
65,089,262 | 65,089,413 | Failing to create a std::ranges::iota_view with value and bound | I tried to create a std::ranges::iota_view with a value and a bound:
#include <ranges>
#include <vector>
int main() {
std::vector v{1,2,3};
auto indices = std::ranges::views::iota(0, v.size());
}
link to program on godbolt
But clang 11.0.0 fails to compile with the error message:
no viable constructor or deducti... | From https://en.cppreference.com/w/cpp/ranges/iota_view
Note that the [deduction] guide protects itself against signed/unsigned mismatch bugs, like views::iota(0, v.size()), where 0 is a (signed) int and v.size() is an (unsigned) std::size_t.
This will work:
auto indices = std::ranges::views::iota(0u, v.size());
... |
65,089,595 | 65,092,335 | Lazy combinations of c++ ranges view | I am looking for an implementation of a ranges view that lazily creates the k combinations of a given range.
For example the range {1, 2, 3} with 2 combinations should return:
std::vector v {1,2,3};
auto rng = ranges::views::combinations<2>(v);
for(auto[a,b] : rng)
std::cout << a << ' ' << b << '\n';
// 1, 2
// 1, 3
... | Make "everything" lazy
Totally untested code
auto lazycombo = [values, comb_size]() mutable {
bool ok = next_combination(values.begin(), values.begin() + comb_size, values.end());
return std::span(values.begin(), values.begin()+comb_size);
}
see next_combination.
Now using your
auto combinationIdx = ranges::views... |
65,089,835 | 65,089,942 | If Namespaces can only have a Global Scope how can there be Nested Namespaces? | I read these 2 pieces of codes and their descriptions and thought that they were clashing with each other.
Namespace definition can appear only in a global scope.
void f()
{
namespace space1{
}
}
// So this is not allowed as space1 is local to f()
Namespaces can be nested
namespace namespace1{
int... | Because your quote is wrong. A more correct description would be:
Namespace definitions are only allowed at namespace scope, including
the global scope.
https://en.cppreference.com/w/cpp/language/namespace
|
65,090,346 | 65,090,394 | Convert ASCII char to uint8_t C++ | I have a char variable AA:
char AA = 'E'; //0x45 HEX
I need to convert variable AA to the same form as the array (uint8_t), after converting I will insert it into an array:
uint8_t arr[] = {0x23, 0x24, 0x25, **AA**};
Please help with converting.
| Use a static_cast, ie.
static_cast<uint8_t>(AA)
|
65,090,626 | 65,107,490 | error C2440: 'static_cast' : cannot convert from 'void (__thiscall Visualizza::* )(char [])' to 'AFX_PMSG' | Can someone help me?
I'm doing an MFC application via VS 2010 ultimate.
ps. im new withth c++.
This application is for print on a combox filenames.
this is the .cpp file
BEGIN_MESSAGE_MAP(Visualizza, CDialogEx)
ON_CBN_SELCHANGE(IDC_COMBO1, &Visualizza::OnCbnSelchangeCombo1)
END_MESSAGE_MAP()
// Visualizza messag... | Registering notification handlers is explained in the Remarks section of the CComboBox documentation. In particular, the following needs to be followed:
The parent's function prototype is as follows:
afx_msg void memberFxn( );
In other words: Your user-supplied notification handlers cannot take any arguments.
void V... |
65,090,761 | 65,091,588 | Using different functions for Windows 7 and Windows 10 in dll | I created dynamic library(dll) which is using function GetScaleFactorForMonitor from windows API. However this function was introduced in Windows 8.1 and those dll won't load at Windows 7 obviously. I am thinking about the solution to have two versions of the same method in one dll and use it according to Windows versi... | You basically need something like this:
typedef HRESULT CALLBACK GETSCALEFACTORFORMONITOR(HMONITOR hMon, DEVICE_SCALE_FACTOR* pScale);
...
HMODULE hm = LoadLibrary("Shcore.dll"); // GetScaleFactorForMonitor is here
GETSCALEFACTORFORMONITOR* pGETSCALEFACTORFORMONITOR = NULL;
if (hm)
{
pGETSCALEFACTORFORMONITOR... |
65,090,828 | 65,091,365 | Problem for dynamic memory allocation in c++ | while i am trying to solve a hackerrank problem,i had a problem in my mind.My problem is i want to allocate some memories with pointers and i made this with two ways,but one of them resulted with the problem.Other one has no problem.
Hackerrank problem is here 1.
enter image description here
Hackerrank problem is here ... | You are trying to make a matrix (2-dimensional array) from an array. You should write like that:
int **matrix = new int*[x]; //pay attention to number of asterisks
for(int i = 0; i < x; ++i)
{
matrix[i] = new int[z];
}
int *arr[x] is similar to int **matrix = new int*[x]. It creates an array of x arrays with undefin... |
65,091,012 | 65,093,104 | How to split an image into M x N tiles | How can I split a Mat object/image into M x N equal pieces and store the pieces from left to right and from top down, into a Mat vector using OpenCV and C++?
Many thanks
| Inline with the solution given here for the opposite problem, this should do it:
#include <opencv2/opencv.hpp>
std::vector<cv::Mat> splitImage( cv::Mat & image, int M, int N )
{
// All images should be the same size ...
int width = image.cols / M;
int height = image.rows / N;
// ... except for the Mth column ... |
65,091,056 | 65,103,034 | SetWindowDisplayAffinity not works in MFC windows | I have 1 Picture Control and want to make it not screen record-able.
In .Net, I have been using SetWindowDisplayAffinity:
WDA_MONTOR = 1;
SetWindowDisplayAffinity(this.Handle, WDA_MONTOR);
Now I have moved to MFC for native performance.
I am using this following code which don't prevent screenshots:
HWND Handle = thi... | According to Raymond chen:
The .NET version was passing the form's window handle (a top-level window), but your MFC version is passing a control's window handle (a child window). Use the top-level window.
That's mean I would have to use Form handle instead of PictureBox handle.
So change
HWND Handle = this->GetDlgIte... |
65,091,439 | 65,102,946 | Set UI Language Windows with SetLocaleInfo | I want to change the default language for windows system. From powershell, there is a way to do this using
Set-WinUILanguageOverride -Language de-DE (Changes language to German)
However, I am looking for a win32 api call for same. Tried SetLocaleInfo , but it wasn't working.The following code prints 0 as the SetLocaleI... | As @Petesh said, The two LCType you used are invalid for the SetLocaleInfo function,and there is no valid flag for SetLocaleInfo that can set the UI language of windows system.
According to the User Interface Language Management:
User UI Language
To retrieve the user UI language, an application can call GetUserDefault... |
65,092,131 | 65,092,460 | Access Violation when using struct | I'm trying to hook OpenSSL's int SSL_connect(SSL *s) method. OpenSSL 1.0.2l version.
Here's the source code:
SSL_connect
SSL structure
SSL_SESSION structure
GOAL:
Printing out any SSL_SESSION member (like ssl_version or master_key)
THE PROBLEM:
I get Access Violation Exception when trying to access the SSL *s parameter... |
I don't think I must map all of the members of SSL and SSL_SESSION, because I found that SSLHook library doesn't do this
If you take a closer look you see, that they do not map everything but they keep the member order and they duplicate all members up to the "point" in the struct that is relevant for them. Ignoring ... |
65,092,609 | 65,092,789 | problem with compiling a simple program with c++ | I am really new to C++. I am trying to compile this simple program but I get an error
#include <iostream>
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
}
The error th... | You can try specify namespace like this ->
#include <iostream>
using namespace std;
EDIT 'must' replaced by 'can try'. It works but why !
|
65,092,969 | 65,093,008 | {-truncated-} in C++ | I'm solving a problem (https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem). I actually solved it, but it worked only on 4 tests. When I unlocked the testcase my program couldn't pass, I have seen this in input:
100
997 981 957 933 930 927 926 920 916 896 887 874 863 863 858 847 815 809 803 794 789 7... |
{-truncated-}
has nothing to do with the output. Its just Hackerranks way of saying (there are more values for the output than we want to show in this window)
|
65,093,371 | 65,094,719 | STM32 LCD Library Which Is Written By Me It Doesn't Work | I have written an LDC driver for STM32f3xx. Wiring is correct but LCD doesn't work. LCD shows only white squares so I think data pins doesn't work correctly or there are logical error. I use char because data is 1 byte actually.
Here are the function's tasks:
fallingEdge() : send to falling edge signal for the waking ... | Have you tried to do something like that:
static void send4BitMode(char data)
{
HAL_GPIO_WritePin(GPIOB, EPin, GPIO_PIN_SET);
HAL_Delay(1);
// delay of 100 MicroSec on my side
HAL_GPIO_WritePin(GPIOB, DataPin4, SET_IF(data & 0x08));
HAL_GPIO_WritePin(GPIOB, DataPin3, SET_IF(data & 0x04));
HAL_G... |
65,093,449 | 65,100,829 | boost::multiprecision::cpp_int is being copied then deleted every time I try and print it | When I print a cpp_int from Boost, it seems that the entire object is copied.
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using std::cout;
void* operator new(size_t size) {
void *memory = malloc(size);
cout << "New: " << memory << " " << size << "\n";
return memory;
}
int main() {
... | The way you mismatched malloc/new is invoking UB (as ubsan+asan will readily tell you).
==32752==ERROR: AddressSanitizer: alloc-dealloc-mismatch (malloc vs operator delete
#0 0x7fb58c15c407 in operator delete(void*, unsigned long) (/usr/lib/x86_64-lin
#1 0x564b19759014 in __gnu_cxx::new_allocator<char>::dealloc... |
65,093,457 | 65,093,489 | Passing function as a class's template paremeter with unknown type | I know we can do something like this:
void f1(){ printf("1"); }
void f2(){ printf("2"); }
template <void F()>
class A{
public:
void func(){
F();
}
};
int main(){
A<f1> a1; a1.func(); // printing "1"
A<f2> a2; a2.func(); // printing "2"
}
Then, is it possible without knowing the return and arg... | In C++17, you might simply use auto
template <auto F>
class A{
public:
void func(){
F();
}
};
|
65,094,320 | 65,094,482 | (How) can a dll call a function that is implemented in its loading program? | Usually we load a dll on windows and call it's functions which is marked as __declspec(dllexport), but can I call a function which is implemented in the loaded program from a dll?
Firstly speaking this can be done on Linux, check the question I asked earlier.
I wrote a test program to test this:
CMakeList.txt (sorry I'... | Since you are using late binding for your .dll, you might do the same thing for function defined in the executable. Just call GetProcAddress in the same way, using this process handle (as it is already in the address space). Here is some (pseudo) code:
auto proc = GetModuleHandle(nullptr);
auto get_e = reinterpret_cast... |
65,094,487 | 65,094,946 | C++ No matching constructor when using inheritance | I have code like this:
class A{
public:
int b;
};
int main()
{
A a{.b = 5};
}
And the program compiles.
However, when I add another class and I make A inherit that class (like below), it throws an error "no matching function for call to βA::A()β" (or "No matching constructor for initialization of A").
class ... | You are using feature "Designated initializers" which is available since C++20.
Also I can't reproduce this issue: https://godbolt.org/z/fz3PeP
note with C++17 gcc and clang just file an warning, msvc file an error
with C++20 it is fine on all three (msvc needs c++latest option).
with C++14 it files error everywhere
... |
65,094,491 | 65,094,755 | Write integers and read them back from binary file in C++: number of bytes mismaych | I'm writing four ints (a=1, b=2, c=3, d=4) to a binary file in C++ with fstream, but when I try to read them back, they do not match.
First of all, the written binary is 4 bytes long. Shouldn't it be 16 bytes (4 ints x 4 bytes/int)? When I read, I get the weird result 1234 2 3 4 if I do not zero-initialize the variable... | output << a << b << c << d;
is using the operator<< stream insertion operator, which is for formatted output. All four integers are being formatted as strings, and output with no delimiter between them.
You can trivially see this by actually looking at your own file (use hexdump or similar if you expect the file to co... |
65,094,516 | 65,097,657 | QT project and USB connection | I have problems with FTD2xx driver.
I'm using QT(C++) in Fedora 26 (64-bit) and the last version of FTD2xx for "2232H" device.
Also the build method is:
qmake /Address/ProjectName.pro -r -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
Problem:
The FT_Status return 0(FT_OK) at ft_openex(....) command, but that return n... | The FT_HANDLE is an output parameter in FT_OpenEx. You are correctly passing &ftH so that the function can overwrite ftH.
The FT_HANDLE is an input parameter to the other functions. You are incorrectly passing &ftH and should pass just ftH.
FT_Close(&ftH);
FT_Close(ftH);
Unfortunately FT_HANDLE is defined in a loosel... |
65,096,392 | 65,096,540 | C++ class and undefined behaviour | I would like to ask if my code is safe - does not have any unintended behaviour.
#include <cstdio>
#include <cstring>
class Test {
private:
char something[20];
public:
Test(){
strcpy(something,"Hello world!");
}
~Test() {
printf("Destructor\n");
}
operator char*() {
return something;
}
};
int... | Your code looks rather odd, but I see nothing undefined in it.
At least instead of the c-style cast you should use a static_cast:
printf ("%s\n",static_cast<char*>(Test()));
It shows [...] but will it be always?
Yes.
Is the object always destructed after printf function?
Yes.
And is this code safe?
No. It is bri... |
65,096,563 | 65,096,855 | How to template containers? | I have this function that I'd like to use for a container of strings, like vector<string> or set<string>. Obviously templating seems like the best solution here but I'm not sure how to template the container. I tried this but it doesn't work:
template<class T>
string pack_addrs(T<string>& caddrs) {
string res = "";
... | You can allow your template to use any class generically, but assert that it must behave like a container. In particular, you can assert that it has a value_type that matches std::string.
template<class C>
std::string pack_addrs(C& caddrs) {
static_assert(std::is_same<typename C::value_type, std::string>::value);
s... |
65,096,673 | 65,096,978 | C++ count digit of factorial of a large digit, two digit number or more | Click Here to View CodeFunction to perform factorial of digit and count the number of digit of that factorial
When i give "Input:13" this code give the desired output but when i use a "Input: digit greater the this or 3 digit number" then it is unable to calculate. I think it because of the number of value unsigned lo... | int digitsInFactorial(int N) {
if (N < 0)
return 0;
if (N <= 1)
return 1;
double digit=0;
for (int i = 1; i <= N; i++)
digit = digit + log10(i);
return floor(digit) + 1;
}
|
65,098,198 | 65,098,363 | Why doesn't my forward_ function work for rvalues? | I've understood how std::move works and implemented my own version for practice only. Now I'm trying to understand how std::forward works:
I've implemented this so far:
#include <iostream>
template <typename T>
T&& forward_(T&& x)
{
return static_cast<T&&>(x);
}
/*template <typename T>
T&& forward_(T& x)
{
... | A T&& reference stops being a forwarding reference if you manually specify T (instead of letting the compiler deduce it). If the T is not an lvalue reference, then T&& is an rvalue reference and won't accept lvalues.
For example, if you do forward_<int>(...), then the parameter is an rvalue reference and ... can only b... |
65,098,391 | 65,101,134 | Create Array as Vector with 10 Million elements and assign random numbers without duplicates | I try to code myself a Table with random generated Numbers. While that is simple as it is, causing that Vector not having any duplicates isn't as easy as I thought. So far my Code looks like that:
QStringList generatedTable;
srand (QTime::currentTime().msec());
std::vector<int> array(10000000);
for(std::size_t i = 0; ... | If you want to sample N integers without replacement from the range [low, high) you can write this:
std::vector<int> array(N); // or reserve space for N elements up front
auto gen = std::mt19937{std::random_device{}()};
std::ranges::sample(std::views::iota(low, high),
array.begin(),
... |
65,098,552 | 65,098,635 | add three std::vectors and store the result in the first vector | I have three vectors, vec1, vec2 and vec3.
I want to add all the three of them and store the result in vec1.
I am currently doing this,
std::transform(vec1.begin(), vec1.end(), vec2.begin(), vec1.begin(), std::plus<double>());
std::transform(vec1.begin(), vec1.end(), vec3.begin(), vec1.begin(), std::plus<double>());
I... | This is more efficient then 2 calls to std::transform:
for (size_t i = 0; i < vec1.size(); ++i) {
vec1[i] += vec2[i] + vec3[i];
}
You could write an algorithm for this, but there is none in the standard library that does it out-of-the box. You could use some weird predicate, but that would reduce readability rather... |
65,098,604 | 65,113,704 | Catch2 installation on ubuntu 20.04 #include <catch2/catch.hpp> | I am trying to install Catch2 on ubuntu 20.04.
Used instruction from here.
This is what i do:
$ git clone https://github.com/catchorg/Catch2.git
$ cd Catch2
$ cmake -Bbuild -H. -DBUILD_TESTING=OFF
$ sudo cmake --build build/ --target install
Than it saing me that all ok: link for output.
BUT:
When I try to compile th... | The problem is quite simple: clonning catchorg/Catch2 now gets you a v3 branch by default, which works differently. The most important change is that it is no longer single header, and that the catch2/catch.hpp header no longer exists.
You can either switch to the v2 branch before configuring and installing the build, ... |
65,098,922 | 65,098,999 | Why is setw not showing spaces? | I have this code. It works for the first space, but it doesn't work for the second one. Can anyone tell me why, or how to fix it?
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
//Constants
const int LENGTH_SPACE = 10;
const int LENGTH_SPACES = 2;
... | You seem to expect setw(LENGTH_SPACE) to simply add spaces in between the other output.
For that you would not need setw (see below). What it does instead (cppreference):
When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n.
For example this:
#inclu... |
65,099,097 | 65,099,733 | Is std::transform SIMD function? | Is std::transform SIMD? I mean if I have two arrays
std::array<int,4> a{1,2,3,4}; and std::array<int,4> b{1,2,3,4};. Let's sum this two arrays with std::transform(a.begin(),a.end(),b.begin(),result.begin(),std::plus<>()); and store the result in a new std::array<int,4> result; array. Have I done summing with SIMD comma... | Whether or not std::transform uses SIMD instructions is implementation and compiler dependant.
If you need to be sure that your transform uses SIMD functionality, here's a library that provides a SIMD transform function that has the same interface as the STL one https://github.com/xtensor-stack/xsimd
|
65,099,287 | 65,099,432 | Returning a generic lambda expression from a function causes compiler warnings if an explicit return type is given | I have a function whose return type is a simple generic lambda expression. (The lambda returned by this function is eventually passed as an argument to STL algorithms like std::transform() or std::accumulate().)
When the lambda does not have an explicit return type, the compiler emits no warnings:
inline auto Accumulat... | The point is that decltype(dst) is auto const & (where you can see auto as a template type`, so the lambda return a reference (I repeat: a reference) to a constant object.
The problem is that is a reference to
dst + src
that is: a reference to a temporary value, the temporary object created from the operation dst + sr... |
65,099,367 | 65,099,417 | How should I manage an intermediary vector after moving/swapping it in the constructor? | I am learning about memory management and not quite sure how how to manage the delete and/or destructor policy.
Suppose I have the following template:
template <typename X>
class DBContainer {
private:
vector<vector<X>> db;
size_t dbSize;
public:
DBContainer(size_t n = 100) {
dbSize = n;
<vector<vector<X... | Anything you construct dynamically with new needs to be delete'd when you are done using it. std::unique_ptr can help with that by calling delete for you when it is itself destructed, eg:
template <typename X>
class DBContainer {
private:
vector<vector<X>> db;
size_t dbSize;
public:
DBContainer(size_t n = 100) ... |
65,099,462 | 65,099,579 | How to pass the address of the overloaded method to template method | I am learning templates and stuck with the following case:
class ClassA {
LPCWSTR Name(void) {...};
UINT Name(LPCWSTR name) {...};
LPCWSTR Surname(void) {...};
UINT Surname(LPCWSTR name) {...};
}
class ClassB {
template <class T>
bool SetValue(UINT(T::*Setter)(LPCWSTR), T& object, LPC... | You might specify the one you want that way:
SetValue<ClassA>(&ClassA::Name, a, "Mike");
or
SetValue(static_cast<UINT(ClassA::*)(LPCWSTR)>(&ClassA::Name), a, "Mike");
Demo
|
65,099,659 | 65,100,315 | I want to implement a swap method in my class using templated swap | I have a class with only one member which is a vector.
class myClass{
private:
vector<double> vector_member;
public:
method1();
method2();
...
}
I want to implement a swap method in this class with a templated swap.
I'm learning the copy-swap idiom right now, the use of the swap method is to help with ... | You are likely missing an #include for the header file that std::swap() is defined in.
Prior to C++11, std::swap() is in <algorithm>. In C++11 and later, it is in <utility> instead.
#include <utility> // or <algorithm>
void Polynomial :: swap(Polynomial& p){
std::swap(vector_member, p.vector_member);
}
That bein... |
65,099,735 | 65,102,708 | Stange behaviour using nanoflann | Using the nanoflann-library for k-nearest-neighbor searches based on KDTrees I encountered a very strange behavior. My Code is a simple set of queries:
#include <vector>
#include <iostream>
#include <nanoflann.hpp>
#include <eigen3/Eigen/Dense>
using Eigen::MatrixX3d;
using Eigen::Vector3d;
using nanoflann::KNNResult... | The result set appears to be stateful - it's always showing you the nearest overall neighbor of all the points. For instance, if you loop from 5 to 10 you get 5 50 for each iteration
Reinitialize the result set each iteration and you'll get your desired behavior:
result_set.init(&index, &distance);
matrix_index.index->... |
65,099,831 | 65,104,811 | value returned from a function with a const range as arguments | lets say I have a function
auto found = find(first, last, condition);
This find should be able to promise not to modify first to last.
So something like
auto find(const T* first, const T* last, Comp c = less<>);
results in a const T or const T* being returned.
so
int arr[] = {3, 4};
std::vector v(arr, arr +2);
int* f... | You cannot have that signature
int* my_find(const int* begin, const int* end);
(to signaling that your method doesn't modify the range)
without (dangerous) /*const_*/cast.
That signature would allow
const int arr[] = {0, 1, 2, 3};
*my_find(std::cbegin(arr), std::cend(arr)) = 42; // Modifying const object. -> UB
Poss... |
65,100,130 | 65,107,765 | Error: no operator "==" matches these operands | This isn't actually my code, but I need help right here. Since I'm new to coding, I don't know how to fix this problem.
bool GetProcessEntryByName(string name, PROCESSENTRY32* pe) {
auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
cerr << "Tool hel... | You are compiling the project with Unicode, so Process32FirstW() will be called instead of Process32First(). Change your function to take wstring as parameter or convert name to wstring before comparison:
std::wstring wName(name.begin(), name.end());
if (pe->szExeFile == wName) {
|
65,100,555 | 65,100,619 | Capacity of Vectors? | According to c++ reference, vector's .capacity() function returns the "size of allocated storage capacity".
Doesn't this mean that a vector {1} should have capacity of sizeof(1) like an array?
If so, then why does this code:
int main() {
vector<int> v = {1};
cout << v.capacity() << endl;
return 0;
}
produce 1 ra... | The capacity() of a vector is better expressed as "the amount of space currently set aside that can be used for storage", expressed in terms of the number of potential elements that can be stored. Note that like size(), this is the number of elements, not the number of bytes.
For example, a vector might have a size() o... |
65,100,558 | 65,101,174 | Trouble with function that is supposed to find highest number in an array | I have this program that is designed to help a maker of chips and salsa keep track of sales for five different types of salsa. There are two parallel arrays, the first being "names" and the second being "num_of_jars". In the "names" array there are the five types of salsa(βMildβ, βMediumβ, βSweetβ, βHotβ, βZestyβ). The... | Actually it returns the index of largest number not the actual number. If you want both and you are bound to not to use vectors than you can additionally pass an integer by reference for index.
You can make a slight change in your program.
int find_max(const int a[], int n,int &index) {
int max = 0;
for (int i... |
65,100,648 | 65,100,706 | How could I iterator a vector as a member of class while the corresponding objects pass as a const | I have a simple class with only one member which is a vector, just like this:
class MyClass{
private:
vector<double> vector_member;
public:
method_1();
method_2();
....
};
And when I trying to overload an operator such as +=, which should add each element in the vectors in two objects and return a vect... | The input MyClass p object is const, so its vector<double> is also const, and as such you need to use vector<double>::const_iterator to iterate its elements, not vector<const double>::iterator. That is why you are getting the compiler error.
But, even fixing that, your code is still wrong. operator+= is supposed to m... |
65,100,766 | 65,104,746 | How to run all threads in sequence as static with out using opemMP for? | I'm new to openMP and multi-threading.
I have been given a task to run a method as static, dynamic, and guided without using OpenMPfor loop which means I cant use scheduled clauses.!
I could create parallel threads with parallel and could assign loop iterations to threads equally
but how to make it static and dynamic(1... | This looks like a university assignment (and a very good one IMO), I will not provide the complete solution, instead I will provide what you should be looking for.
The static scheduler looks okey; Notwithstanding, it can be improved by taking into account the chunk size as well.
For the dynamic and guided schedulers, t... |
65,100,774 | 65,258,457 | How to create a LibArchive archive on a directory path instead of a list of files? | I've never used LibArchive before and am trying to use it to create a .tar archive of a directory, since it is installed on my remote compute instance.
LibArchive has an example of how to create an archive from a flat list of files (shown below). But I can't find any examples of how to actually create an archive from a... | The archive_read_disk_descend function from the libtar api allows you to traverse a directory. It should be called before archive_write_header(a, entry); To use this function prior to starting the for loop you need to call struct archive *disk = archive_read_disk_new() in order to create an archive representing your di... |
65,100,841 | 65,103,091 | Lambda for function pointer of class | I'm using a signal/slot library (https://github.com/pbhogan/Signals) and I want the method to be able to have a different signature as the event. So I figure I'll need to intercept the call and make my own call so I can do any kind of argument manipulation. Right now I'm using a Signal with no parameters just to test i... | One nice property of lambdas is that they're objects - they generate an anonymous class with the call operator overloaded. And a nice property of operator overloads in C++ is that they can be treated like methods.
The Signal0 class expects a pointer to an object, and a pointer-to-member to a method in that object's cla... |
65,100,862 | 65,101,201 | Performance overhead of resizing to 0 a multidimensional vector? | Let's say I need to construct and frequently resize a vector of vectors of vectors as follows:
template <typename X>
class DB {
vector<vector<vector<X>>> database;
// hidden helper
h_clear() {
/* resize to 0 or iterate deleting? */
}
public:
DB(size_t size = 100) : database(100) {}
~DB() { h_clear(); }... | Don't use nested vectors. They're not allocated contiguously which can be a real problem when it comes to cache performance and confuses the pre-fetcher. Use N dimensional emulation with offsets, like x + y * w and so on.
The cost of releasing memory is generally trivial and won't "block" for any measurable period of t... |
65,101,558 | 65,101,598 | How to initialize a list of struct with constructor in c++ | I have a struct with a constructor likes:
struct Rectangle
{
int width;
int height;
Rectangle(int _width, int _height)
{
width = _width;
height = _height;
}
}
And I create a Rectangle that is okay: Rectangle rect = Rectangle(4, 8);
But how to create a list a Rectangle struct with c... | The "no default constructor" means there's no constructor that takes no arguments. You have one that takes 2. The compiler can't just make up values, it needs to know exactly what values to supply.
You can easily make this a default constructor by adjusting the signature to include defaults:
Rectangle(int _width = 0, i... |
65,102,024 | 65,102,303 | How do I check if there is a special character in a string in C++ using isalpha? | Pretty new to coding here. We are working with the isalpha function and I am having trouble using it with a string. My program will prompt the user for a word and then the function will check if the word contains any special characters. Basically, my code will only say there is a special character if they are all speci... | As mentioned, IsAlphaStr shall only return true if all the given characters are alphabetic. This can be achieved by adding a break in the false branch of the if condition, which stops the further execution of the for loop.
if (isalpha(wordcheck[i]) == 0)
{
alphabetic = false;
br... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.