question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,105,863 | 72,107,089 | filesystems "remove_all" vulnerability is not defined error | Hello i started c++ and im using Visual Studio 2017 and i want deletin all files/folder inside a folder and i tried this code:
#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
remove_all("C:\myfolder");
printf("All items deleted!");
return 0;
}
remove(); is works for me but remove_all(); doesn't work even i use #include <filesystem>
This is what i what i get while im using remove_all();:
Severity Code Description Project File Line Hide Status Error (active)
E0020 "remove_all" vulnerability is not defined.
is it possible to fix? or there another method to delete all files inside a folder?
Not: My VisualStudio is so laggy and sometimes it stay displays error even i fix it. Thanks
My c++ version:
enter image description here
| I modified the snippet: added filesystem:: and \\
#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
filesystem::remove_all("XX:\\XX\\TestFolder");
printf("All items deleted!");
return 0;
}
And use the C++ 17 in Project's properties.(Right click the project and you will see the properties page on the last line )
|
72,106,025 | 72,106,233 | Linker error on Timer based on Singleton pattern | Trying to write Singleton for the first time. This is a timer that works with one function to handle timer's both start and stop and also printing result.
When compiling, I'm getting linker errors like this one:
:-1: ошибка: CMakeFiles/some_algorithms.dir/timer_singleton.cpp.obj:timer_singleton.cpp:(.rdata$.refptr._ZN15timer_singleton7counterE[.refptr._ZN15timer_singleton7counterE]+0x0): undefined reference to `timer_singleton::counter'
What causes this error and how do I fix it?
Here is my source code:
timer_singleton.h
#ifndef TIMER_SINGLETON_H
#define TIMER_SINGLETON_H
#pragma once
#include <iostream>
#include <chrono>
class timer_singleton
{
public:
timer_singleton(timer_singleton & other) = delete;
void operator=(const timer_singleton& other) = delete;
static timer_singleton * getInstance();
static void hit_the_clock();
private:
timer_singleton();
static timer_singleton * instance;
static std::chrono::high_resolution_clock clock;
static std::chrono::high_resolution_clock::time_point start;
static std::chrono::high_resolution_clock::time_point stop;
static size_t counter;
};
#endif // TIMER_SINGLETON_H
timer_singleton.cpp
#include "timer_singleton.h"
timer_singleton::timer_singleton()
{
clock = std::chrono::high_resolution_clock();
start = clock.now();
stop = clock.now();
counter = 0;
}
timer_singleton * timer_singleton::getInstance()
{
if (instance == nullptr)
{
instance = new timer_singleton();
}
return instance;
}
void timer_singleton::hit_the_clock()
{
if (counter % 2 == 1)
{
// Clocks start ticking
start = clock.now();
++counter;
}
else
{
// Clocks stop ticking and print time measured time
stop = clock.now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "Measured time = " << duration.count() << " microseconds" << std::endl;
++counter;
}
}
main.cpp
#include "timer_singleton.h"
// ...
timer_singleton * timer = timer_singleton::getInstance();
timer->hit_the_clock();
// some calculations
timer->hit_the_clock();
| The problem: Most non-constant static members need to be defined outside of the class definition in order to get the one-and-only-one instance that will be shared by all class instances. Normally this means that in timer_singleton.cpp you would have to add
timer_singleton::counter = 0; // allocate and initialize
But...
A singleton is effectively already static so the only static member should be the function that gets the instance. This makes the whole problem go away.
New code with comments about other useful changes:
class timer_singleton
{
public:
timer_singleton(timer_singleton &other) = delete;
void operator=(const timer_singleton &other) = delete;
static timer_singleton* getInstance();
void hit_the_clock(); // shouldn't be static
private:
timer_singleton();
// None of these should have been static
std::chrono::high_resolution_clock clock; // This clock could jump around,
// including backward, in time.
// Safer with a steady_clock
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point stop;
size_t counter;
};
timer_singleton::timer_singleton():
start(clock.now()),
stop(start), // guaranteed to be same as start
counter(0)
{ // assignments replaced with initializations in member initializer list
}
timer_singleton* timer_singleton::getInstance()
{ // now using Meyers singelton
static timer_singleton instance;
return &instance; // consider adjusting to return a reference.
// Often a bit cleaner thanks to the no null guarantee
}
void timer_singleton::hit_the_clock()
{
auto now = clock.now(); // if timing is critical, the first thing
// you do is get the current time.
//if (counter % 2 == 1) // remember counter starts at 0, so first hit
// would stop, not start, the timer.
if (counter % 2 == 0)
{
// Clocks start ticking
start = now;
}
else
{
// Clocks stop ticking and print time measured time
stop = now;
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "Measured time = " << duration.count() << " microseconds" << std::endl;
}
++counter; // don't repeat yourself
}
|
72,106,369 | 72,106,465 | Using queue Between two object of class | In order to send messages between two objects of class!
I implemeted this
class User
{
public:
virtual void run()
{
while (true)
{
string receivedMessage = receiveMessage();
sendMessage(receivedMessage);
}
}
virtual void sendMessage(string message)
{
sentQueue.push(reply);
};
virtual string receiveMessage()
{
string receivedMessage;
receivedMessage = receivedQueue.pop();
return receivedMessage;
};
private:
};
What I am asking now is where to instantiate this blocking queue to use it between the two objects (User 1 and User 2) in order to exchange messages between them
| You have a global send queue and a global receive queue. What you need is a receive queue per player.
Have a send method on the player class that writes to their send queue
So player 1 would go
player2.Send("hello player2");
How to do it
class Player
{
BlockingQueue<string> queue_ = BlockingQueue<string>();
public:
void Post(const string& message){
queue_.push(message);
}
virtual void run()
{
while (true)
{
string msg= queue_.pop();
// do something with the message
if(msg == "BangBang")
{
}
}
}
now you can go
Player player1("player1");
Player player2("player2");
thread thread1(&Player::run, player1);
thread thread2(&Player::run, player2);
player1.Post("BangBang");
Probably you should make you message more that a string, something like
class Message{
Player* sender;
string text;
CommandType ct;
}
or have a string syntax like "player1/shoot/0,5"
you need to know who the message cam from so you can react correctly and maybe reply
or maybe the post method is called on the sending player object and includes the destination user. Using my suggested Message class
class Player
{
BlockingQueue<Message> queue_ = BlockingQueue<Message>();
public:
void Post(const string& message, Player *dest){
Message msg;
msg.sender= this; // sender
msg.text = message;
dest->queue_.push(message);
}
virtual void run()
{
while (true)
{
Message msg= queue_.pop();
// do something with the message
if(msg.Text == "BangBang")
{
/// check for hit
// reply to sender
Post("you got me", msg.sender);
}
}
}
now
Player player1("player1");
Player player2("player2");
thread thread1(&Player::run, player1);
thread thread2(&Player::run, player2);
player2.Post("BangBang", &player1); // send message to player2 (from 1)
|
72,106,607 | 72,106,698 | c++ How do I fix my no instance error on my setMaterial piece of code | I just started coding with C++, and am doing a few tutorials on using C++, but when I finished up one part of code I saw that it was erroring:
no instance of overload function "Unigine::ObjectMeshDynamic""setMaterial" matches the argument
Here is my code, and even though I did exactly as I was supposed to, maybe there was something I missed, even after looking at it over and over again (this is in unigine):
int AppWorldLogic::addMeshToScene(const char *file_name, const char *mesh_name, const char *material_name, Math::Vec3 position)
{
MeshPtr mesh = Mesh::create();
ObjectMeshDynamicPtr omd;
if (file_name)
{
if (!mesh->load(file_name))
{
Log::error("\nError opening .mesh file!\n");
mesh.clear();
return 0;
}
else omd = ObjectMeshDynamic::create(mesh);
}
else
{
mesh->addBoxSurface("box_surface", Math::vec3(0.5f));
omd = ObjectMeshDynamic::create(mesh);
}
// setting node material, name and position
omd->setMaterial(material_name, "*");
omd->setName(mesh_name);
omd->setWorldPosition(position);
Objects.append(omd);
Log::message("-> Object %s added to the scene. \n", mesh_name);
mesh.clear();
return 1;
}
| If you read Unigine's current (2.15.1) documentation for setMaterial() (which Unigine::ObjectMeshDynamic inherits from Unigine::Object), you will see that it is overloaded to accept only the following parameters:
void setMaterial ( const Ptr<Material> & mat, int surface )
void setMaterial ( const Ptr<Material> & mat, const char * pattern )
You are trying to call SetMaterial() with 2 strings as input, and there is no such overload available, hence the error.
"*" is a string literal, which is implemented as a const char[2] array that decays into a const char*. So you can safely pass that to the pattern parameter.
However, you are trying to pass your material_name variable, which is a const char* string, to the mat parameter. A const char* is not compatible with Ptr<Material>. setMaterial() wants a pointer to a Unigine::Material object instead of a string.
I looked at earlier versions of the documentation, and found that prior to 2.15, there were additional overloads of setMaterial(), some of which accepted a const char* name parameter instead of a const Ptr<Material> &mat parameter. It seems those overloads where removed in 2.15. Which means the code you are trying to use was meant for an earlier version of Unigine, not for the latest version.
It appears that you copied your code from this documentation page, which has apparently not been updated to account for the latest Unigine version. There is obviously now another step involved to get a Material object from a name string in the latest version. For instance, by calling Materials::findMaterial(). Or alternatively, using setMaterialPath() instead of setMaterial().
Have a look at the Upgrading to UNIGINE 2.15: API Migration: Materials Changes documentation.
|
72,106,670 | 72,106,707 | cold weather meteorologists report index | I'm new in c++ and trying to calculate "W = 33 - ( 10√v −v + 10.5) * (33 - t) / 23.1", but i don't know how to use sqrt() !!
here is my code :
/* W=33−(10√v−v+10.5)(33−t)/23.1
Where 'V' is speed in (m/s)
Where 't' is temperature in degrees Celsius: t <= 10
Where 'W' is windchill index (in degrees Celsius)
*/
#include <iostream>
#include <cmath>
using namespace std;
double meteorologistReport(double V, double t, double W);
int main() {
double V, t, W = 0;
cout << "Please enter wind speed (m/sec) : ";
cin >> V;
cout << "Please enter temperature (degrees celsius <= 10 ) : ";
cin >> t;
if (t > 10) {
cout << "You entered a value above 10! Please enter a value less then or equal to 10! " << endl;
}
else {
W = 33 - (10√V - V + 10.5) * ( 33 - t ) / 23.1 );
cout << "The WindChill index is : " << W << endl;
}
return 0;
}
Thank you.
| The square root character is not a valid math operator in C++. You will have to use the sqrt function:
10.0 * sqrt(V)
Note: the square root is a floating point function, so all your values and variables should be float or double.
|
72,107,749 | 72,107,951 | How can I save a string input with blank space in c++ (I am using if else statement) | So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Everything was fine until I came to know that it was not saving the text input with a blank space
I searched how to store string input with blank space and then changed the code but it didn't work.
The changed code was
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Please help
List item
| If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
Note: the use of isdigit(y) is superfluous. If you validate the input correctly, you determine whether a valid integer was entered at the time of the read simply by checking the stream-state after the read. If failbit is set, the user did not enter a valid integer.
While fine for test code, you will want to look at Why is “using namespace std;” considered bad practice?
Example Use/Output
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
If I misinterpreted your goal, let me know and I'm happy to help further.
|
72,107,767 | 72,107,794 | the lua math.random equivalent for c ++? | is there a similar function in c ++ where I can bind variables to random numbers?
local xoffset, yoffset, zoffset = math.random(-1, 10), math.random(1, -10), math.random(1, 10)
| There is a full suite of random number generation algoriths in <random>. You can do something like this:
std::default_random_engine e1(r());
int xoffset = std::uniform_int_distribution<int>{-1, 10}(e1);
int yoffset = std::uniform_int_distribution<int>{-10, 1}(e1);
...
|
72,108,619 | 72,108,923 | Is my understanding of __ATOMIC_SEQ_CST correct? (I'd like to write a mutex with it + atomics) | For fun I'm writing my own threading library used by me and a friend or two. First thing I'd like to write is a mutex
It appears I'm generating the assembly I want. __atomic_fetch_add seems to generate lock xadd and __atomic_exchange seems to generate xchg (not cmpxchg). I use both with __ATOMIC_SEQ_CST (for now I'll stick to that)
If I am using __ATOMIC_SEQ_CST will gcc or clang understand these are synchronizing function? If I write lock(); global++; unlock(); will any compilers move global++; before or after the lock/unlock function? Do I need to call __atomic_thread_fence(__ATOMIC_SEQ_CST); or __sync_synchronize(); for any reason? (they seem to do the same thing on x86-64). https://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync seems to suggest my understanding is correct but its easy to misread documentation and I sometimes wonder if scope plays a part in these rules.
I think using those intrinsic the behavior of code in between a lock/unlock will act the same way as a pthread mutex lock/unlock?
|
If I am using __ATOMIC_SEQ_CST will gcc or clang understand these are synchronizing function?
Yes, that is the entire reason for these primitives to have memory ordering semantics.
The memory ordering semantics accomplish two things: (1) ensure that the compiler emits instructions that include the appropriate barriers to prevent reordering by the CPU; (2) ensure that compiler optimizations do not move code past those instructions in ways that the barrier should forbid.
If I write lock(); global++; unlock(); will any compilers move global++; before or after the lock/unlock function?
They will not. Again, that is the whole point of being able to specify memory ordering.
Do I need to call __atomic_thread_fence(__ATOMIC_SEQ_CST); or __sync_synchronize(); for any reason?
Not in this setting, no.
|
72,109,441 | 72,109,673 | Maximum subsequence sum such that no three are consecutive | Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present.
Examples :
Input 1: arr[] = {1, 2, 3}
Output: 5
We can't take three of them, so answer is
2 + 3 = 5
Input 2: arr[] = {3000, 2000, 1000, 3, 10}
Output: 5013
3000 + 2000 + 3 + 10 = 5013
Input 3: arr[] = {100, 1000, 100, 1000, 1}
Output: 2101
100 + 1000 + 1000 + 1 = 2101
Input 4: arr[] = {1, 1, 1, 1, 1}
Output: 4
Input 5: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 27
Input 6: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 40
#include<bits/stdc++.h>
using namespace std;
int findMax(vector<int>& nums, int k, vector<long long int>& dp)
{
if(k >= nums.size()) {
return 0;
}
if(dp[k]!=-1)
return dp[k];
int a=findMax(nums,k+1,dp); //exclude first element
int b=nums[k]+findMax(nums,k+2,dp); //exclude second element
int c=nums[k]+nums[k+1]+findMax(nums,k+3,dp); //exclude third element
dp[k]= max(a,max(b, c));
return dp[k];
}
int main()
{
vector<int>nums = {1, 2, 3, 4, 5, 6, 7, 8};
int n = nums.size();
vector<long long int>dp(n,-1);
cout<<findMax(nums,0,dp);
return 0;
}
Can somebody tell me what is the error with this code? Input 1 to 5 is running perfectly fine. But, the output for the sixth test case is coming as 134 instead of 40. Why is it so?
| When k == nums.size() - 1, you have UB with out of bound access with c computation.
You have to handle the case, for example:
int findMax(std::vector<int>& nums, std::size_t k, std::vector<long long int>& dp)
{
if(k >= nums.size()) {
return 0;
}
if(dp[k] != -1)
return dp[k];
int a = findMax(nums,k+1,dp); //exclude first element
int b = nums[k] + findMax(nums, k + 2, dp); //exclude second element
int c = (k + 1 < nums.size()) ? nums[k] + nums[k + 1] + findMax(nums, k + 3, dp) : 0; //exclude third element
dp[k] = std::max({a, b, c});
return dp[k];
}
Demo
|
72,109,610 | 72,109,807 | Random word pick based on the number of times that they were used | I have a vector of strings like this one:
std::vector<string> words ={"word1", "word2", "word3", "word4"}; //and many more
The code randomise the vector ( in an auxiliary vector) and takes the first word from the auxiliary vector. To do this I use random_shuffle. So far, everything goes very well. But now, I would like to minimise repeated words. My idea is to save the number of times a word is used to in another vector of <int> and randomise the words based on some weights that depends on the number of times that a word is selected by the generator. The words used more times have a lower weight and, for instance, the words never used have maximum weight (1.0 maybe). Is there something in STL that can do that? If not, does someone can help me on this hard task?
The task is:
At beginning all words have the same probability (same weight) of being picked and the random function picks any word with equal weight;
After first pick, one of the words will have lower probability because it was already picked once, so,the random function will pick a random word from the list, but the one already picked will have lower probability of being picked;
After some tries suppose that word1 was picked 4 times word2 3 times word3 3 times and word4 0 times. The word with lower weight is word1 and the word maximum weight will be word4. Based on the number of times that word was picked the random function will generate the weights and pick a word.
thanks in advance
| std::discrete_distribution might help, something like
std::random_device rd;
std::mt19937 gen(rd());
std::vector<std::string> words = {"word1", "word2", "word3", "word4"};
std::vector<std::size_t> weights = {10, 10, 10, 10};
for (int i = 0; i != 12; ++i) {
std::discrete_distribution<> d(weights.begin(), weights.end());
const auto index = d(gen);
std::cout << words[index] << std::endl;
weights[index]--;
}
Demo
|
72,109,724 | 72,109,800 | Why removing random element from vector and list costs almost the same time? | As cppreference says
Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.
Considering the continuous memory used by std::vector where erase should be linear time. So it is reasonable that random erase operations on std::list should be more efficient than std::vector.
But I the program shows differently.
int randi(int min, int max) {
return rand()%(max-min)+min; // Generate the number, assign to variable.
}
int main() {
srand(time(NULL)); // Seed the time
int N = 100000;
int M = N-2;
int arr[N];
for (int i = 0; i < N; i++) {
arr[i] = i;
}
list<int> ls(arr, arr+N);
vector<int> vec(arr, arr+N);
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
for (int i = 0; i < M; i++) {
int j = randi(0, N - i);
ls.erase(next(ls.begin(), j));
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds_1 = end - start;
cout << "list time cost: " << elapsed_seconds_1.count()) << "\n";
for (int i = 0; i < M; i++) {
int j = randi(0, N - i);
vec.erase(vec.begin() + j);
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds_2 = end - start;
cout << "vector time cost: " << elapsed_seconds_2.count()) << "\n";
return 0;
}
~/cpp_learning/list$ ./demo
list time cost: 8.114993171
vector time cost: 8.306458676
| Because it takes a long time to find the element in the list. Insertion or removal from list is O(1) if you already hold an iterator to the desired insertion/deletion location. In this case you don't, and the std::next(ls.begin(), j) call is doing O(n) work, eliminating all savings from the cheap O(1) erase (frankly, I'm a little surprised it didn't lose to vector; I'd expect O(n) pointer-chasing operations to cost more than a O(n) contiguous memmove-like operation, but what do I know?) Update: On checking, you forgot to save a new start point before the vector test, and in fact, once you fix that issue, the vector is much faster, so my intuition was correct there: Try it online!
With -std=c++17 -O3, output was:
list time cost: 9.63976
vector time cost: 0.191249
Similarly, the vector is cheap to get to the relevant index (O(1)), but (relatively) expensive to delete it (O(n) copy-down operation after).
When you won't be iterating it otherwise, list won't save you anything if you're performing random access insertions and deletions. Situations like that call for using std::unordered_map and related containers.
|
72,110,090 | 72,110,299 | Overload assignment operator and rule of zero | I have written a template class A<T> and I am making use of the rule of zero (I let the compiler generate the destructor, copy/move constructors and assignment operator overloadings).
However, I need now a customized assignment operator that takes a different type B<T> as argument:
A<T>& operator=(const B<T>& rhs);
Will this implementation prevent the compiler from generating the default destructor etc.?
My guess is no, because the compiler generates
A<T>& operator=(const A<T>& rhs);
which is just entirely different from the overloading I want to implement.
| According to my understanding, adding a operator= overload will not prevent the compiler from generating the default one according to the rule of 0.
I base this understanding on the fact that your operator= overload is not in fact a copy assignment, nor a move assignment.
Therefore the rules about generaing default constructors and assignment operators are not relevant.
I verified it with MSVC.
You can use the code below to verify with your compiler:
#include <iostream>
template <typename T>
struct B
{
B(T const & n) : bn(n) {}
T bn{ 0 };
};
template <typename T>
struct A
{
A(T const & n) : an(n) {}
A<T>& operator=(const B<T>& rhs)
{
an = rhs.bn;
return *this;
}
T an{ 0 };
};
int main()
{
A<int> a1{ 5 };
A<int> a2{ 6 };
std::cout << a2.an << ",";
a2 = a1; // Use default assinment
std::cout << a2.an << ",";
B<int> b{ 3 };
a2 = b; // Use custom assignment
std::cout << a2.an << std::endl;
return 0;
}
The output should be: 6,5,3:
6 is the value A<int> a2 is constructed with, 5 is the value assigned from A<int> a1, and 3 is the value assigned from B<int> b.
Note: an alternative would be to use a user-defined conversion function, as @LouisGo commented (see above).
|
72,111,100 | 72,111,761 | CListCtrl did not show text immediately like StaticText | I have a code like this to write install log to a static text and a list control, and i have a button to start the installer that be handle by function OnClickInstallBtn() but every time I call the WriteLogtoScreen(), only the static text change and nothing show up in the list until the OnClickInstallBtn() is done and everything on that list show up all at one.
How can i make it show up right away like the static text?
WriteLogtoScreen(LPCTSTR sLog)
{
int iItems;
iItems = m_ListLog.GetItemCount();
m_ListLog.InsertItem(iItems, sLog);
m_ListLog.Update(iItems);
m_ListLog.SetItemText(iItems, 0, sLog);
m_ListLog.Update(iItems);
UpdateData(FALSE);
SetDlgItemText(IDC_STATIC, sLog);
}
| You should call RedrawWindow() if you want to force the redraw of your list explicitly in something like this :
void WriteLogtoScreen(LPCTSTR sLog)
{
int iItems;
iItems = m_ListLog.GetItemCount();
m_ListLog.InsertItem(iItems, sLog);
m_ListLog.Update(iItems);
m_ListLog.SetItemText(iItems, 0, sLog);
m_ListLog.Update(iItems);
UpdateData(FALSE);
//instant redraw
m_ListLog.RedrawWindow();
SetDlgItemText(IDC_STATIC, sLog);
}
|
72,111,819 | 72,112,297 | How to let a template function accept anything you can construct some basic_string_view out | I'm trying to write a simple template function which accepts all possible basic_string_view but i always get the compiler error "no matching overloaded function found".
I don't know the reason; explicitly converting to string_view by the caller works but i'd like to avoid that; or is intentionally made hard?
Are there deduction guidelines which prevent this?
And is there a easy way to implement this as a template?
Here (and on godbolt) is what i tried:
#include <string_view>
#include <string>
template <typename CharT, typename Traits> void func(std::basic_string_view<CharT, Traits> value)
//template <typename CharT> void func(std::basic_string_view<CharT> value)
//void func(std::string_view value)
{}
int main() {
std::string s;
std::string_view sv(s);
char const cs[] = "";
std::string_view csv(cs);
std::wstring ws;
std::wstring_view wsv(ws);
wchar_t const wcs[] = L"";
std::wstring_view wcsv(wcs);
func(s);
func(sv);
func(cs);
func(csv);
func(ws);
func(wsv);
func(wcs);
func(wcsv);
}
Here are the errors msvc, clang and gcc show:
error C2672: 'func': no matching overloaded function foundx64 msvc v19.latest #3
error C2783: 'void func(T)': could not deduce template argument for '<unnamed-symbol>'x64 msvc v19.latest #3
error: no matching function for call to 'func'x86-64 clang (trunk) #1
error: no matching function for call to 'func(std::string&)'x86-64 gcc (trunk) #2
EDIT:
Demo of a blend of Yakks c++20 answer with the addition of Jonathans raw character pointer support.
| It's also possible to do this using just C++20 by checking whether the argument passed to the function is a range. The range can then be converted to a basic_string_view using its constructor overload that takes iterators.
I've also added an overload that can deal with char pointers since those aren't ranges.
#include <string_view>
#include <string>
#include <type_traits>
#include <ranges>
template <typename CharT, typename Traits>
void func(std::basic_string_view<CharT, Traits> value) {
// ...
}
template<typename S> requires std::ranges::contiguous_range<S>
void func(const S& s) {
func(std::basic_string_view{std::ranges::begin(s), std::ranges::end(s)});
}
template<typename S> requires (!std::ranges::range<S> && requires (S s) { std::basic_string_view<std::remove_cvref_t<decltype(s[0])>>(s); })
void func(const S& s) {
func(std::basic_string_view<std::remove_cvref_t<decltype(s[0])>>(s));
}
|
72,111,903 | 72,113,978 | Adding multiple data attributes to one node | I need a way to add more than one data ( such as name, id, age) into a single node in a linked list in C++. Instead of having the data value being only a name or a number.
| I think you wish to group your data, there are many ways to do that.
The easiest is if you create a stucture:
struct MyData {
int id;
std::string name;
int age;
};
MyData data;
data.id = 1;
data.name = "John";
data.age = 23;
std::list<MyData> list;
list.push_back(data);
...
std::list<MyData>::const_iterator itr = list.begin();
int age = itr->age;
Would that help?
|
72,111,960 | 72,113,861 | GCC error when using parent class method as derived class method | I have a function in my code which only accepts a class member method as a template parameter. I need to call this method using a class method which is inherited from a parent class. Here is an example code of my problem:
template <class C>
class Test {
public:
template<typename R, R( C::* TMethod )()> // only a member function should be accepted here
void test() {}
};
class A {
public:
int a() { return 0; } // dummy method for inheritance
};
class B : public A {
public:
using A::a; // A::a should be declared in the B class declaration region
// int a() { return A::a(); } // if this lines is activated compliation works
};
int main() {
auto t = Test<B>();
t.test<int, &B::a>();
}
With the MSVC 2019 compiler the code compiles without problems. However the gcc produces following error:
<source>: In function 'int main()':
<source>:23:23: error: no matching function for call to 'Test<B>::test<int, &A::a>()'
23 | t.test<int, &B::a>();
| ~~~~~~~~~~~~~~~~~~^~
<source>:5:10: note: candidate: 'template<class R, R (B::* TMethod)()> void Test<C>::test() [with R (C::* TMethod)() = R; C = B]'
5 | void test() {}
| ^~~~
<source>:5:10: note: template argument deduction/substitution failed:
<source>:23:17: error: could not convert template argument '&A::a' from 'int (A::*)()' to 'int (B::*)()'
23 | t.test<int, &B::a>();
|
As far as I understand the gcc is still handling the type of B::a as A::a. On the cpp reference its saying that using
Introduces a name that is defined elsewhere into the declarative
region where this using-declaration appears.
So in my opinion the using should transfer the A::a method to the declerativ region of B and therefor it should be handled as B::a. Am I wrong or is there a bug in GCC?
Here is the example on Compiler Explorer: https://godbolt.org/z/TTrd189sW
| There is namespace.udecl, item 12 (emphasis mine):
For the purpose of forming a set of candidates during overload
resolution, the functions named by a using-declaration in a derived
class are treated as though they were direct members of the derived
class. [...] This has no effect on the type of the function,
and in all other respects the function remains part of the base class.
Thus, a is not a member of B, and the type of &B::a is int (A::*)().
(&B::a means the same thing regardless of whether you include using A::a; or not)
There is no point to using named functions from a base class except to work around the "hiding problem" when you want to overload or override them.
|
72,112,249 | 72,113,646 | BOOST_DEFINE_ENUM_CLASS and json | In the documentation for boost describe, under the heading "Automatic Conversion to JSON", it shows how to implement "a universal tag_invoke overload that automatically converts an annotated struct to a Boost.JSON value". The example supports BOOST_DESCRIBE_STRUCT, how would I implement something similar for BOOST_DEFINE_ENUM_CLASS?
Here is my naive attempt to adapt the example to support BOOST_DEFINE_ENUM_CLASS alongside BOOST_DESCRIBE_STRUCT:
#include <boost/describe.hpp>
#include <boost/mp11.hpp>
#include <boost/json.hpp>
#include <type_traits>
#include <vector>
#include <map>
namespace app {
template<class T,
class D1 = boost::describe::describe_members<T, boost::describe::mod_public | boost::describe::mod_protected>,
class D2 = boost::describe::describe_members<T, boost::describe::mod_private>,
class En = std::enable_if_t<boost::mp11::mp_empty<D2>::value> >
void tag_invoke(boost::json::value_from_tag const&, boost::json::value& v, T const& t) {
auto& obj = v.emplace_object();
boost::mp11::mp_for_each<D1>([&](auto D) {
obj[D.name] = boost::json::value_from(t.*D.pointer);
});
}
struct A {
int x;
int y;
};
BOOST_DESCRIBE_STRUCT(A, (), (x, y))
struct B {
std::vector<A> v;
std::map<std::string, A> m;
};
BOOST_DESCRIBE_STRUCT(B, (), (v, m))
BOOST_DEFINE_ENUM_CLASS(E1, v1, v2, v3)
struct C {
int x;
E1 e1;
};
BOOST_DESCRIBE_STRUCT(C, (), (x, e1))
} // namespace app
#include <iostream>
void main() {
app::A a{ 1, 2 };
std::cout << boost::json::value_from(a) << std::endl;
app::B b{ { { 1, 2 }, { 3, 4 } }, { { "k1", { 5, 6 } }, { "k2", { 7, 8 } } } };
std::cout << boost::json::value_from(b) << std::endl;
app::C c{ 1, app::E1::v1 };
//std::cout << boost::json::value_from(c) << std::endl;
}
What do I need to do in order to enable boost::json::value_from() for c?
Edit: Okey dokes, the code below does the trick, but I got to make it more templatey:
void tag_invoke(boost::json::value_from_tag const&, boost::json::value& v, E1 const& t) {
v = boost::describe::enum_to_string(t, "x");
}
| The documentation gives this example (slightly modified to suit our JSON needs later):
template <class E> char const* enum_to_string(E e) {
char const* r = nullptr;
boost::mp11::mp_for_each<boost::describe::describe_enumerators<E>>(
[&](auto D) {
if (e == D.value)
r = D.name;
});
return r;
}
You can use that to implement the value_from customization point:
static inline void tag_invoke(json::value_from_tag, json::value& jv, E1 e) {
auto name = enum_to_string(e);
jv = name
? name
: std::to_string(static_cast<std::underlying_type_t<E1>>(e));
}
Given suitable SFINAE you can template that on any enum type, as long as you keep in mind to limit the ADL applicability to your own enums to avoid interfering with other libraries.
Live demo:
Live On Compiler Explorer
#include <boost/describe.hpp>
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for online demo
#include <boost/mp11.hpp>
#include <map>
#include <type_traits>
#include <vector>
namespace app {
namespace json = boost::json;
template<class T,
class D1 = boost::describe::describe_members<T, boost::describe::mod_public | boost::describe::mod_protected>,
class D2 = boost::describe::describe_members<T, boost::describe::mod_private>,
class En = std::enable_if_t<boost::mp11::mp_empty<D2>::value> >
void tag_invoke(json::value_from_tag const&, json::value& v, T const& t) {
auto& obj = v.emplace_object();
boost::mp11::mp_for_each<D1>([&](auto D) {
obj[D.name] = json::value_from(t.*D.pointer);
});
}
struct A {
int x;
int y;
};
BOOST_DESCRIBE_STRUCT(A, (), (x, y))
struct B {
std::vector<A> v;
std::map<std::string, A> m;
};
BOOST_DESCRIBE_STRUCT(B, (), (v, m))
BOOST_DEFINE_ENUM_CLASS(E1, v1, v2, v3)
template <class E> char const* enum_to_string(E e) {
char const* r = nullptr;
boost::mp11::mp_for_each<boost::describe::describe_enumerators<E>>(
[&](auto D) {
if (e == D.value)
r = D.name;
});
return r;
}
static inline void tag_invoke(json::value_from_tag, json::value& jv, E1 e) {
auto name = enum_to_string(e);
jv = name
? name
: std::to_string(static_cast<std::underlying_type_t<E1>>(e));
}
struct C {
int x;
E1 e1;
};
BOOST_DESCRIBE_STRUCT(C, (), (x, e1))
} // namespace app
#include <iostream>
int main() {
app::A a{ 1, 2 };
std::cout << boost::json::value_from(a) << std::endl;
app::B b{ { { 1, 2 }, { 3, 4 } }, { { "k1", { 5, 6 } }, { "k2", { 7, 8 } } } };
std::cout << boost::json::value_from(b) << std::endl;
app::C c{ 1, app::E1::v1 };
std::cout << boost::json::value_from(c) << std::endl;
}
Prints
{"x":1,"y":2}
{"v":[{"x":1,"y":2},{"x":3,"y":4}],"m":{"k1":{"x":5,"y":6},"k2":{"x":7,"y":8}}}
{"x":1,"e1":"v1"}
|
72,112,372 | 72,113,446 | How to test the problem size scaling performance of code | I'm running a simple kernel which adds two streams of double-precision complex-values. I've parallelized it using OpenMP with custom scheduling: the slice_indices container contains different indices for different threads.
for (const auto& index : slice_indices)
{
auto* tens1_data_stream = tens1.get_slice_data(index);
const auto* tens2_data_stream = tens2.get_slice_data(index);
#pragma omp simd safelen(8)
for (auto d_index = std::size_t{}; d_index < tens1.get_slice_size(); ++d_index)
{
tens1_data_stream[d_index].real += tens2_data_stream[d_index].real;
tens1_data_stream[d_index].imag += tens2_data_stream[d_index].imag;
}
}
The target computer has a Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz with 24 cores, L1 cache 32kB, L2 cache 1MB and L3 cache 33MB. The total memory bandwidth is 115GB/s.
The following is how my code scales with problem size S = N x N x N.
Can anybody tell me with the information I've provided if:
it's scaling well, and/or
how I could go about finding out if it's utilizing all the resources which are available to it?
Thanks in advance.
EDIT:
Now I've plotted the performance in GFLOP/s with 24 cores and 48 cores (two NUMA nodes, the same processor). It appears so:
And now the strong and weak scaling plots:
Note: I've measured the BW and it turns out to be 105GB/S.
Question: The meaning of the weird peak at 6 threads/problem size 90x90x90x16 B in the weak scaling plot is not obvious to me. Can anybody clear this?
| Your graph has roughly the right shape: tiny arrays should fit in the L1 cache, and therefore get very high performance. Arrays of a megabyte or so fit in L2 and get lower performance, beyond that you should stream from memory and get low performance. So the relation between problem size and runtime should indeed get steeper with increasing size. However, the resulting graph (btw, ops/sec is more common than mere runtime) should have a stepwise structure as you hit successive cache boundaries. I'd say you don't have enough data points to demonstrate this.
Also, typically you would repeat each "experiment" several times to 1. even out statistical hiccups and 2. make sure that data is indeed in cache.
Since you tagged this "openmp" you should also explore taking a given array size, and varying the core count. You should then get a more or less linear increase in performance, until the processor does not have enough bandwidth to sustain all the cores.
A commenter brought up the concepts of strong/weak scaling. Strong scaling means: given a certain problem size, use more and more cores. That should give you increasing performance, but with diminishing returns as overhead starts to dominate. Weak scaling means: keep the problem size per process/thread/whatever constant, and increase the number of processing elements. That should give you almost linear increasing performance, until -- as I indicated -- you run out of bandwidth. What you seem to do is actually neither of these: you're doing "optimistic scaling": increase the problem size, with everything else constant. That should give you better and better performance, except for cache effects as I indicated.
So if you want to say "this code scales" you have to decide under what scenario. For what it's worth, your figure of 200Gb/sec is plausible. It depends on details of your architecture, but for a fairly recent Intel node that sounds reasonable.
|
72,113,071 | 72,113,238 | Why the datatype of the pointer should be same as the datatype of the variable to which it is addressing? | Code snippet 1:
int main(){
float fl;
int *i=&fl;
}
The error was:
error: cannot convert 'float*' to 'int*' in initialization int *i=&fl;
Code snippet 2:
int main(){
int i;
float *fl=&i;
}
The error was:
error: cannot convert 'int*' to 'float*' in initialization float *fl=&i;
Question
The datatype only helps in allocating the required memory size to the specified datatype. When it comes to the address of the memory, irrespective of the datatype of the variable, both addresses will be in the same format.
For Example-
int a;
float b;
cout<<&a<<" "<<&b;
The output was_
0x61fe1c 0x61fe18
So by looking at the address, one can't differentiate between datatypes. So when the pointer deals with the addresses, why can't we assign an integer pointer to the float variable?
NOTE: Here I'm not talking about the size of the datatype or the number of bytes that each datatype takes or the data format that each instruction is stored. I'm only interested in the address of the variable.
|
The datatype only helps in allocating the required memory size to the specified datatype.
This is not true. The type of a pointer p also tells the compiler what type to use for the expression *p.
If p is an int *, then *p has type int, and, if the program uses an expression such as a *p + 3, the compiler will generate an integer add instruction (or equivalent code). If p is a float *, then *p has type float, and, if the program uses an expression such as *p + 3, the compiler will generate a floating-point add instruction (or equivalent code). These different instructions will cause the computer to treat the bits of *p differently.
When it comes to the address of the memory, irrespective of the datatype of the variable, both addresses will be in the same format.
This is often true in C implementations but is not always true. The C standard allows pointers of different types to have different representations, with certain exceptions. (Pointers to character types and to void must have the same representation as each other. Pointers to structure types must have the same representation as each other. Pointers to union types must have the same representation as each other.)
|
72,113,099 | 72,113,237 | What do clang and gcc qualify as variable being unused | I noticed in a PR review an unused variable and we were wondering why compiler didn't catch that. So I tested with godbolt the following code with bunch of unused variables and was surprised that some were reported as unused but others not. Even though all of them are unused.
#include <string>
struct Index
{
Index(int index) : m_index(index) {}
int m_index;
};
int main()
{
std::string str = "hello"; // case 1. no warning here - unexpected
int someValue = 2; // case 2. warning - as expected
const int someConstant = 2; // case 3. warning - as expected
Index index1(2); // case 4. just as equally not used but no warning - unexpected
// here using the assignment but do get a warning here
// but the str assignment doesn't give a warning - weird
Index index2 = 2; // case 5.
Index index3{2}; // case 6. just as equally not used but no warning - unexpected
Index index4 = {2}; // case 7. just as equally not used but no warning - unexpected
return 0;
}
warning: unused variable 'someValue' [-Wunused-variable]
warning: unused variable 'index2' [-Wunused-variable] (warning only on clang, not on gcc)
warning: unused variable 'someConstant' [-Wunused-variable]
So what do clang and gcc qualify as unused? What if I'm using a lock? I declare it but don't use it directly but use it for automatic releasing of a resource. How do I tell the compiler that I am using it if one day it starts to give a warning about the lock?
int g_i = 0;
std::mutex g_i_mutex; // protects g_i
void safe_increment()
{
const std::lock_guard<std::mutex> lock(g_i_mutex);
++g_i;
// g_i_mutex is automatically released when lock goes out of scope
}
flags: -Wunused-variable
clang: 14.0.0
gcc: 11.3
| The reason why there's no warning is that variables of non-trivial class type aren't technically unused when you initialize them but then never access them in your function.
Consider this example:
struct Trivial {};
struct NonTrivial {
NonTrivial() {
//Whatever
}
};
void test() {
Trivial t;
NonTrivial nt;
}
GCC warns about Trivial t; being unused since this declaration never causes any user-defined code to run; the only thing that's run are the trivial constructor and trivial destructor, which are no-ops. So no operation at all is performed on Trivial t and it is truly unused (its memory is never even touched).
NonTrivial nt; doesn't cause a warning, however, since it is in fact used to run its constructor, which is user-defined code.
That's also why compilers are not going to warn about "unused lock guards" or similar RAII classes - they're used to run user-defined code at construction and destruction, which means that they are used (a pointer to the object is passed to the user-defined constructor/destructor = address taken = used).
This can further be proved by marking the object's constructor with the gnu::pure attribute:
struct Trivial {};
struct NonTrivial {
[[gnu::pure]] NonTrivial() {
//Whatever
}
};
void test() {
Trivial t;
NonTrivial nt;
}
In this case, GCC warns about both of them because it knows that NonTrivial::NonTrivial() doesn't have side-effects, which in turn enables the compiler to prove that construction and destruction of a NonTrivial is a no-op, giving us back our "unused variable" warning. (It also warns about gnu::pure being used on a void function, which is fair enough. You shouldn't usually do that.)
Clang's warning about the following code also does make sense.
struct Hmm {
int m_i;
Hmm(int i): m_i(i) {}
};
void test() {
Hmm hmm = 2; //Case 5 from the question
}
This is equivalent to the following:
void test() {
Hmm hmm = Hmm(2);
}
Construction of the temporary Hmm(2) has side-effects (it calls the user-defined constructor), so this temporary is not unused. However, the temporary then gets moved into the local variable Hmm hmm. Both the move constructor and the destructor of that local variable are trivial (and therefore don't invoke user code), so the variable is indeed unused since the compiler can prove that the behavior of the program would be the same whether or not that variable is present (trivial ctor + trivial dtor + no other access to the variable = unused variable, as explained above). It wouldn't be unused if Hmm had a non-trivial move constructor or a non-trivial destructor.
Note that a trivial move constructor leaves the moved-from object intact, so it truly does not have any side-effects (other than initializing the object that's being constructed).
This can easily be verified by deleting the move constructor, which causes both Clang and GCC to complain.
|
72,114,337 | 72,115,595 | CMake - Install Find script for depencency together with script | I am making a CMake library around some installable SDK. So the dependency tree looks like:
Application --> MyLibrary --> OfficialSDK
This SDK is installed by some setup.exe and does not have a CMake module.
So instead I include a custom find script inside MyLibrary: MyLibrary/cmake/FindOfficialSDK.cmake. Then inside the CMakeLists.txt of MyLibrary I can use find_package(OfficialSDK).
This works well for MyLibrary. I can build it and install it, together with the CMake export. So then Application can run find_package(MyLibrary) out of the box, since MyLibrary was installed properly using CMake.
However, when configuring Application I get an error:
Target "Application" links to target "OfficialSDK" but the target was not found.
Okay, so MyLibrary remembers it needs OfficialSDK, but it cannot find it in this CMake project.
I could solve this by including cmake/FindOfficialSDK.cmake in Application, but I would rather not make my users to copy the find script in case I need to update it in the future.
Is there some way of including the imported target OfficialSDK and install it together with MyLibrary, so Application doesn't need to search for it?
| I found a solution, largely based on https://discourse.cmake.org/t/install-findpackage-script/5307.
Another example I found inside Pagmo2, for a custom FindBoost script: https://github.com/esa/pagmo2/blob/master/pagmo-config.cmake.in#L10
In a nutshell, I've added the following:
Added an install for my custom find script: install(FILE ${CMAKE_CURRENT_DIR}/cmake/FindOfficialSDK ...)
Added a custom *-config.cmake.in script that will be installed, aside from the more automatic *-targets.cmake export
Added an explicit find_dependency(OfficialSDK) (not find_package) inside this config script, but inside a clause that adds the MyLibrary cmake install directory to the CMake module path, so the custom find script is used.
A complete example can be seen this PR: https://github.com/ET-BE/AdsClient/pull/1/files (as well as a bunch of other stuff). The OfficialSDK is TwinCAT's ADS library.
|
72,114,380 | 72,116,921 | Codewars:Path Finder #3: the Alpinist in C++ | I just tried to finish a problem:Path Finder #3: the Alpinist in Codewars. I had passed all basic test cases and there were any errors under my own test cases. But when i submited my solution, my code failed for random test cased. My solution of problem is graph searching based Dijkstra algorithm and priority_queue. I think there my some potential errors i didn't consider. Please help me check it. I have tried achieve it for three hours.
My solution is below.
#include <iostream>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
const int INF = 1e9;
const int WHITE = -1;
const int GRAY = 0;
const int BLACK = 1;
int path_finder(string maze)
{
int result = 0;
vector<pair<int, int>> element;
vector<vector<pair<int, int>>> altitude;
int width = (-1 + sqrt(5 + 4 * maze.size())) / 2;
auto tem = maze.find('\n');
while (tem != string::npos)
{
maze.erase(tem, 1);
tem = maze.find('\n');
}
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
altitude.push_back(element);
if (i >= 1)
altitude[i * width + j].push_back(make_pair(i * width + j - width, abs(maze[i * width + j] - maze[i * width + j - width])));
if (i < width - 1)
altitude[i * width + j].push_back(make_pair(i * width + j + width, abs(maze[i * width + j] - maze[i * width + j + width])));
if (j >= 1)
altitude[i * width + j].push_back(make_pair(i * width + j - 1, abs(maze[i * width + j] - maze[i * width + j - 1])));
if (j < width - 1)
altitude[i * width + j].push_back(make_pair(i * width + j + 1, abs(maze[i * width + j] - maze[i * width + j + 1])));
}
}
int* distance = new int[width * width];
int* state = new int[width * width];
for (int i = 0; i < width * width; ++i)
{
distance[i] = INF;
state[i] = WHITE;
}
priority_queue<pair<int, int>> unfinished;
unfinished.push(make_pair(0, 0));
state[0] = GRAY;
distance[0] = 0;
while (!unfinished.empty())
{
pair<int, int> tem = unfinished.top();
unfinished.pop();
state[tem.second] = BLACK;
if(distance[tem.second] < tem.first * (-1))
continue;
for (int i = 0; i < altitude[tem.second].size(); ++i)
{
if(state[altitude[tem.second][i].first] != BLACK)
{
unfinished.push(make_pair(-1 * altitude[tem.second][i].second, altitude[tem.second][i].first));
if (distance[tem.second] + altitude[tem.second][i].second < distance[altitude[tem.second][i].first])
{
distance[altitude[tem.second][i].first] = distance[tem.second] + altitude[tem.second][i].second;
state[altitude[tem.second][i].first] = GRAY;
}
}
}
}
result = distance[width * width - 1];
return result;
}
| Here is a test case where your code has the wrong answer.
"53072\n"
"09003\n"
"29977\n"
"31707\n"
"59844"
The least cost is 13, with this path:
{1 1 0 0 0}
{0 1 0 0 0}
{0 1 1 1 1}
{0 0 0 0 1}
{0 0 0 0 1}
But your program outputs 15.
|
72,114,591 | 72,118,439 | gsoap - Avoid escaping < and > to < and > | I am using gsoap to access a web service. I generate the code with wsdl2h and soapcpp2 in the following way:
wsdl2h -o BILBO.h http://www.bilbao.eus/WebServicesBilbao/services/ws_bilbaoSOAP?wsdl
soapcpp2 -j -r -CL -1 BILBO.h
And accessing the service in the following way:
#include "soapws_USCOREbilbaoSOAPSoapBindingProxy.h"
#include "ws_USCOREbilbaoSOAPSoapBinding.nsmap"
int main()
{
ws_USCOREbilbaoSOAPSoapBindingProxy service;
char str_buf[128];
const char *servicio = "BUSLISPARO";
const char *usuario = "BILBOBUS";
int cod_linea = 30;
sprintf(str_buf, "<![CDATA[<PETICION><CODIGOLINEA>%d</CODIGOLINEA></PETICION>]]>", cod_linea);
std::string parametros(str_buf);
_ns1__wsBilbao param_req;
param_req.servicio = (char *)servicio;
param_req.usuario = (char *)usuario;
param_req.parametros.push_back(parametros);
if (service.send_wsBilbao(NULL, NULL, ¶m_req) != SOAP_OK)
{
service.soap_sprint_fault(str_buf, sizeof(str_buf));
service.destroy(); // delete data and release memory
printf("err: %s\n", str_buf);
return -1;
}
_ns1__wsBilbaoResponse param_resp;
if (service.recv_wsBilbao(param_resp) != SOAP_OK)
{
service.soap_sprint_fault(str_buf, sizeof(str_buf));
service.destroy(); // delete data and release memory
printf("err: %s\n", str_buf);
return -1;
}
for (int i = 0; i < param_resp.valores.size(); i++)
{
printf("[%d] \"%s\"\n", i, param_resp.valores[i].c_str());
}
service.destroy(); // delete data and release memory
}
My problem is that when I run the code I get the following output:
[0] ""
I expect to get some data. When I preform the same request with Soap UI I do get it.
Comparing the differences between the Soap UI requests and the gsoap requests I notice gsoap is escaping < and > characters. In the following way:
<![CDATA[<PETICION><CODIGOLINEA>30</CODIGOLINEA></PETICION>]]>
Is there a way to tell gsoap no to escape < to < and > to >?
| To send and receive plain XML you can use the _XML built-in type that is a char* string serialized "as-is", i.e. without translation. Then use the _XML type at places where you used char* in the header file for soapcpp2.
In C++ you can define typedef std::string XML; in the header file for soapcpp2 to define an XML type that is serialized "as-is".
I don not fully understand why you are creating a string with <![CDATA[.... You do not have to use CDATA when you are serializing strings, since gsoap serializes strings in valid XML.
|
72,114,811 | 72,121,222 | Calling C++ function using python | I am trying to build python wrapper for a function implemented in C++ that accepts 2d vector and returns 2d vector. I am trying to adapt the code from this to suit my needs.
Input matrix shape: (n*2)
Output matrix shape: (n*2)
I think there is an issue with code.i file but not really sure what exactly is the issue.
If there are any other libraries which can achieve this that works as well. I just need to call the c++ function from python.
Here is complete reproducible example: Google Colab
My files:
code.cpp:
#include <vector>
#include "geomutils.h"
#include "code.h"
using namespace std;
vector< vector<double> > computeConvexHull(vector< vector<double> > i_matrix){
Polygon custompts, customhull;
for (int r = 0; r < i_matrix.size(); r++){
custompts.push_back(Point(i_matrix[r][0], i_matrix[r][1]));
}
computeConvexHull(custompts, customhull);
vector< vector<double> > res;
for(int i = 0;i < customhull.size();i ++) {
res[i][0] = customhull[i].x;
res[i][1] = customhull[i].y;
}
return res;
}
geomutils.cpp:
#include "geomutils.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
void computeConvexHull(Polygon &pts, Polygon &chull) {
chull.clear();
if(pts.size() == 1) {
chull.push_back(pts[0]);
chull.push_back(pts[0]);
return;
} else if(pts.size() == 2) {
chull.push_back(pts[0]);
chull.push_back(pts[1]);
chull.push_back(pts[0]);
return;
}
typedef boost::tuple<double, double> point;
typedef boost::geometry::model::multi_point<point> mpoints;
typedef boost::geometry::model::polygon<point> polygon;
mpoints mpts;
for(int i = 0;i < pts.size();i ++) {
boost::geometry::append(mpts,point(pts[i].x,pts[i].y));
}
polygon hull;
// Polygon is closed
boost::geometry::convex_hull(mpts, hull);
for(auto pt : hull.outer()) {
chull.push_back(Point(pt.get<0>(), pt.get<1>()));
}
}
geomutils.h:
#ifndef GEOMUTILS_H
#define GEOMUTILS_H
#include <vector>
struct Point {
double x,y;
Point(){}
Point(double x, double y):x(x),y(y){}
};
typedef std::vector<Point> Polygon;
void computeConvexHull(Polygon &pts, Polygon &chull);
#endif // GEOMUTILS_H
code.i:
%module code
%{
#include "code.h"
#include "geomutils.h"
%}
%include "std_vector.i"
namespace std {
/* On a side note, the names VecDouble and VecVecdouble can be changed, but the order of first the inner vector matters! */
%template(VecDouble) vector< vector<double> >;
%template(VecVecdouble) vector< vector<double> >;
}
%include "code.h"
The code uses one external library called boost. The way I am trying to generate the wrapper is as follows:
g++ -c -fPIC code.cpp geomutils.cpp
swig -c++ -python code.i
g++ -c -fPIC code_wrap.cxx -I/usr/include/python3.7 -I/usr/lib/python3.7
The first two commands run without giving any error but the third code gives me an error.
The Error is too long to post in the question. But the error can be reproduced using code link.
Update 1:
After trying the changes suggested in answer 1 and running the following commands the code compiles but nothing happens when I try to run the c++ code from python. The code is updated in the same link. "test.py" is a simple python code that calls the computeConvexHull function.
Commands:
g++ -c -fPIC code.cpp geomutils.cpp
swig -c++ -python code.i
g++ -c -fPIC code_wrap.cxx -I/usr/include/python3.7 -I/usr/lib/python3.7
g++ -shared -Wl,-soname,_code.so -o _code.so code.o geomutils.o code_wrap.o
python test.py
| First of all, I just want to say that this is one of the most well-written questions I've seen on SO. So thanks for that.
The issue is that you are defining a template for the same type twice, which you are not allowed to do as-per the SWIG documentation:
The %template directive should not be used to wrap the same template instantiation more than once in the same scope. This will generate an error. For example:
%template(intList) List<int>;
%template(Listint) List<int>; // Error. Template already wrapped.
This error is caused because the template expansion results in two identical classes with the same name. This generates a symbol table conflict. Besides, it probably more efficient to only wrap a specific instantiation only once in order to reduce the potential for code bloat.
Since the type system knows how to handle typedef, it is generally not necessary to instantiate different versions of a template for typenames that are equivalent. For instance, consider this code:
%template(intList) vector<int>;
typedef int Integer;
...
void foo(vector<Integer> *x);
In this case, vector is exactly the same type as vector. Any use of Vector is mapped back to the instantiation of vector created earlier. Therefore, it is not necessary to instantiate a new class for the type Integer (doing so is redundant and will simply result in code bloat).
This issue is, as you suspected, in code.i, where you template both VecDouble and VecVecDouble as vector<vector<double>>.
Based on this answer, I'm guessing what you meant to do was:
%template(VecDouble) vector<double>;
%template(VecVecdouble) vector< vector<double> >;
Which does indeed compile.
|
72,116,513 | 72,125,276 | Eigen::Quaternion::FromTwoVectors(a, b) * a != b | I am trying to get the quaternion representing the rotation from unit vector a to unit vector b.
As a sanity check this quaternion should garantee this equality q * a = b. The Eigen function Quaterniond::FromTwoVector https://eigen.tuxfamily.org/dox/classEigen_1_1Quaternion.html doesn't seem to respect my intuition. You can check here https://godbolt.org/z/rrb3Ev9cf (for a = {0, 0, -1} and b = {-0.0082091040565241327, 0.15209511189816791, -0.89586970189502269}).
Am i missing something ? Is there some condition that a and b must verify for this to be true ?
| A check with R:
> crossprod(c(-0.0082091040565241327, 0.15209511189816791, -0.89586970189502269))
[,1]
[1,] 0.8257828
shows that your vector b is not a unit vector.
|
72,116,742 | 72,128,149 | Changing type of template at run time | I'm trying to make a Matrix struct which would work with various data types, including my Complex struct:
struct Complex {
double re = 0, im = 0;
Complex operator*(const Complex& other) const {
return Complex(re * other.re - im * other.im, im * other.re + re * other.im);
}
Complex operator*(const double& other) const {
return Complex(re * other, im * other);
}
Complex() {}
Complex(double a) : re(a) {}
Complex(double a, double b) : re(a), im(b) {}
};
std::ostream& operator<<(std::ostream& out, Complex z) {
out << z.re << " " << z.im << "i";
return out;
}
template <typename T>
Complex operator*(const T& c, const Complex& z) {
return z * c;
}
The obvious way is to make a template like one in the code below:
template <typename T>
struct Matrix {
std::vector<T> m;
unsigned int rows, cols;
Matrix<Complex> operator*(const Complex& z) const {
Matrix<Complex> result(rows, cols);
for (int i = 0; i < m.size(); i++) {
result.m[i] = m[i] * z;
}
return result;
}
void operator*=(const Complex& z) {
(*this) = (*this) * z; // <- ideally we're trying to get this to work
}
void operator=(const Matrix<T>& other) {
rows = other.rows;
cols = other.cols;
m.resize(rows * cols);
m = other.m;
}
Matrix(const unsigned int& rows, const unsigned int& cols) : rows(rows), cols(cols) {
m.resize(rows * cols);
}
Matrix(const Matrix<T>& other) : rows(other.rows), cols(other.cols) {
(*this) = other;
}
};
int main() {
Complex z(1, 1);
Matrix<double> A(1, 1);
A.m[0] = 2.0;
std::cout << (A * z).m[0] << std::endl; // works as it should because a temporary Matrix<Complex> gets created
A *= z; // and here we're introducing the problem
std::cout << A.m[0] << std::endl;
}
The problem arises when calling *= operator. We're trying to call an unexisting = operator overload. My first attempt was to write something like this instead:
template <typename T_other>
void operator=(const Matrix<T_other>& other) {
rows = other.rows;
cols = other.cols;
m.resize(rows * cols);
for (int i = 0; i < m.size(); i++) {
m[i] = other.m[i];
}
}
This however leads to other problems:
The type of A is still Matrix<double> and after the multiplication it should be Matrix<Complex> to store complex numbers.
There is no conversion from Complex to double as it results in loss of data (the imaginary part).
Also, I would like to avoid creating a template specialization for Matrix<Complex>, but if there's no other way I'll accept it.
| C++ is statically typed. Once you declare a variable and type, you can't change the type of that variable.
template <typename T>
struct Matrix {
void operator*=(const Complex& z) {
(*this) = (*this) * z;
}
}
The *= operator overload for your Matrix doesn't make sense. A Complex can hold the value of a double with imaginary part 0, but a double can never hold the value of a Complex.
Multiplying a real matrix by a complex number necessarily produces a complex matrix. So you try and assign the complex RHS to the real LHS - and either that makes no sense and shouldn't be done, or you have some idea for how to convert that (e.g. keep real part, keep absolute value etc) and then have to implement a Matrix<double> constructor from Matrix<Complex>.
Real numbers are a subset of complex numbers, so just make A a Matrix<Complex> from the beginning if you ever want to make it complex later.
|
72,117,373 | 72,117,524 | Factorization of numbers | I'm trying to write a function that has one integer parameter (let's call it ), which returns as a result a vector consisting of all prime factors of the number , where each factor appears as many times how many times it appears in the factorization of numbers into prime factors.
#include <iostream>
#include <vector>
#include <cmath>
bool is_prime(int n)
{
if (n <= 1)
return false;
for (int i = 2; i < sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
std::vector<int> PrimeFactors(int n)
{
std::vector<int> a, b, temp;
for (int i = 1; i < n; i++)
if (is_prime(i))
temp.push_back(i);
for (int i = 0; i < temp.size(); i++)
for (int j = 0; j < temp.size(); j++)
for (int k = 0; k < temp.size(); k++)
{
if (temp[i] * temp[j] == n)
{
b.push_back(temp[i]);
b.push_back(temp[j]);
return b;
}
if (temp[i] * temp[j] * temp[k] == n)
{
b.push_back(temp[i]);
b.push_back(temp[j]);
b.push_back(temp[k]);
return b;
}
}
}
int main()
{
int n;
std::cin >> n;
std::cin.ignore(1000, '\n');
for (int i : PrimeFactors(n))
std::cout << i << " ";
return 0;
}
Storing number exactly the time it appears in factorization makes this tough a little bit. Could you give an idea for algorithm?
| Use the % operator to find numbers that divide n evenly. Each time you find a factor, divide n by that factor as long as it continues to divide evenly.
std::vector<int> PrimeFactors(int n) {
std::vector<int> r;
for (int i = 2; i * i <= n; i += 1 + (i > 2)) {
while ((n % i) == 0) {
r.push_back(i);
n /= i;
}
}
if (n != 1)
r.push_back(n);
return r;
}
|
72,117,485 | 72,118,361 | undefined reference to inline friend | Why does taking the address of an inline friend not result in code being produced. This works for regular inline functions. Is the declaration not matching the inline friend somehow?
#include <iostream>
namespace S
{
template <unsigned N>
class X
{
int i;
friend X operator+(const X& a, const X& b) noexcept
{
(void)a;
(void)b;
return {};
}
};
inline X<256> operator+(const X<256>&, const X<256>&) noexcept;
}
int main()
{
S::X<256> (*ptr)(const S::X<256>& a, const S::X<256>& b) noexcept = &::S::operator+;
std::cout << (void*)ptr << std::endl;
return 0;
}
$ g++ --version
g++ (GCC) 11.2.1 20220401 (Red Hat 11.2.1-10)
$ g++ -std=c++17 test2.cpp
test2.cpp:18:13: warning: inline function ‘S::X<N> S::operator+(const S::X<N>&, const S::X<N>&) [with unsigned int N = 256]’ used but never defined
18 | inline X<N> operator+(const X<N>&, const X<N>&) noexcept;
| ^~~~~~~~
/usr/bin/ld: /tmp/ccoA1Nxj.o: in function `main':
test2.cpp:(.text+0xc): undefined reference to `S::X<256u> S::operator+<256u>(S::X<256u> const&, S::X<256u> const&)'
collect2: error: ld returned 1 exit status
| There is no argument-dependent lookup when taking the address of an overload set.
So, the initialization of the function pointer doesn't require the compiler to instantiate X<256> to figure out whether there is a operator+ in it. For an unqualified function call this would happen.
Neither does the declaration of operator+ outside the class require any of the involved types to be complete. So there is no implicit instantiation of X<256> there either.
Consequently, when the address of the function is taken, X<256> has not been instantiated and so the compiler can't be aware of the friend definition of the function, which is then also not instantiated.
In the end, there is no definition for the function, which however was ODR-used by taking its address and therefore the program is ill-formed, no diagnostic required.
This can be fixed by having X<256> be instantiated before taking the address, e.g. by writing static_assert(sizeof(S::X<256>)); before main to cause implicit instantiation or template S::X<256>; to cause explicit instantiation.
|
72,117,986 | 72,119,927 | c++ write date as bytes in binary file and read in same view | I have multiple dates in yyyy-mm-dd format, which I need to write in a binary file as bytes and then read them in the same format. Here is the method I have for writing the file (but seems it is not fully correct):
fstream f("binaryOut.bin", ios::out | ios::binary);
string dateString;
char arr[4];
char dateArray[8];
for (int i = 0; i < amountOfDates; i++)
{
stringstream str;
char yearArr[] = {2, 0, 2, 2};
strncpy_s(dateArray, yearArr, 4);
int year = 2022;
char generatedDay = 0, generatedMonth = 0;
generatedMonth = getGeneratedValue(1, 12);
dateArray[4] = '-';
dateArray[5] = generatedMonth;
generatedDay = getGeneratedValue(1, 31);
dateArray[6] = '-';
dateArray[7] = generatedDay;
str >> dateString;
strcpy_s(arr, dateString.c_str());
f.write(dateArray, 8);
}
f.close();
Method for reading the file:
fstream f("binaryOut.bin", ios::in | ios::binary);
char inputArr[8];
for (int i = 0; i < amountOfDates; i++)
{
f.read(inputArr, 8);
for (int i = 0; i <= 8; i++)
{
if (isdigit(inputArr[i]))
{
cout << inputArr[i] - '0';
}
else if (inputArr[i] == '-')
{
cout << inputArr[i];
}
else
{
cout << inputArr[i] << static_cast<int>(inputArr[i]);
}
}
cout << endl;
}
When trying to read, I'm getting this output in the console:
☻20■-2■-2-♠6-↨23╠-52
☻20■-2■-2-♂11-7╠-52
☻20■-2■-2-♠68╠-52
☻20■-2
It seems, when I am trying to read the file, I am getting char's but not in the same format that I need.
Can someone help with fixing my issue?
| I noticed that in your code you use numbers instead of chars to represent the year (e.g. char yearArr[] = {2, 0, 2, 2};). Is that by design? I would prefer to use char yearArr[] = {'2', '0', '2', '2'}; In fact, I would convert everything to char, so that I can read/write to the file using char.
Another observation I made is that your read char array (char inputArr[8];) does not have a null terminator (e.g. inputArr[8] = '\0';). This should eliminate the extra garbage characters at the end.
There are several questions I still have about your code but here's a simpler but similar problem that you can use as a guide:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
void WriteToBinaryFile();
void ReadFromBinaryFile();
void GetYear(char*);
void GetMonth(char*);
void GetDay(char*);
int main()
{
srand(time(0));
WriteToBinaryFile();
ReadFromBinaryFile();
return 0;
}
void WriteToBinaryFile()
{
std::ofstream binary_file("binaryOut.bin", std::ios::out | std::ios::binary);
char date[10] = { 'Y', 'Y', 'Y', 'Y', '-', 'M', 'M', '-', 'D', 'D' };
GetYear(date);
GetMonth(date);
GetDay(date);
if (!binary_file)
{
std::cout << "Can't open binary file for write" << std::endl;
return;
}
binary_file.write(date, sizeof(date) / sizeof(char));
binary_file.close();
if (!binary_file.good())
{
std::cout << "Error occurred during write" << std::endl;
return;
}
}
void ReadFromBinaryFile()
{
std::ifstream binary_file("binaryOut.bin", std::ios::out | std::ios::binary);
if (!binary_file)
{
std::cout << "Can't open binary file for read" << std::endl;
return;
}
char date[10];
binary_file.read(date, sizeof(date) / sizeof(char));
binary_file.close();
if (!binary_file.good())
{
std::cout << "Error occurred during read" << std::endl;
return;
}
date[10] = '\0';
std::cout << "Binary file: " << date << std::endl;
}
void GetYear(char* date)
{
const char year[] = { '2', '0', '2', '2' };
date[0] = year[0];
date[1] = year[1];
date[2] = year[2];
date[3] = year[3];
}
void GetMonth(char* date)
{
int month = (std::rand() % 11) + 1;
if (month > 9)
{
int first_digit = month % 10;
int second_digit = month / 10;
date[5] = first_digit + '0';
date[6] = second_digit + '0';
}
else
{
date[5] = '0';
date[6] = month + '0';
}
}
void GetDay(char* date)
{
int day = (std::rand() % 31) + 1;
if (day > 9)
{
int first_digit = day % 10;
int second_digit = day / 10;
date[8] = first_digit + '0';
date[9] = second_digit + '0';
}
else
{
date[8] = '0';
date[9] = day + '0';
}
}
The output of this code: Binary file: 2022-05-04
|
72,118,002 | 72,118,470 | How can i store all my vector elements in a hash table c++ | Code which i Have Done##
class vehicle
{
public:
vehicle();
virtual ~vehicle();
void addVehicle();
void deleteVehicle();
void printvehicle(vehicle v);
void show();
void showleft();
void vehcileLoad();
protected:
private:
std::string pltno;
date dt;
lime arrive;
lime departure;
};
int static totalvehicle=0,totalcar=0,totalamt=0,i=0,z=0;
void vehicle::addVehicle()
{
vehicle *v = new vehicle;
std::cin.ignore();
std::cout<<"Enter vehicle number : ";
std::getline(std::cin, v->pltno);
std::cout<<"Enter arrival time in hours minutes and seconds : ";
std::cin>>v->arrive.hh>>v->arrive.col1>>v->arrive.mm>>v->arrive.col2>>v->arrive.ss;
std::cout<<"Enter date in day month and year: ";
std::cin>>v->dt.day>>v->dt.sym1>>v->dt.month>>v->dt.sym2>>v->dt.year;
veh.at(i).pltno=v->pltno;
veh.at(i).arrive.hh=v->arrive.hh;
veh.at(i).arrive.mm=v->arrive.mm;
veh.at(i).arrive.ss=v->arrive.ss;
veh.at(i).dt.day=v->dt.day;
veh.at(i).dt.month=v->dt.month;
veh.at(i).dt.year=v->dt.year;
What i hope to accomplish
This is part of the code i have this is also how i store data into the vector using v->pltno = ... etc I would like to know how can i store all elements within the vector into a hash table please help i am clueless how can i store all items with veh and vehleft into a hash table 1 being for vehciles in parking and 1's which have left
what would the code look like to perform such a task?
Other code of vector
std::vector<vehicle> veh(100);
std::vector<vehicle> vehleft(100);
Thank you?
| Assuming all of your vehicle objects are stored in a std::vector<Vehicle>, using a std::unordered_map<std::string, Vehicle> is a very simple way of getting a hash table populated with the vehicles:
#include <unordered_map>
#include <vector>
#include <string>
//...
class Vehicle
{
//...
};
void foo()
{
std::vector<Vehicle> veh(100);
//...
std::unorderd_map<std::string, Vehicle> mapVehicle;
for (auto& v : veh)
{
// add the vehicle v to the hash table
mapVehicle[v.pltNo] = v;
}
//...
}
Once you do that, you lookup a vehicle using the plate number:
Vehicle& v = mapVehicle["ABC123"]; // this is the vehicle with license plate ABC123
or to be safe (since using [] to do a search will add an empty entry if not found), you can check if the vehicle exists using std::unordered_map::find():
auto iter = mapVehicle.find("ABC123");
if (iter != mapVehicle.end())
{
Vehicle& v = iter->second;
}
|
72,118,060 | 72,118,266 | how to delete a row from the QListWidget in which the button was pressed | how to delete a line from QListWidget in which the button was pressed? i know to delete some line (foto) it is necessary to cause method removeItemWidget but for it it is necessary QListWidgetItem but I do not know how to receive it having QWidget which I received from sender ()
The code I use to create strings:
QLayout* l = new QHBoxLayout;
auto le=new QLineEdit;
le->setMaximumWidth(250);
l->addWidget( le );
auto le2=new QLineEdit;
l->addWidget( le2 );
QPushButton* btn = new QPushButton( "Х" );
btn->setObjectName(QString::number(ggg));
connect( btn, SIGNAL( clicked() ), SLOT( close() ) );
btn->setFixedWidth(22);
l->addWidget( btn );
wgt->setLayout( l );
QListWidgetItem* item = new QListWidgetItem( ui->listWidget);
item->setSizeHint( wgt->sizeHint() );
ui->listWidget->setItemWidget(item,wgt);```
| removeItemWidget() only removes the item from the view but it does not delete it so you will have a memory leak. I am not sure if this is what you want, I guess not. But to remove widget from the item, you can delete the widget and it is removed automatically. So the following code should delete the widget and the row as well. This is what I understand from your requirements.
connect( btn, &QPushButton::clicked, [item, wgt]{ delete wgt; delete item; } );
Of course you can only place this line after line
QListWidgetItem* item = new QListWidgetItem( ui->listWidget);
I have not tested it, you may need to use wgt->deleteLater(); instead of delete wgt.
|
72,118,896 | 72,119,036 | why i am getting this error request for member set in b which is of non class type box[5] | why I am getting this request for member set in b which is of non class type box[5]?
I am calculating volume of box and storing length breadth and volume in box array of objects
what can I do to solve this?
#include<iostream>
using namespace std;
class box
{
int length;
int breadth;
int height;
int n;
int volume;
box *b;
public:
box()
{
}
void set(int n)
{
for(int i=0;i<n;i++)
{this->b=new box[5];
int len,bre,hei,vol;
cout<<"enter length"<<endl;
cin>>len;
cout<<"enter breadth"<<endl;
cin>>bre;
cout<<"enter height"<<endl;
cin>>hei;
cout<<"enter volume"<<endl;
cin>>vol;
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
}
}
void get()
{
for(int i=0;i<n;i++)
{
cout<<"length "<<b[i].length;
cout<<"breadth "<<b[i].breadth;
cout<<"height "<<b[i].height;
cout<<"volume "<<b[i].volume;
}
}
};
int main()
{
box b[5];
b.set(5);
b.get();
}
| emphasized textThe variable b declared in main
box b[5];
has an array type. Arrays do not have member functions. So this statement
b.set(5);
is incorrect. You could write for example
b[0].set( 5 );
However within the member function set there is used uninitialized pointer b
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
that invokes undefined behavior.
So your code as is just does not make a sense.
It seems you need a static member function like for example
static void set(box b[], int n)
{
for(int i=0;i<n;i++)
{
int len,bre,hei,vol;
cout<<"enter length"<<endl;
cin>>len;
cout<<"enter breadth"<<endl;
cin>>bre;
cout<<"enter height"<<endl;
cin>>hei;
cout<<"enter volume"<<endl;
cin>>vol;
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
}
}
And call it like
box b[5];
box::set( b, 5 );
In this case you should remove the data members b and n
int n;
box *b;
in the class definition.
The function get can be declared and defined the following way
void get() const
{
cout<<"length "<< length << '\n';
cout<<"breadth "<< breadth << '\n';
cout<<"height "<< height << '\n';
cout<<"volume "<< volume << '\n';
}
And for the declared array in main the function can be called the following way
for ( const auto &item : b )
{
item.get();
cout << '\n';
}
|
72,119,362 | 72,120,090 | Formatting input in C++ | So I am writing a program, and need to use some formatting to pretty up the output. Right now, the way I write it is like this (as an example):
cout << "|" << setfill('=') << setw(40) << "|" << endl;
cout << "| What is your name?: ";
cin >> userName;
cout << setfill(' ') << setw(40 - 21 - userName.size()) << "|" << endl;
cout << "|" << setfill('=') << setw(40) << "|" << endl;
What this should be outputting is this (the user's input is in all-caps):
|========================================|
| What is your name?: ALARIC |
|========================================|
but what I get is this:
|========================================|
| What is your name?: ALARIC
|
|========================================|
is there a way to solve this, and/or what am I doing wrong?
| This string "\033[F" moves the cursor up one line. What I did is move the cursor up one line after receiving the username and then reprinting the second line with the '|' symbol at the end.
This code only works if the username is not too long.
#include <iostream>
int main()
{
std::string username;
std::string second_line = "| What is your name?: ";
std::cout << "|========================================|" << std::endl;
std::cout << second_line;
std::cin >> username;
int line_size = second_line.size() + username.size();
/* assumes line_size < 41 */
std::cout << "\033[F" << second_line << username << std::string(41 - line_size, ' ') << "|" << std::endl;
std::cout << "|========================================|" << std::endl;
return 0;
}
Here are two examples of the output:
|========================================|
| What is your name?: username |
|========================================|
|========================================|
| What is your name?: Alaric |
|========================================|
I tried this on my Linux machine and with an online compiler. Both worked, but I haven't tried it on a Windows machine.
|
72,119,874 | 72,120,187 | Why initializing a 'const reference to base' object from 'constexpr derived' object doesn't yields constant expression? | I have this simple example:
struct base
{
constexpr base () {};
};
struct derived: public base
{
constexpr derived () {};
};
int main()
{
constexpr derived d{};
constexpr const base &b = d; // why error?
}
G++ gives me the following error:
error: '(const base&)(& d)' is not a constant expression
And clang++ gives me following error:
error: constexpr variable 'b' must be initialized by a constant
expression.
note: reference to subobject of 'd' is not a constant
expression. Add 'static' to give it a constant address.
It's clear to me that clang gives the solution but I cannot understand why the problem is solved?
It said that "the reference to subobject of d is not a constant expression.", and the subobject here has constexpr constructor so why it's not constant expression?
Finally, I don't understand why using static solves the problem?
Please includes the answer with a quote from the standard (if possible).
| The explanation given by Clang is correct.
Constexpr doesn't change the storage of a variable (where it's put in memory). If you declare a non-static constexpr variable, it'll still go onto the stack, just like all other non-static local variables do.
int test() {
constexpr int a = 3; //a gets created here and put on the stack
const int *b = &a; //Pointer to a location on the stack
} //a gets destroyed when the function ends
This means that the address of that local variable can change with every invocation of the function. There can also be multiple copies of the variable at any given time, i.e. if multiple threads execute the function or if the function recurses.
The overall net effect is that the address of a local variable can never be a constant expression, no matter if that variable is const, constexpr, volatile, or anything else.
The static keyword changes this. It "promotes" the local variable into static storage, meaning that it behaves like a global variable that is only visible in that function. In particular, the variable has a fixed address and there is only one copy of the variable, no matter how often (if at all) the function gets executed. The address of a global variable is a constant expression.
If you want a single, global, constant instance of derived d, just add static in front of it like Clang suggests.
|
72,119,906 | 72,765,374 | cmake problem of target type when using swig with C++17 | Things are getting confused for me, so I hope to be clear.
I made a c++17 library (called here myLib), and I bind it with python using swig. Everything is working when I compile by hand.
Now, I would like to automatize and clean my work using cmake: no problem for the library.
But things are getting more obscure to me when it comes to creating the binding with cmake.
I came with the following cmake sample:
include(FindSWIG)
find_program(SWIG_PATH swig)
find_package(SWIG 4.0 COMPONENTS python)
include(UseSWIG)
find_package(PythonLibs 3 REQUIRED)
find_package(PythonInterp ${PYTHONLIBS_VERSION_STRING} REQUIRED)
set(CMAKE_SWIG_FLAGS -py3)
message("PYTHONLIBS_VERSION_STRING: ${PYTHONLIBS_VERSION_STRING}")
message("CMAKE_SWIG_FLAGS: ${CMAKE_SWIG_FLAGS}")
add_custom_target(
binding_target
)
include_directories("${PROJECT_SOURCE_DIR}/external/include" "${PROJECT_SOURCE_DIR}/include" ${PYTHON_LIBRARIES})
# If I use the following line instead to the previous, I get an error of target type non-compilable
# target_include_directories(binding_target "${PROJECT_SOURCE_DIR}/external/include" "${PROJECT_SOURCE_DIR}/include" ${PYTHON_LIBRARIES})
set_source_files_properties(py_myLib.i PROPERTIES CPLUSPLUS ON)
# If I use the following line, I get an error of target type non-compilable.
# target_compile_features(binding_target SHARED cxx_std_17)
swig_add_library(binding_target
TYPE SHARED
LANGUAGE python
SOURCES py_myLib.i
)
swig_link_libraries(binding_target ${PYTHON_LIBRARIES} USE_TARGET_INCLUDE_DIRECTORIES)
With the previous code, the command cmake .. is exiting without error, but the compilation with make is returning errors as the compiler is not using the option -std=c++17 to compile.
(by the way, I am wondering why make is compiling while make binding_target does nothing, I would expect the opposite.)
I tried to add a C++17 feature to the compilation with the line target_compile_features but then, I get an error from cmake .. about a target_compile_features called with non-compilable target type
So my question is: how can I build properly (inside a target) the swig binding with cmake
(precising the include directories and compilation option for this target) ?
| I came up with this solution (do not hesitate to improve it):
include(FindSWIG)
find_program(SWIG_PATH swig)
find_package(SWIG 4.0 COMPONENTS python)
include(UseSWIG)
find_package(PythonLibs 3 REQUIRED)
find_package(PythonInterp ${PYTHONLIBS_VERSION_STRING} REQUIRED)
set(CMAKE_SWIG_FLAGS -py3)
message("PYTHONLIBS_VERSION_STRING: ${PYTHONLIBS_VERSION_STRING}")
message("CMAKE_SWIG_FLAGS: ${CMAKE_SWIG_FLAGS}")
#
set_source_files_properties(py_myLib.i PROPERTIES CPLUSPLUS ON)
set_property(SOURCE py_myLib.i PROPERTY SWIG_MODULE_NAME py_myLib)
set (UseSWIG_TARGET_NAME_PREFERENCE STANDARD)
swig_add_library(py_myLib
TYPE SHARED
LANGUAGE python
SOURCES py_myLib.i
)
# For Swig wrapping
set_property(TARGET py_myLib PROPERTY SWIG_INCLUDE_DIRECTORIES
"${PROJECT_SOURCE_DIR}/external/include"
"${PROJECT_SOURCE_DIR}/include"
)
# For Cxx compilation
set_property(TARGET py_myLib PROPERTY INCLUDE_DIRECTORIES
"${PROJECT_SOURCE_DIR}/external/include"
"${PROJECT_SOURCE_DIR}/include"
${PYTHON_INCLUDE_PATH}
)
set_property(TARGET py_myLib PROPERTY COMPILE_OPTIONS -shared -std=c++17 ) #
# swig_link_libraries(
target_link_libraries( py_myLib
${PYTHON_LIBRARIES}
)
#
target_include_directories(py_myLib
PRIVATE
# where the library itself will look for its internal headers
${CMAKE_SOURCE_DIR}/include #
${CMAKE_SOURCE_DIR}/external/include
PUBLIC
# where top-level project will look for the library's public headers
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}/include>
)
|
72,119,987 | 72,120,018 | getting error in understanding friend function in c++ | Why am I am getting an "expected identifier" error before .token?
Please provide a solution to understand friend function properly.
At first, I am getting a forward declaration error, but I resolved that one by myself.
#include<iostream>
using namespace std;
class a;
class b
{
public:
void search(a and);
};
class a
{
string name;
friend void b::search(a and);
public:
};
void b::search(a and)
{
cout << and.name;
}
int main()
{
}
| For compatibility with old keyboards and encoding schemes where some symbols weren't available, certain keywords can be used in place of symbols. Among them, and is a valid replacement for &&. So your and.name is actually getting parsed as &&.name, which is a syntax error.
The (unfortunate) solution to your problem is: Don't name variables and or any of the other words on that list.
|
72,120,029 | 72,120,169 | boost::multiprecision::cpp_int acting like unsigned long long | So I have a programming assignment in which I have to work with 64 digit numbers. I am currently using the boost::multiprecision::cpp_int library but I'm not able to use it on large numbers.
For example-
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
boost::multiprecision::cpp_int n1 =123341257612045876129038576124390847381295732;
}
This is giving the error that the code is too long.
After experimentation, it seems like cpp_int (supposed to contain as large a number as you want) is acting like an unsigned long long (shown in the picture above), how do I solve this?
| Use the string constructor, because you cannot express the initializer in C++, otherwise.
Live On Coliru
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main() {
boost::multiprecision::cpp_int n1("123341257612045876129038576124390847381295732");
n1 *= n1;
n1 *= n1;
std::cout << n1 << "\n";
}
Prints
231437371927256216552064578371685752056581253909626001052591740261122589692668963795268703088073326299461305156397520102373182511147316463882992573577585984095769469664077598976
Which is ~2.31 × 10^176
|
72,120,058 | 72,120,082 | Function GetDriveTypeW always returns DRIVE_NO_ROOT_DIR | As title says, standard Windows GetDriveTypeW returns value 1 (DRIVE_NO_ROOT_DIR) for all passed paths.
Documentation says
The root path is invalid; for example, there is no volume mounted at
the specified path.
Although I'm pretty sure the supplied paths (e.g. "C:\\temp", "c:\\temp") is valid and is fixed drive (hard disk).
Am I missing something? What could possibly cause this? Any help would be appreciated - I'm not very familiar with WinAPI.
bool FileAttributesRetriever::IsExternalPath(const std::filesystem::path& path)
{
uint32_t driveType = GetDriveTypeW(path.wstring().c_str()); // Always 1 / DRIVE_NO_ROOT_DIR
switch (driveType)
{
case DRIVE_REMOTE: // Network storage.
case DRIVE_REMOVABLE: // External drive.
{
return true;
}
default:
{
return false;
}
}
}
| The documentation also says that the argument must be:
The root directory for the drive.
A trailing backslash is required...
That is you should call it with C:\ if you want to check the C: drive, or C:\temp\ if you want to check the drive mounted at C:\temp.
|
72,120,369 | 72,125,589 | Number of friendly pairs in vector | I'm trying to write a function that accepts a vector of integers as a parameter and returns the number of friendly pairs that can be found in that vector. The function must not use any other auxiliary functions.
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to another number and vice versa.
#include <iostream>
#include <vector>
int Number_Of_Friendly_Pairs(std::vector<int>a) {
std::vector<int>b;
for (int i = 0; i < a.size(); i++) {
int sum_of_divisors = 0;
for (int j = 1; j < a[i]; j++)
if (a[i] % j == 0)
sum_of_divisors += j;
b.push_back(sum_of_divisors);
}
int number = 0;
for (int i = 0; i < a.size(); i++)
for (int j = i + 1; j < b.size(); j++)
if (a[i] == b[j])
number++;
return number;
}
int main()
{
std::vector<int>b{220, 1184, 284, 1210, 2620, 2924};
std::cout << Number_Of_Friendly_Pairs(b);
return 0;
}
Is my code completely accurate? For vector {220, 1184, 284, 1210, 2620, 2924} it gives correct output (which is 3). However, I'm not sure will it give correct output for every case.
|
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to another number and vice versa.
However, the code only tests that some sum of divisors equal to some number. The vice versa part is sorely missing. For example, the code claims one friendly pair in {7, 8}.
You need to test for (a[i] == b[j]) && (b[i] == a[j]).
|
72,120,435 | 72,122,188 | Calculating surface normals of dynamic mesh (without geometry shader) | I have a mesh whose vertex positions are generated dynamically by the vertex shader. I've been using https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal to calculate the surface normal for each primitive in the geometry shader, which seems to work fine.
Unfortunately, I'm planning on switching to an environment where using a geometry shader is not possible. I'm looking for alternative ways to calculate surface normals. I've considered:
Using compute shaders in two passes. One to generate the vertex positions, another (using the generated vertex positions) to calculate the surface normals, and then passing that data into the shader pipeline.
Using ARB_shader_image_load_store (or related) to write the vertex positions to a texture (in the vertex shader), which can then be read from the fragment shader. The fragment shader should be able to safely access the vertex positions (since it will only ever access the vertices used to invoke the fragment), and can then calculate the surface normal per fragment.
I believe both of these methods should work, but I'm wondering if there is a less complicated way of doing this, especially considering that this seems like a fairly common task. I'm also wondering if there are any problems with either of the ideas I've proposed, as I've had little experience with both compute shaders and image_load_store.
| See Diffuse light with OpenGL GLSL. If you just want the face normals, you can use the partial derivative dFdx, dFdy. Basic fragment shader that calculates the normal vector (N) in the same space as the position:
in vec3 position;
void main()
{
vec3 dx = dFdx(position);
vec3 dy = dFdy(position);
vec3 N = normalize(cross(dx, dy));
// [...]
}
|
72,120,862 | 72,125,127 | Indexing JSON object in C++ | I am looking to parse a JSON object much more efficiently than I am now. Currently I'm running through a range-based for loop to index the key-value elements (see below). Is it possible to run through all of the records inside of a JSON object and parse particular fields w/o a loop?
#include "nlohmann/json.hpp"
using json = nlohmann::json;
json myObj = json::parse(apiResponse);
for (auto& element : myObj.items()) {
if (element.key() == "batters") {
for (auto& element2 : element.value()) {
std::cout << element2["batter"]["id"].get<std::string>() << std::endl;
}
}
}
Here's an example of one JSON API response:
{
"id": "0001",
"type": "donut",
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
]
},
}
{
"id": "0002",
"type": "donut",
"batters":
{
"batter":
[
{ "id": "2001", "type": "Lowfat" },
]
},
}
Thank you!
CookieCrisp
| According to the documentation at https://json.nlohmann.me/api/basic_json/at/ you can use the at()-method, which has a constant complexity when it's used with a location index parameter.
So for example you could do something like this:
std::cout << myObj.at(2)["batter"]["id"].get<std::string>() << std::endl;
Note that your JSON-fields must always be at the same position for this.
If that's not the case you could also use the field name as a key to find the field-object you need.
But then you will have logarithmic complexity.
std::cout << myObj.at("batters")["batter"]["id"].get<std::string>() << std::endl;
|
72,121,621 | 72,121,717 | When does std priority queue compare the values? | I have a priority queue and the compare function references a value accessed by multiple threads. So it has to be protected by a mutex. Except I don't know when this compare function is ran. Is it ran when I push a value or when I pop a value? Example code below.
#include <iostream>
#include <queue>
#include <mutex>
using namespace std;
int main()
{
int compare = 7;
mutex compare_m;
auto cmp = [&](int a, int b) {return abs(compare - a)>=abs(compare-b);};
priority_queue<int, vector<int>, decltype(cmp)> x(cmp);
mutex x_m;
//in thread
{
scoped_lock m1(x_m);
//do I need this?
scoped_lock m(compare_m);
x.push(6);
}
//in thread
{
scoped_lock m1(x_m);
//do I need this?
scoped_lock m(compare_m);
x.pop();
}
}
| To answer the question, if it is not documented anything can happen (and then we cannot then reason about when comparator is invoked).
If we take a look into cppreference, push is defined in terms of push_heap, which then reorganizes the elements into a heap. Given it then needs to reorganize, we can reason that it invokes the comparator. A similar situation happens with pop, that invokes pop_heap, which again modifies the underlying heap. So again, invoking comparator.
So the above implies you need a critical section on both (however please notice the comments regarding whether it is actually safe to change the behaviour of comparison function while the pq contains elements).
|
72,122,018 | 72,149,017 | How can I get a consistent, unique, identifier for a unique class combination? | I need a way to identify a unique combination of template types that gives me an easily indexable identifier.
I have the following class:
#include <cstdint>
typedef std::uint32_t IDType;
template<class T>
class TypeIdGenerator
{
private:
static IDType m_count;
public:
template<class U>
static IDType GetNewID()
{
static const IDType idCounter = m_count++;
return idCounter;
}
};
template<class T> IDType TypeIdGenerator<T>::m_count = 0;
Which works, but when utilized across dll and exe, each "instance" in each process resets the count, so if in the .dll I have:
IDType id = TypeIdGenerator<A>::GetNewID<B>();
It will be a different value to the same call made in the .exe with the same two classes:
IDType id = TypeIdGenerator<A>::GetNewID<B>();
Of course, this only happens if the types for different classes are generated in different orders.
I understand that the static members are static across each process, and the dll is another process, so how else can I easily retrieve a unique id that's consistent?
I'd prefer to use standard methods, no special compiler extensions or flags etc.
EDIT: More info on my use case.
I have a template class that holds another type so I can operate on arbitrary data using that template type. Very simplified:
class ComponentBase
{
public:
virtual ~ComponentBase() {}
virtual void DestroyData(unsigned char* data) const noexcept = 0;
virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0;
virtual void ConstructData(unsigned char* data) const = 0;
};
template<class C>
class Component : public ComponentBase
{
public:
typedef C type;
virtual void DestroyData(unsigned char* data) const noexcept override
{
C* dataLocation = std::launder(reinterpret_cast<C*>(data));
dataLocation->~C();
}
virtual void MoveData(unsigned char* source, unsigned char* destination) const override
{
new (&destination[0]) C(std::move(*reinterpret_cast<C*>(source)));
}
virtual void ConstructData(unsigned char* data) const override
{
new (&data[0]) C(*m_component);
}
};
This is because instances of A or B need to be stored alongside each other in unsigned char* arrays. By storing a map of std::unordered_map<IDType,ComponentBase*>s I can keep access to all of the constructors, destructors, move operators etc.
I have a container that provides me information of which index in an unsigned char* is IDType for A or B etc.
So when operating on my data, I would have a container of std::vector<IDType> which from beginning to end provides me with every type stored in unsigned char* arbitrary.
I can use the IDType to lookup my unordered_map<IDType, ComponentBase*> so that I can operate on the type stored in arbitrary.
Obviously it's a little more involved than that or I'd just store the ComponentBase*s, but that's the general gist of why I need to be able to generate consistent type ids of some indexable type. Consistent only during the same execution of my program, not between different executions (though that would be a bonus).
I am using MingW64 delivered through MSYS2.
| Instead of incrementing a counter to create the type IDs, you could instead use a hash function to generate a 'unique' hash. While there is some chance of collision, the risk is very low if the hashing function is efficient. This approach would provide consistent IDs for each type throughout an invocation of the program.
To this end, C++ actually provides a typeid operator which returns a type_info class instance. The type_info class implements a hash_code() function which is guaranteed to return a unique hash for each unique type.
The documentation notes that this hash can change between invocations of the same program, so this will not work across multiple different invocations.
The type_info class can also be used to get a unique type_index which can be used directly to index into an associate container.
|
72,122,101 | 72,123,297 | Question about some specific differences between new T() and new T in C++11 and afterwards | Attention please: you may think this post is a duplicate to this old post. But the said post was more than 12 years ago and none of the answers mentions the C++11 and afterwards.
And what's more, my question is about the comment of the answer which has most votes and my question is about the detailed code snippet below.
As per the comment of this answer, which says that[emphasise mine]:
With C++11 you can do this in stack too; B obj{}; will make the object value-initialized (to 0s) as opposed to B obj; which will be default-initialized (garbage).
But it seems that there is no difference between them for this code snippet.
Tips: Pay attention to the outputs of the said code snippet.
new Line() is default-initialized but it's not garbage indeed.
Here is the aforementioned code snippet:
#include <utility>
#include <iostream>
#include <string>
template<typename T>
struct Point {
T x;
T y;
};
struct Line{
Point<double> head;
Point<double> tail;
double *demo;
int color;
//std::string comment;
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const Point<T>& point)
{
os << "(" << point.x <<"," << point.y <<")";
return os;
}
std::ostream& operator<<(std::ostream& os, const Line& line)
{
os << "head: " << line.head << std::endl;
os << "head: " << line.tail << std::endl;
os << "demo=" << static_cast<void*>(line.demo) << std::endl;
os << "color=" << line.color << std::endl;
//os << "string=" << line.comment << std::endl;
return os;
}
int main()
{
auto ptr2lineWithBracket = new Line();
std::cout << *ptr2lineWithBracket;
std::cout << "==================" << std::endl;
auto ptr2lineWithout = new Line;
std::cout << *ptr2lineWithout;
}
Here is the output:
head: (0,0)
head: (0,0)
demo=0
color=0
==================
head: (0,0)
head: (0,0)
demo=0
color=0
|
Question about some specific differences between new T() and new T
new T() is value initialisation. For aggregate classes such as Line and Point<T> this means that all sub objects are value initialised. For primitive objects such as double* and int this means zero initialisation.
new T is default initialisation. For aggregate classes such as Line and Point<T> this means that all sub objects are default initialised. For primitive objects such as double* and int this means no initialisation. If an object isn't initialised1, then it has an indeterminate value. This means that their value is indeterminate. If a program reads an indeterminate value (of a type other than narrow character type), then the behaviour of the program is undefined. This is to be avoided. Don't do this.
The example program reads indeterminate values, and its behaviour is undefined.
in C++11 and afterwards
There hasn't been a change regarding these since C++03 where value initialisation was added to the language.
Not related to the example directly, but a new syntax was added for value initialisation in C++11:new T {} (in addition to analogous syntaxes using curly braces for temporary and variable initialisation).
1 Note that objects with static storage duration are zero initialised before any other initialisation regardless of the syntax you use.
|
72,122,119 | 72,122,228 | why the raw pointer get by std::unique_ptr's get() can not delete the object and how is that implemented | As the following code presents, I tried to delete the object by the raw pointer get from a unique_ptr. But, as the output shows, the complier reported errors. However, for raw pointers, we can do this int *p1 = new int{100}; int* p2 = p1; delete p2;.
Besides, I thought that unique_ptr maintain its ownership by move semantics. As the get() function of unique_ptr returns the raw pointer, how does the unique_ptr can still have the ownership of the object. Meanwhile, why the raw pointer doesn't get the ownership. At the same time, I am confusing how does this implemented. Thanks.
#include <iostream>
#include <memory>
int main(int argc, char const *argv[])
{
std::unique_ptr<int> newPtr = std::make_unique<int>(1234);
std::cout << *newPtr << std::endl;
int* rawInt = newPtr.get();
*rawInt = 200;
delete rawInt;
rawInt = nullptr;
std::cout << *newPtr << std::endl;
return 0;
}
The code was performed on MacOs and the output is:
| std::unique_ptr is a really simple class. Conceptually, it's basically just this:
template <typename T>
class unique_ptr
{
private:
T* ptr;
public:
unique_ptr(T* p) ptr{p} {}
~unique_ptr() { delete ptr; }
T* get() { return ptr; }
T* release() {
T* p = ptr;
ptr = nullptr;
return p;
}
// other stuff
};
It just has a pointer member, and deletes the pointed-to object in its destructor. In reality there's a bit more to it, but that's essentially it.
The get member just returns a copy of the unique_ptr's managed pointer. That's it. Since the unique_ptr's pointer member is still pointing to that object, its destructor will still delete the object. If you also delete that object via another pointer to it then it will get deleted twice, which results in undefined behavior.
The release member function, on the other hand, sets the unique_ptr's pointer member to nullptr before returning a copy of its original value. Since its member pointer is null, its destructor won't delete anything.
|
72,122,147 | 72,127,784 | Problem with Boost Fibonacci Heap at the moment of erasing an element | I'm getting an unrelated error with Boost's Fibonacci Heap when I use the erase()method:
astar: /usr/include/boost/intrusive/list.hpp:1266: static boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::iterator boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::s_iterator_to(boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::reference) [with ValueTraits = boost::intrusive::bhtraits<boost::heap::detail::heap_node_base<false>, boost::intrusive::list_node_traits<void*>, (boost::intrusive::link_mode_type)1, boost::intrusive::dft_tag, 1>; SizeType = long unsigned int; bool ConstantTimeSize = true; HeaderHolder = void; boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::iterator = boost::intrusive::list_iterator<boost::intrusive::bhtraits<boost::heap::detail::heap_node_base<false>, boost::intrusive::list_node_traits<void*>, (boost::intrusive::link_mode_type)1, boost::intrusive::dft_tag, 1>, false>; boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::reference = boost::heap::detail::heap_node_base<false>&]: Assertion `!node_algorithms::inited(value_traits::to_node_ptr(value))' failed.
This is the part of the code that triggers the error:
void prune(Node_h* last_sol){
Node_h* elem;
int count = 0;
for(auto it=open.begin(),end=open.end(); it != end; ++it){
elem = *it;
if (handlers.find(elem) == handlers.end()){
printf("KEEEEY NOT FOUND");
} else {
printf("elem->f: %f >= last_sol->f: %f \n",elem->g.second+elem->h.second, last_sol->g.second+last_sol->h.second);
if(elem->g.second+elem->h.second >= last_sol->g.second+last_sol->h.second){
open.erase(handlers[elem]);
count++;
}
}
}
printf("New Open size: %ld ", open.size());
printf("Nodes prune: %d\n", count);
}
I'm saving the handlers in a hash map at the moment of pushing the nodes:
open_handle handler = open.push(succ);
handlers[succ] = handler;
Everything worked fine with the heap until this point (pop and push methods) so I'm puzzled on what could trigger this error, implementation looks accord to the documentation.
Other information:
struct compare_states {
bool operator()(const Node_h* s1, const Node_h* s2) const {
//return n1.id > n2.id;
return s1->f > s2->f ;
}
};
typedef fibonacci_heap<Node_h*,compare<compare_states> >::handle_type open_handle;
gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)
| This loop looks suspect:
for(auto it=open.begin(),end=open.end(); it != end; ++it){
open.erase(/*...*/);
}
Quoting the docs:
Unless otherwise noted, all non-const heap member functions invalidate iterators, while all const member functions preserve the iterator validity.
That means the erase invalidates the loop iterator(s).
From context I'm assuming that handler/handlers in your code actually refers to node handles. If so, you might want to collect handles to be erased in a temporary container before doing the deletion:
Live On Compiler Explorer
#include <boost/heap/fibonacci_heap.hpp>
#include <fmt/ranges.h>
#include <map>
int main() {
namespace bh = boost::heap;
using Heap = bh::fibonacci_heap<int>;
using Handle = Heap::handle_type;
Heap open;
std::map<int, Heap::handle_type> handles;
for (int j : {1, 2, 3, 4, 5})
handles.emplace(j, open.push({j}));
std::vector<Handle> to_erase;
for (int el : open) {
if (el % 2) {
//if (handles.contains(el)) {
to_erase.push_back(handles.at(el));
//}
}
}
fmt::print("Deleting {} odd elements from {}\n", to_erase.size(), open);
for (auto h : to_erase)
open.erase(h);
fmt::print("Remaining {}\n", open);
}
Prints
Deleting 3 odd elements from [5, 4, 3, 2, 1]
Remaining [4, 2]
For classic node-based containers, the following loop style would be applicable:
for (auto it = open.begin(), end = open.end(); it != end;) {
if (condition)
it = open.erase(it);
else
++it;
}
However, fibonacci_heap::erase returns void.
In fact this algorithm is standardized as the free function std::erase_if in c++20 for standard containers.
|
72,122,163 | 72,122,213 | After inserting at head in linked list. Now what is name of that node which was head before inserting new node | // insert at head LL
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
void insertAtHead(node* &head, int value){
node* n= new node(value);
n->next=head;
head=n;
}
void display(node* head){
while(head!=NULL){
cout<<head->data<<"->";
head=head->next;
}
cout<<"NULL"<<endl;
}
int main(){
node* head=new node(1);
node* second=new node(2);
node* third=new node(3);
head->next=second;
second->next=third;
insertAtHead(head, 0);
display(head);
cout<<head->data; // accessing data of new head.
// how to access data of node which was previously head?
return 0;
}
Now after inserting new node with data '0' it's our new head but node which was previously head node, how can we access it's data and what is name of that node because it's name is definitely not 'n'?
|
[H]ow to access data of node which was previously head?
The previous head node is now the currents head-nodes next node:
std::cout << "Previous head value: " << head->next->data << '\n';
|
72,122,455 | 72,135,263 | Linux Apache CGI can't open lib when visiting the website | I'm using unixODBC and Apache CGI to build a database website on Linux. The following problems occurred when I tested the query of the database.
Connect Error
[01000] [unixODBC][Driver Manager]Can't open lib '/usr/local/lib/psqlodbcw.so' : file not found (0)
The above information appears on another computer on which I tried to access the website using Windows.
http://serverIP/cgi-bin/website.cgi?first=1
Strangely, when I run this CGI file directly on the Linux server, it executes normally. That is, successfully connect to the database and query the output results. The successful connection of isql also proves that it can connect to the database.
Equivalent to the following
root@VM-4-11-ubuntu:~# /var/www/cgi-bin/website.cgi
Content-type:text/html
<html>
<head>
<title>test button</title>
</head>
<body>
<p>Connected!</p>
<p>SELECT * FROM people WHERE id = 1;<p>
<p>id = 1 name = Tom</p>
</body>
</html>
// -----
root@VM-4-11-ubuntu:~# curl http://localhost/cgi-bin/website.cgi
<html>
<head>
<title>test button</title>
</head>
<body>
<p>Connect Error</p>
<p>[01000] [unixODBC][Driver Manager]Can't open lib '/usr/local/lib/psqlodbcw.so' : file not found (0)</p>
</body>
</html>
The following is the code to output the error message
// In DataBase's constructor
// ...
V_OD_erg = SQLConnect(V_OD_hdbc, dataSource, SQL_NTS,
usrName, SQL_NTS, password, SQL_NTS);
if ((V_OD_erg != SQL_SUCCESS) && (V_OD_erg != SQL_SUCCESS_WITH_INFO)) {
noErr = false;
printf("<p>Connect Error</p>\n");
showDBCErr(V_OD_erg);
}
// ...
void DataBase::showDBCErr(SQLRETURN retCode) {
HandleDiagnosticRecord(V_OD_hdbc, SQL_HANDLE_DBC, retCode);
}
// ...
void DataBase::HandleDiagnosticRecord(SQLHANDLE hHandle, SQLSMALLINT hType,
RETCODE RetCode) {
SQLSMALLINT iRec = 0;
SQLINTEGER iError;
SQLCHAR wszMessage[1000];
SQLCHAR wszState[SQL_SQLSTATE_SIZE + 1];
if (RetCode == SQL_INVALID_HANDLE) {
printf("<p>Invalid handle!</p>");
return;
}
while (SQLGetDiagRec(hType, hHandle, ++iRec, wszState, &iError, wszMessage,
(SQLSMALLINT)(sizeof(wszMessage) / sizeof(SQLCHAR)),
(SQLSMALLINT*)NULL) == SQL_SUCCESS) {
// Hide data truncated..
if (strcmp((const char*)wszState, "01004")) {
printf("<p>[%5.5s] %s (%d)</p>", wszState, wszMessage, iError);
}
}
}
// in /usr/local/etc/odbcinst.ini
[ODBC]
Trace=Yes
TraceFile=~/unixODBCLog/odbctrace.log
[GaussMPP]
Driver64=/usr/local/lib/psqlodbcw.so
setup=/usr/local/lib/psqlodbcw.so
// in ~/.bashrc
# ...
export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
export ODBCSYSINI=/usr/local/etc
export ODBCINI=/usr/local/etc/odbc.ini
root@VM-4-11-ubuntu:~# odbcinst -j
unixODBC 2.3.7pre
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /usr/local/etc/odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
I have no idea how to solve this problem. I can provide more information if necessary.
| Okay, guys, I've solved this problem. Like Some programmer dude said, "Generally don't use the root user for any kind of development, that can give you the false impression that things works ". When I use tar as ubuntu (not root), system shows the same error "file not found". Then I realize that the ODBC library installed as root may not be available to ordinary users. So I reinstall as ubuntu. It works!
Thanks, @Some programmer dude, @Alan Birtles, @Stephen Ostermiller
|
72,122,495 | 72,122,546 | Overloading Type-Cast in c++ | I want to understand how typecast-overloading works. For my question, I want to know
The thing I'm trying to do is it possible?
If yes, then how?
I want the user to be able to pass a vector<float> to a function. This function is implemented in such a way that its parameter is a wrapper class around vector<float>.
Can typecast-overloading help in such a case? (automatically convert vector<float> into Layer)
or do we have to use some complicated templated function?
// ---------- someFile.cpp ------------
class Layer {
vector<float> l;
public:
friend void process (const Layer& someLayer);
}
// ---------- main.cpp ------------
int main() {
vector<float> vec = {1.0, 1.5, 2.0};
process(vec);
}
| All that's needed is a non-explicit constructor taking the correct argument (a so-called conversion constructor):
class Layer {
vector<float> l;
public:
Layer(vector<float> const& v);
};
Now the compiler will be able to do implicit conversions from vector<float> to Layer.
Note that it's usually not recommended to have such conversion constructors being non-explicit (not declared using the explicit keyword), because sometimes implicit conversions might be unexpected and not wanted.
|
72,122,733 | 72,123,328 | C++ function not getting called | I have a function that takes 2d-vector and outputs a 2d-vector. For some reason, the function is not getting called.
Here is the link to reproduce the issue: Google Colab.
In the link to check for correctness, I have added another code that uses the exact same function but doesn't take a 2d-vector array as an argument instead it runs on static input.
mycode.cpp:
#include <vector>
#include "geomutils.h"
#include "mycode.h"
#include <iostream>
using namespace std;
vector< vector<double> > customComputeConvexHull(vector< vector<double> > i_matrix){
cout <<"\nDone1.1";
Polygon custompts, customhull;
for (int r = 0; r < i_matrix.size(); r++){
custompts.push_back(Point(i_matrix[r][0], i_matrix[r][1]));
}
computeConvexHull(custompts, customhull);
// vector< vector<double> > res;
vector<vector<double>> res( customhull.size() , vector<double> (2));
for(int i = 0;i < customhull.size();i ++) {
res[i][0] = customhull[i].x;
res[i][1] = customhull[i].y;
}
return res;
}
void print_polygon(Polygon &h, int name){
std::cout << "\nHull in "<< name << ": \n"<<"[";
for(int i = 0;i < h.size();i ++) {
std::cout << "("<< h[i].x<< ", "<< h[i].y<<"), ";
}
std::cout <<"]\n";
}
void get_convex_hull_custom(){
Polygon custompts;
Polygon customhull;
custompts.push_back(Point(0,0));
custompts.push_back(Point(4.58,7.14));
custompts.push_back(Point(0,7.14));
computeConvexHull(custompts, customhull);
print_polygon(customhull, -99999);
}
int main()
{
// Create an empty vector
vector< vector<double> > mat,mat2;
vector<double> myRow1(0,0);
mat.push_back(myRow1);
vector<double> myRow2(7.61,9.48);
mat.push_back(myRow2);
vector<double> myRow3(0,9.48);
mat.push_back(myRow3);
cout <<"Done1\n";
get_convex_hull_custom();
mat2 = customComputeConvexHull(mat);
cout <<"Done2";
return 0;
}
mycode.h:
#ifndef _code
#define _code
#include <vector>
std::vector< std::vector<double> > customComputeConvexHull (std::vector< std::vector<double> > i_matrix);
#endif
geomutils.cpp:
#include "geomutils.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
void computeConvexHull(Polygon &pts, Polygon &chull) {
chull.clear();
if(pts.size() == 1) {
chull.push_back(pts[0]);
chull.push_back(pts[0]);
return;
} else if(pts.size() == 2) {
chull.push_back(pts[0]);
chull.push_back(pts[1]);
chull.push_back(pts[0]);
return;
}
typedef boost::tuple<double, double> point;
typedef boost::geometry::model::multi_point<point> mpoints;
typedef boost::geometry::model::polygon<point> polygon;
mpoints mpts;
for(int i = 0;i < pts.size();i ++) {
boost::geometry::append(mpts,point(pts[i].x,pts[i].y));
}
polygon hull;
// Polygon is closed
boost::geometry::convex_hull(mpts, hull);
for(auto pt : hull.outer()) {
chull.push_back(Point(pt.get<0>(), pt.get<1>()));
}
}
geomutils.h:
#ifndef GEOMUTILS_H
#define GEOMUTILS_H
#include <vector>
struct Point {
double x,y;
Point(){}
Point(double x, double y):x(x),y(y){}
};
typedef std::vector<Point> Polygon;
void computeConvexHull(Polygon &pts, Polygon &chull);
#endif // GEOMUTILS_H
When I compile the code and try to run it.
Only Done1 gets printed on the console. It neither gives any error nor any message.
Output:
Done1
Hull in -99999:
[(0, 0), (0, 7.14), (4.58, 7.14), (0, 0), ]
| There's some issue on your code. First of all in main to correctly initialize the vector you have to use the {} syntax. Further in customComputeConvexHull you are setting values inside the res vector which are not yet present. You have to use push_back to populate res. Below a version of your code which works (I put everything into one cpp file for semplicity.
#include <vector>
//#include "geomutils.h"
//#include "mycode.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
using namespace std;
struct Point {
double x, y;
Point() {}
Point(double x, double y) :x(x), y(y) {}
};
typedef std::vector<Point> Polygon;
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian);
void computeConvexHull(Polygon& pts, Polygon& chull) {
chull.clear();
if (pts.size() == 1) {
chull.push_back(pts[0]);
chull.push_back(pts[0]);
return;
}
else if (pts.size() == 2) {
chull.push_back(pts[0]);
chull.push_back(pts[1]);
chull.push_back(pts[0]);
return;
}
typedef boost::tuple<double, double> point;
typedef boost::geometry::model::multi_point<point> mpoints;
typedef boost::geometry::model::polygon<point> polygon;
mpoints mpts;
for (int i = 0; i < pts.size(); i++) {
boost::geometry::append(mpts, point(pts[i].x, pts[i].y));
}
polygon hull;
// Polygon is closed
boost::geometry::convex_hull(mpts, hull);
for (auto pt : hull.outer()) {
chull.push_back(Point(pt.get<0>(), pt.get<1>()));
}
}
vector< vector<double> > customComputeConvexHull(vector< vector<double> > i_matrix) {
cout << "\nDone1.1";
Polygon custompts, customhull;
for (int r = 0; r < i_matrix.size(); r++) {
custompts.push_back(Point(i_matrix[r][0], i_matrix[r][1]));
}
computeConvexHull(custompts, customhull);
vector< vector<double> > res;
for (int i = 0; i < 3; i++)
{
vector<double> v1{ customhull[i].x, customhull[i].y };
res.push_back(v1);
}
return res;
}
int main()
{
// Create an empty vector
vector< vector<double> > mat, mat2;
vector<double> myRow1{0, 0};
mat.push_back(myRow1);
vector<double> myRow2{ 7.61, 9.48 };
mat.push_back(myRow2);
vector<double> myRow3{ 0, 9.48 };
mat.push_back(myRow3);
cout << "Done1";
mat2 = customComputeConvexHull(mat);
cout << "Done2";
return 0;
}
|
72,123,107 | 72,127,138 | What were the reasons to terminate boost graph searches via exceptions? | Early exit of algorithms in boost graph such as breadth first search should be done by throwing an exception according to the FAQ:
How do I perform an early exit from an algorithm such as BFS?
Create a visitor that throws an exception when you want to cut off the search, then put your call to breadth_first_search inside of an appropriate try/catch block. This strikes many programmers as a misuse of exceptions, however, much thought was put into the decision to have exceptions has the preferred way to exit early. See boost email discussions for more details.
I am interested in the actual "thoughts that were put into the decision". So far I failed to find the appropriate posts on the mailing list. The closest I found was this one, stating
If the graph is big, exiting the algorithm by throwing an exception might be
the most efficient way ;-). Of course, if you do many invocations on small
graphs, it may be the least efficient ;-(.
and this one:
If you have enough callbacks, you can surely do all the same things. I'm not
sure what loss of control you fear, but from an efficiency point-of-view it
might make sense to exit the algorithm by throwing an exception (no, I'm
really NOT kidding).
Which, to me, are no real well-founded justifications for the design decision. Also because we do see huge slow downs when a lot of exceptions are thrown, especially while running the code in a debugger.
I am also aware of similar posts on stackoverflow (such as this one or this one) asking on how to terminate the searches. But I know how (by throwing an exception). Yet, none of them provide the reasoning behind the decision.
So my question is: Does anyone know the actual thoughts that went into the decision? And does anyone have an actual link to the boost mailing list post that contains these thoughts that are alluded to in the FAQ?
| It simplifies the implementation. It allows all searches to leverage a generic traversal algorithm.
The argument becomes amplified in the face of generics.
Note that the visitors can be implemented in several ways:
users can implement the visitor interface
derive from one and override some handlers
or
compose one from different Event Visitors
Especially that case creates questions with generic composition if handlers were to return a control value. What if several handlers handle the same event, how would the return values be combined?
This situation is similar to other event-driven designs, like browser script UI events (which can bubble up or not) or Boost Signals2 signal slots, which can have user-supplied combiners instead of the default optional_last_value
The key element is multiplicity of event handlers/"slots".
You might argue that this can be summarized as "the library doesn't afford early search termination", but as the documentation reflects the designers specifically opted to allow the exceptions language feature to be used here. In addition to all the places you already mentioned, let me quote from the implementation of the BGL function is_bipartite which uses a DFS that is potentially prematurely aborted when the graph is not bipartite:
try
{
depth_first_search(graph,
vertex_index_map(index_map).visitor(make_dfs_visitor(
std::make_pair(detail::colorize_bipartition(partition_map),
std::make_pair(detail::check_bipartition(partition_map),
put_property(partition_map,
color_traits< partition_color_t >::white(),
on_start_vertex()))))));
}
catch (const detail::bipartite_visitor_error< vertex_descriptor_t >&)
{
return false;
}
return true;
|
72,123,155 | 72,123,990 | Using a enum class from a c++ header in a c header | I am writing a c wrapper around a c++ library.
In the c++ there are enum classes used as types for function arguments.
How do I use theme correctly in the c header.
One ugly way would be to use int's in the c function and cast theme in the wrapper function to the enum type. But this gives the user of the c function no clue about the valid values, and it is really hard to check if the value is valid.
cpp header
namespace GPIO
{
enum class Directions
{
UNKNOWN,
OUT,
IN,
HARD_PWM
};
void setup(int channel, Directions direction, int initial = -1);
}
c wrapper header
int setup(int channel, int direction, int initial);
c wrapper code
int setup(int channel, int direction, int initial)
{
GPIO::setup(channel, static_cast<GPIO::Directions>(direction), initial);
return 0;
}
What would be a good way to give the user of the c functions the benefits of the enum classes in the c++ library. Because it is not my library, I would like to not change too much of the code in the library.
There would be the option to extract the enum classes to a different file and include it in the original header. But I don't know how to define it correctly, so I don't have to change the naming in the cpp library and still can use it in the c header.
| You can not do it. It is impossible to use C++ features from C code. You are creating C wrapper for C++ function, why can not you create also C wrapper for enum? The only question is how to be sure that both enums have the same values. You can check it compile time after the small code change:
cpp header:
namespace GPIO
{
enum class Directions
{
UNKNOWN,
OUT,
IN,
HARD_PWM,
SIZE
};
}
c wrapper header:
enum GPIO_Directions
{
GPIO_Directions_UNKNOWN,
GPIO_Directions_OUT,
GPIO_Directions_IN,
GPIO_Directions_HARD_PWM,
GPIO_Directions_SIZE
};
c wrapper code:
int setup(int channel, GPIO_Direction direction, int initial)
{
static_assert(GPIO::Directions::SIZE == GPIO_Directions_SIZE,
"c wrapper enum must be equal to c++ enum");
GPIO::setup(channel, static_cast<GPIO::Directions>(direction), initial);
return 0;
}
|
72,123,200 | 72,123,568 | Unknown command : QT5_ADD_TRANSLATION in Qt cmake project | I'm developing Qt application and now I want to do some I18N stuff. First problem I meet is that cmake doesn't know about command QT5_ADD_TRANSLATION(we are using cmake for building our project). I refer to QtLinguist Manual. When I met that problem, I also read threads like Unknown CMake command "QT5_CREATE_TRANSLATION" and qt4 to qt5 migration, but unluckily, I still stuck here.
My cmake version is 3.16 for Qt 5.15.2. If you need more informations, please let me know.
Besides, If there is an alternative way to accomplish I18N work in Qt with cmake, that is also fine. For example, I come up with add_custom_command with lupdate from qt, but don't success yet.
add_custom_command(OUTPUT ${TRANSLATIONS}
DEPENDS ${SOURCES}
COMMAND lupdate)
command won't execute. I'm still try it.
| It should be something like this:
find_package(Qt5 COMPONENTS LinguistTools)
qt5_add_translation(OUTPUT_VAR your_translation.ts)
CMake functions/macros provided by Qt itself belong to some particular module so you need to find that module before using its functioncs.
|
72,123,757 | 72,124,019 | Why is my matrix multiplication code not working? | I am new to C++ and I have written a C++ OpenMp Matrix Multiplication code that multiplies two 1000x1000 matrices. So far its not running and I am having a hard time finding out where the bugs are. I tried to figure it out for a few days but I'm stuck.
Here is my code:
#include <iostream>
#include <time.h>
#include <omp.h>
using namespace std;
int N;
void Multiply()
{
//initialize matrices with random numbers
//#pragma omp for
int aMatrix[N][N], i, j;
for( i = 0; i < N; ++i)
{for( j = 0; j < N; ++j)
{aMatrix[i][j] = rand();}
}
int bMatrix[N][N], i1, j2;
for( i1 = 0; i1 < N; ++i1)
{for( j2 = 0; j2 < N; ++j2)
{bMatrix[i1][j2] = rand();}
}
//Result Matrix
int product[N][N] = {0};
//Transpose Matrix;
int BTransposed[j][i];
BTransposed[j][i] = bMatrix[i1][j2];
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
// Multiply the row of A by the column of B to get the row, column of product.
for (int inner = 0; inner < N; inner++) {
product[row][col] += aMatrix[row][inner] * BTransposed[col][inner];
}
}
}
}
int main() {
time_t begin, end;
time(&begin);
Multiply();
time(&end);
time_t elapsed = end - begin;
cout << ("Time measured: ") << endl;
cout << elapsed << endl;
return 0;
}```
| The transposed matrix (BTransposed) is not correctly constructed. You can solve this in the following ways:
First Option: use a for loop to create the correct BTransposed matrix.
for (int i = 0; i != N; i++)
for (int j = 0; j != N; j++)
BTransposed[i][j] = bMatrix[j][i]
Second Option (better one): completely delete BTransposed matrix. when needed just use the original bMatrix with indexes i,j exchanged! for example instead of BTransposed[col][inner] you can use BMatrix[inner][col].
|
72,123,871 | 72,124,119 | How to store every sequentially increasing sequence in a vector into new vectors | I have a vector with the following elements:
std::vector<int> vectorOfInts{ 95, 137, 138, 139, 140, 156, 157, 158, 159 };
Problem: I'm trying to store each sequence in a new vector, where each sequence is defined as a list of sequentially increasing values (that are increasing by 1).
Some properties of vectorOfInts:
The number of sequences are known, but the length of each sequence are unknown as well as the first and last element in each sequence.
All the elements are always sorted, from lowest to highest.
A sequence is defined by a list of numbers, where the next number is 1 greater than the previous number.
The shortest length of a sequence is 1.
For this example, there are 3 sequences: [95], [137, 138, 139, 140] and [156, 157, 158, 159]. 95 is the first and last element of sequence 1, 137 is the first element of sequence 2 and 140 is the last element of sequence 2, and 156 is the first element of sequence 3 and 159 is the last element of sequence 3.
I have to store the sequences in a new and different vector for each sequence, i.e., std::vector<int> vec1 = {95}, std::vector<int> vec2 = {137, 138, 139, 140}, and std::vector<int> vec3 = {156, 157, 158, 159}.
I think I have to loop through the vectorOfInts and check if the number at the next index is 1 greater than the number on the current index. I have also thought about partitioning the vectorOfInts according to some criteria.
Some pseudocode:
#include <vector>
int main()
{
std::vector<int> vectorOfInts{ 95, 137, 138, 139, 140, 156, 157, 158, 159 };
std::vector<int> vec1;
std::vector<int> vec2;
std::vector<int> vec3;
for (size_t i = 0; i < vectorOfInts.size(); i++)
{
vec1.push_back(vectorOfInts[i])
if (vectorOfInts[i + 1] is one greater than vectorOfInts[i])
{
vec1.push_back(vectorOfInts[i]);
}
else
{
vec2.push_back(vectorOfInts[i]);
}
}
return 0;
}
| You can use this algorithm: Create a vector of vectors that contains one vector containing the first element of the input vector. These are the output vectors. For each element of the input vector after the first, if the element is not previous element +1, then push a new vector to the output. Insert the current element to the last output vector.
|
72,123,893 | 72,124,047 | How to read in C++ a short int (2 byte) LSB first value? | How can I read two separate bytes each with LSB first?
2 speparate LSB first bytes -> one short int MSB first
e.g. 01001100
11001100
-> 00110010 00110011
short int lsbToMsb(char byte1, char byte2) {
...
return msb;
}
| Try this:
char reverseBits(char byte)
{
char reverse_byte = 0;
for (int i = 0; i < 8; i++) {
if ((byte & (1 << i)))
reverse_byte |= 1 << (7 - i);
}
return reverse_byte;
}
short int lsbToMsb(char byte1, char byte2) {
byte1 = reverseBits(byte1);
byte2 = reverseBits(byte2);
short int msb = (byte1 << 8) | byte2;
return msb;
}
int main(){
char byte1 = 76; // 01001100
char byte2 = -52; // 11001100
short int msb = lsbToMsb(byte1, byte2);
printf("%d", msb);
}
Output:
12851 // 00110010 00110011
|
72,124,111 | 72,124,279 | Why the `this` pointer worked in constructor in C++? | I know the this pointer will point to the object instance that currently in, but I don't know how to implement it.
And I found that in standard 7.5.2 said:
The keyword this names a pointer to the object for which an implicit object member function ([class.mfct.non.static]) is invoked or a non-static data member's initializer ([class.mem]) is evaluated.
but in 12.2.2 said constructors do not have implicit object parameter, then why I can use this pointer in constructor?
then I have several question comming, so my question is:
Does the this pointer belongs to the class?
I think the answer is NO, but I wanna confirm it.
Does all class instance shared the constructors and destructor?
I knew that the class instance will share the member function, does it same on constructors and destructor?
How the this pointer was implemented?
Is there something like virtual table to maintain the this pointer?
Why I can use the this pointer in constructor?
The this point to the implicit object, but constructor didn't have the implicit object parameter, then how could the this pointer worked well?
Any additional supplements and recommendations are appreciated.
Edit:
This stackoverflow helps me a lot : Does a constructor also have an implicit this parameter
|
but I don't know how to implement it.
this pointer is a feature of the C++ language. If you aren't implementing C++, then you don't need to "implement" this pointer. If you want to know how to implement C++, there are open source C++ compilers available.
why I can use this pointer in constructor?
Constructor is a non-static member function. You can use this in non-static member functions.
but in 12.2.2 said constructors do not have implicit object parameter
Quoted rule is prefaced: For the purposes of overload resolution.... It doesn't apply to anything other than overload resolution.
Does the this pointer belongs to the class?
There is no concept of "belongs" in the language.
Does all class instance shared the constructors and destructor?
There is no concept of sharing functions in the language.
How the this pointer was implemented?
The language doesn't describe how to implement itself. It describes how the program written in the language shall or may behave.
Why I can use the this pointer in constructor?
See above.
|
72,124,149 | 72,124,443 | Why doesn't mutex work without lock guard? | I have the following code:
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
int shared_var {0};
std::mutex shared_mutex;
void task_1()
{
while (true)
{
shared_mutex.lock();
const auto temp = shared_var;
std::this_thread::sleep_for(std::chrono::seconds(1));
if(temp == shared_var)
{
//do something
}
else
{
const auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << ": Data race at task_1: shared resource corrupt \n";
std::cout << "Actual value: " << shared_var << "Expected value: " << temp << "\n";
}
shared_mutex.unlock();
}
}
void task_2()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
++shared_var;
}
}
int main()
{
auto task_1_thread = std::thread(task_1);
auto task_2_thread = std::thread(task_2);
task_1_thread.join();
task_2_thread.join();
return 0;
}
shared_var is protected in task_1 but not protected in task_2
What is expected:
I was expecting else branch is not entered in task_1 as the shared resource is locked.
What actually happens:
Running this code will enter else branch in task_1.
Expected outcome is obtained when replace shared_mutex.lock(); with std::lock_guard<std::mutex> lock(shared_mutex); and shared_mutex.unlock(); with std::lock_guard<std::mutex> unlock(shared_mutex);
Questions:
What is the problem in my current approach?
Why does it work with loack_guard?
I am running the code on:
https://www.onlinegdb.com/online_c++_compiler
| Suppose you have a room with two entries. One entry has a door the other not. The room is called shared_var. There are two guys that want to enter the room, they are called task_1 and task_2.
You now want to make sure somehow that only one of them is inside the room at any time.
taks_2 can enter the room freely through the entry without a door. task_1 uses the door called shared_mutex.
Your question is now: Can achieve that only one guy is in the room by adding a lock to the door at the first entry?
Obviously no, because the second door can still be entered and left without you having any control over it.
If you experiment you might observe that without the lock it happens that you find both guys in the room while after adding the lock you don't find both guys in the room. Though this is pure luck (bad luck actually, because it makes you beleive that the lock helped). In fact the lock did not change much. The guy called task_2 can still enter the room while the other guy is inside.
The solution would be to make both go through the same door. They lock the door when going inside and unlock it when leaving the room. Putting an automatic lock on the door can be nice, because then the guys cannot forget to unlock the door when they leave.
Oh sorry, i got lost in telling a story.
TL;DR: In your code it does not matter if you use the lock or not. Actually also the mutex in your code is useless, because only one thread un/locks it. To use the mutex properly, both threads need to lock it before reading/writing shared memory.
|
72,124,490 | 72,124,562 | Why is the member value of parent lost in the vector after push_back()? (C++) | I would like to push an instance of Child (Parent is the base class of Child), in a vector using push_back(). But then the value of the Parent members lost.
In the following example, I would like to see 70 when writing the vector to the console, but I get random value instead. What is causing this?
main.cpp:
void demo(vector<Child> &ch) {
Child c(4);
c.setPrice(70);
cout << c.getPrice() << endl; // 70
ch.push_back(c);
cout << ch[ch.size()-1].getPrice() << endl; // random value
}
int main()
{
vector<Child> ch;
demo(ch);
return 0;
}
Child.h:
#ifndef CHILD_H_INCLUDED
#define CHILD_H_INCLUDED
#include "Parent.h"
class Child : public Parent
{
private:
int siz;
public:
Child();
~Child();
Child(int);
Child(const Child&);
int getSiz() const;
void setSiz(int);
};
#endif // CHILD_H_INCLUDED
Child.cpp:
#include "Child.h"
Child::Child()
{
}
Child::Child(int siz)
{
this->siz = siz;
}
Child::Child(const Child& other)
{
siz = other.siz;
}
Child::~Child () {
}
int Child::getSiz() const
{
return siz;
}
void Child::setSiz(int s)
{
siz = s;
}
Parent.h:
#ifndef PARENT_H_INCLUDED
#define PARENT_H_INCLUDED
class Parent
{
private:
int price;
public:
Parent();
~Parent();
Parent(int);
Parent(const Parent&);
int getPrice() const;
void setPrice(int);
};
#endif // PARENT_H_INCLUDED
Parent.cpp:
#include "Parent.h"
Parent::Parent()
{
}
Parent::Parent(int price)
{
this->price = price;
}
Parent::Parent(const Parent& other)
{
price = other.price;
}
Parent::~Parent () {
}
int Parent::getPrice() const
{
return price;
}
void Parent::setPrice(int p)
{
price = p;
}
Thank you very much in advance for your help!
| The child's copy constructor only copies the child parts. It should also invoke the parent's copy constructor to let it copy the parent members.
Child::Child(const Child& other) : Parent(other)
{
siz = other.siz;
}
|
72,124,951 | 72,125,039 | different behaviour of unhashable typeError between cpp and python | It is ok to insert a vector to a set in cpp, which not works in python however. Codes shown below:
// OK in cpp
set<vector<int>> cpp_set;
cpp_set.insert(vector<int>{1,2,3});
// not OK in python
py_set = set()
py_set.add([1,2,3]) # TypeError: unhashable type: 'list'
py_set.add({1,2,3}) # TypeError: unhashable type: 'set'
Even adding a set to a set is not allowed, and I don't understand why a set is unhashable.
Why does the difference happens? And is it a permitted good way to use in cpp? I mean adding a vector to a set.
| Python's set is a hash table, and has no hashing functions for set and list.
std::set is not a hash table but a sequence ordered by an ordering relation (std::less by default).
You can use std::set with any type where you can define a strict weak ordering.
Try std::unordered_set in C++ and you will encounter problems.
|
72,125,208 | 72,125,265 | cin didnt work in range based loop in vector | I tried to input values to my vector,but it filled with zero value.
I try to input value by following range based loop and output them.
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0; i<(n); i++)
int main() {
int N;
cin>>N;
vector<int>A(N);
for(auto x:A) cin>>x;
for(auto y:A) cout<<y<<' ';
cout<<endl;
return 0;
}
output is following , N=2 vector=1 2 but output is 0 0
root@DESKTOP-TM0ASL2:~/work# ./a.out
2
1 2
0 0
What is the root cause of this ?
I worked for a while, but I haven't understood yet, if someone has opinion, will you please let me know. thanks
| The problem does not relate to std::cin at all. The problem is the way you used auto in the range based loop.
In order to update the std::vector, you should change:
for(auto x:A) cin>>x;
to:
for(auto & x:A) cin>>x; // NOTE: added '&'
Because the meaning of auto does not include "reference-ness" (even if the expression assigned to the auto is in fact a reference). See more info here: C++ auto& vs auto. This is the more "formal" description (a bit harder to understand): cppreference.com - auto. The bottom line is that auto will be deduced by the compiler to be int in your case (not int&).
Therefore in your code, x in the loop is getting a copy of the element from A, which is filled by cin (i.e. the vector is not modified).
Same applies to constness. Therefore when you print the std::vector, it's better to do something like:
for(auto const & y:A) cout<<y<<' '; // NOTE: added 'const &'
This will cause the compiler to ensure that A's elements are not modified in the loop (due to const) and be efficient (using reference [&] will avoid coping the elements).
Some other notes:
Better to avoid #include <bits/stdc++.h> - see here: Why should I not #include <bits/stdc++.h>?.
Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
|
72,125,663 | 72,131,960 | Avoid compiling definition of inline function multiple times | I have a non-template struct in a header file:
struct X {
constexpr X() : /* ... */ { /* ... */ }
constexpr void f() {
// ...
}
};
With functions of varying size. This is used in a lot of different translation units, and each function appears in multiple object files for them to be discarded in the final executable.
What I want is for the definitions to be in a single object file, and the other translation units can either inline the function or use an external definition (something like the extern inline semantics from C). How can I do that?
It seems to work with templates and extern template:
namespace detail {
template<std::nullptr_t>
struct X_base {
constexpr X_base() // ...
constexpr void f() // ...
};
extern template struct X_base<nullptr>;
}
struct X : detail::X_base<nullptr> {
using X_base::X_base;
};
// X.cpp
#include <X.hpp>
template struct detail::X_base<nullptr>;
But are there any major downsides to this (longer symbol names, confusing to read, needs documentation, etc.), or are there any easier ways to do this?
| C++ doesn’t have the notion of an inline function that must be emitted in one translation unit and which therefore certainly need not be emitted anywhere else. (It doesn’t have the notion of emitting object code at all, but the point is that there’s no syntax that says “I promise this definition is ODR-identical to the others except that it and only it bears this marker.” so that compilers could do that.)
However, the behavior you want is the obvious way of implementing C++20 modules: because the definition of an inline function in a module is known to be the only definition, it can and should be emitted once in case several importing translation units need an out-of-line copy of it. (Inlining is still possible because the definition is made available in a compiler-internal form as part of building the module.) Bear in mind that member functions defined in a class in a module are not automatically inline, although constexpr still implies it.
Another ugly workaround is to make non-inline wrappers to be used outside of constant evaluation, although this could get unwieldy if there were multiple levels of constexpr functions that might also be used at runtime.
|
72,126,220 | 72,126,536 | Allocator named requirements -- exceptions | [allocator.requirements.general]/37
Throws: allocate may throw an appropriate exception.
Any limitations on "appropriate" implied elsewhere?
Can a valid custom allocator just throw a double on any request?
Context: implementation of a noexcept function that uses allocator, but has fallback strategy to do something if all allocations fail.
|
Any limitations on "appropriate" implied elsewhere?
No. "Appropriate" qualifier has no objective meaning. It's effectively a suggestion to use common sense. There are no limitations on the type thrown from allocate.
Can a valid custom allocator just throw a double on any request?
It would be conforming if the author considers double to be appropriate. I wouldn't consider it "appropriate" myself, but it's up to the author to decide.
Context: implementation of a noexcept function that uses allocator, but has fallback strategy to do something if all allocations fail.
You should use a catch-all block:
try {
ptr = a.allocate();
} catch(...) {
// deal with it
}
|
72,126,824 | 72,391,931 | How to load multiple images in SDL_image and SDL2? | I've been trying to load 2 images in a SDL window, like a player and an enemy, but SDL2_image loads only one image at a time
here's my code :
#include<iostream>
#define SDL_MAIN_HANDLED
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
using namespace std;
SDL_Texture* load(SDL_Renderer* ren, const char* path, SDL_Rect rect)
{
SDL_Texture* img = IMG_LoadTexture(ren, path);
if (img == NULL)
cout << SDL_GetError() << endl;
SDL_RenderClear(ren);
SDL_RenderCopy(ren, img, NULL, &rect);
SDL_RenderPresent(ren);
return img;
}
int main()
{
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Window* window = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 460, 380, SDL_WINDOW_RESIZABLE);
SDL_Surface* icon = IMG_Load("sdl.png");
SDL_SetWindowIcon(window, icon);
SDL_Renderer* ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect rect,r2;
rect.x = 0; r2.x = 65;
rect.y = 0; r2.y = 80;
rect.w = 64; r2.w = 64;
rect.h = 64; r2.h = 64;
SDL_Texture* img = load(ren, "player.png", rect);
SDL_Delay(2000);
SDL_Texture* tex = load(ren, "enemy.png", r2);
SDL_Event events; bool running = true;
while (running == true)
{
if (SDL_PollEvent(&events))
{
if (events.type == SDL_QUIT)
{
running = false;
break;
}
}
}
IMG_Quit();
SDL_Quit();
return 0;
}
I used SDL_Delay to demonstrate what happens
it loads "player.png" first and then after 2 seconds, it loads "enemy.png"
I wanted to load both at the same time but I couldn't
Please help!
| solved, it was due to SDL_RenderClear
|
72,127,008 | 72,127,295 | Why this function is not able to reverse the Linked List? | I want to reverse a linked list but when i compile this code it terminates unexpectedly.
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
For Inserting Elements in Linked List
void insertattail(node* &head,int lol){
node* n= new node(lol);
if(head==NULL){
head=n;
return;
}
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
}
Display Function to print linked list
void display(node* head){
node* temp =head;
do{
cout<<temp->data<<"->";
temp=temp->next;
}
while(temp!=NULL);
cout<<"Null";
}
Function to reverse Linked List
node* reverseit(node* head){
node* prevptr= NULL;
node* currptr= head;
node* nextptr= currptr->next;
while(currptr!=NULL){
currptr->next =prevptr;
prevptr=currptr;
currptr=nextptr;
nextptr=currptr->next;
}
return prevptr;
}
Main Function
int main()
{
node* head= NULL;
insertattail(head,1);
insertattail(head,2);
insertattail(head,3);
insertattail(head,8);
node* newhead= reverseit(head);
display(newhead);
return 0;
}
I think the problem is in logic of reverse function.
I just used the code for linked list and made small changes.
| Your initialization and 'incrementing' of nextptr both (potentially/eventually) dereference a NULL value of currptr. You should initialize nextptr to NULL and only change that to the 'real' next if currptr is not NULL; thus, its (re)assignment should be at the start of the loop, not at the end:
node* reverseit(node* head){
node* prevptr = nullptr;
node* currptr = head;
node* nextptr = nullptr; // Don't assume a non-NULL currptr
while (currptr != nullptr) {
nextptr = currptr->next; // Safe here: save next
currptr->next = prevptr; // Do the reversal here
prevptr = currptr; // Step forward through
currptr = nextptr; // the list (prev/curr)
// nextptr = currptr->next; // WRONG HERE: currptr will be NULL at some point
}
return prevptr;
}
|
72,127,603 | 72,127,661 | Can we take the address of xvalue | As I know, there have been come concepts since C++11: lvalue, rvalue, prvalue, xvalue etc.
As my understanding, if a function returns a local variable, it should be a rvalue.
std::string func() { return std::string("abc"); }
auto ret = func(); // func returns a rvalue
And for xvalue, std::move(x) is a kind of xvalue.
I think I'm right.
Today, my colleague told me that we can't get the address of rvalue, so &func() is illegal, but we can get the address of xvalue. This is a way to distinguish rvalue and xvalue...
Well, I just tried: int a = 1; std::cout << &std::move(a);. But the compiler said:
error: taking address of xvalue (rvalue reference)
So is my colleague wrong?
UPDATE
In fact, my colleague misunderstood the meaning of "has identity" and the unary & operator and I'm confused by him...
Here is a very nice question about this issue: What does it mean "xvalue has identity"?
| Your colleague is incorrect. C++ has always required an lvalue for use with the address of operator. This is called out explicitly in [expr.unary.op]/3:
The operand of the unary & operator shall be an lvalue of some type T. The result is a prvalue.
If the standard had used glvalue instead of lvalue then they would have been correct but per [fig:basic.lval] lvalue and xvalue are distinct leaves of glvalue so xvalues are not allowed.
|
72,127,835 | 72,127,957 | Should assignment initialization work with a type with non-explicit single param ctor but with deleted move ctor? | Should the following compile under c++11 rules? Why should it or why not? Is there UB? It seems that gcc forbade it before but changed their mind in version 11. Microsoft accepts it and clang consistently does not.
I was under the expression that IntWrapper myInt = 42; in this case is just syntactic sugar and is exactly the same as IntWrapper myInt(42); and that overloading of the assignment operator has no effect on initialization. To me it looks like old versions gcc and all versions of clang want to do ctor(int) and then a move. While msvc and new version gcc just call ctor(int) which I think is correct. Why to do a move when it's not needed.
If some c++ language lawyer could translate this into english see 11.10.1 Explicit initialization page 294-295 here https://isocpp.org/files/papers/N4860.pdf
Alternatively,
a single assignment-expression can be specified as an initializer using the = form of initialization. Either
direct-initialization semantics or copy-initialization semantics apply;
Note: Overloading of the assignment operator (12.6.2.1) has no effect on initialization. —
How I understood the standard is that the compiler can choose either to do a copy then a move or directly initialize using the ctor taking one argument. Which would be weird because how would you then know does it compile or not.
#include <iostream>
struct IntWrapper
{
IntWrapper(int value) : m_value(value)
{
std::cout << "ctor(int)\n";
}
IntWrapper(IntWrapper&& that) = delete;
int m_value;
};
int main()
{
IntWrapper myInt = 42;
return 0;
}
compiler
result
msvc v.19.x
compiles
gcc 11.x
compiles
gcc 10.x
error: use of deleted function 'IntWrapper::IntWrapper(IntWrapper&&)
clang 14.0.0
error: copying variable of type 'IntWrapper' invokes deleted constructor
clang 13.0.0
error: copying variable of type 'IntWrapper' invokes deleted constructor
clang 12.0.0
error: copying variable of type 'IntWrapper' invokes deleted constructor
| msvc v.19.x and gcc 11.x both default to using C++17 as the language standard to compile against while all of the other compilers you used default to C++14. This is why you see a difference.
Before C++17 IntWrapper myInt = 42; is semantically treated as IntWrapper myInt = IntWrapper(42); so you need a non-deleted copy or move constrcutor in order to compile that, even if the temporary object is elided away via compiler optimization.
Since C++17 IntWrapper myInt = 42; is now treated as having done IntWrapper myInt{42}; and now we are directly constrcuting, no temporary object is created. This feature is called guaranteed copy elision
When the standard says
Either direct-initialization semantics or copy-initialization semantics apply;
They mean that IntWrapper myInt = 42; can be treated as IntWrapper myInt = IntWrapper(42); or IntWrapper myInt{42};. It depends on if you have optimizations turned on or not on which form you get. The additional part of the standard that makes this fail before C++17 can be found in [class.temporary]/1
Even when the creation of the temporary object is unevaluated (Clause [expr]) or otherwise avoided ([class.copy]), all the semantic restrictions shall be respected as if the temporary object had been created and later destroyed. [ Note: This includes accessibility ([class.access]) and whether it is deleted, for the constructor selected and for the destructor. However, in the special case of a function call used as the operand of a decltype-specifier ([expr.call]), no temporary is introduced, so the foregoing does not apply to the prvalue of any such function call. — end note ]
|
72,127,920 | 72,128,180 | Naive reverse string iteration infinite loop and/or assertion failure C++ / Visual Studio 2022 | I am trying to reverse iterate through a string, but am getting assertion failure for the [] operator in the latest VS.
int foo() {
std::string s = "s";
for (int i = (s.size() - 1); i >= 0; i--) {
std::cout << s[i] << std::endl;
}
return 0;
}
Commenting out the cout line gives infinite loop warning and indeed enters infinite loop:
int foo2() {
std::string s = "s";
for (int i = (s.size() - 1); i >= 0; i--) {
//std::cout << s[i] << std::endl;
}
return 0;
}
Iterating forwards works just fine with or without anything in the for loop:
int bar() {
std::string s = "s";
for (int i = 0; i < s.size(); i++) {
std::cout << s[i] << std::endl;
}
return 0;
}
I am using the C++14 standard and the same code used to work on other compilers/older versions of VS. The same problem exists for any string size (although that should be irrelevant). I understand I could modify the code to use and dereference pointer instead of using int, but want to understand why this doesn't work anymore, why is it unsafe or incorrect, or what else am I missing. Thanks!
| Could it be that your int defaults to being unsigned and therefore decrementing when i=0 resuts in a high value ?
As @PeteBecker mentioned, int should be signed and should not overflow. However my guess is that your actual code does not use int.
|
72,128,134 | 72,129,309 | Generic vector of vector n dimensionnal | I try something (probably in the wrong way) but the langage and std doesn't let me do what I want.
I have a void* that can contain : std::vector<int> or std::vector<std::vector<int>> or std::vector<std::vector<std::vector<int>>> or ... and so on. I have a dpeth variable to know how much vector level.
So I "just" want to write a method that iterate through my vector and for each element give to me a new void* to a subVector or int.
But I can't get generically a sub element from my vector if don't give the real type (which can be very very very long)
I'm trying to macro some typedef :
using DIM1 = std::vector<int>;
using DIM2 = std::vector<std::vector<int>>;
But I can't convert my void* to a DIMX* (without an insane switch case statement)
Any ideas, (or other ways to approach the problem)
| First of all, prefer a std::any (rather than void*) to allow a variable to take on values of any type.
Here is a way to describe your strongly-typed N-dimensional jagged vector.
#include <vector>
#include <any>
template<int n, typename T>
class DIM : public std::vector<typename DIM<n - 1, T>::type> {
public:
typedef std::vector<typename DIM<n - 1, T>::type> type;
};
template<typename T>
class DIM<1, T> : public std::vector<T> {
public:
typedef std::vector<T> type;
};
int main()
{
// Let's populate a minimal 4-D example object.
DIM<4, int> foo;
foo.push_back(DIM<3,int>());
foo[0].push_back(DIM<2,int>());
foo[0][0].push_back(DIM<1, int>());
foo[0][0][0].push_back(1);
// example of stashing it in a std::any
std::any idk = foo;
// example of extracting the contents of idk
DIM<4, int> bar;
bar = std::any_cast<DIM<4, int>>(idk);
}
(Above example requires C++17.)
But you still are required to know the dimension at compile time. This doesn't get you a run-time-variable number of dimensions (variable depth).
If you require variable depth at run-time then look for a tree data structure.
|
72,128,421 | 72,132,012 | Convert python with numpy to c++ with opencv | I'm working on some optimazation and want to convert some parts from python to c++
Is it possible to convert this code to c++ with opencv?
The python code uses numpy
import numpy as np
from PIL import Image
pil_img = Image.open(input_filename)
img = np.array(pil_img)
pixels = img.reshape((-1, 3))
num_pixels = pixels.shape[0]
num_samples = int(num_pixels*5)
idx = np.arange(num_pixels)
np.random.shuffle(idx)
samples = pixels[idx[:num_samples]]
update
std::vector<uchar> sample_pixels(const cv::Mat& m, int sample_percent=5){
assert(m.isContinuous());
const auto* input = m.ptr<uchar>();
int
num_pixels = m.total(),
num_samples = num_pixels * sample_percent;
std::cout
<< "num pixels: " << num_pixels << '\n'
<< "num samples: " << num_samples << '\n';
std::vector<uchar> samples(num_samples);
// Fills idx with sequentially increasing values
std::vector<int> idx(num_pixels);
std::iota(idx.begin(), idx.end(), 0);
// Shuffle idx
std::mt19937 engine(0);
std::shuffle(idx.begin(), idx.end(), engine);
for(int i = 0; i < num_samples; i++){
//samples[i] = input[idx[i]];
}
//auto output_mat = cv::Mat(samples, false);
//cv::imwrite("enhance-samples.png", output_mat);
return samples;
}
| This is the equivalent code in C++11. This should be several times faster than your python code.
#include <random>
#include <numeric>
#include <opencv2/opencv.hpp>
void shuffling(const std::string &input_filename, const std::string &output_filename) {
// ========== UPDATE ==========
const cv::Mat plain_input_mat = cv::imread(input_filename, -1);
// Equivalent to img.reshape((-1, 3))
const cv::Mat input_mat = plain_input_mat.reshape(3);
// ============================
// By doing this, you can access the pixels without any extra checks.
assert(input_mat.isContinuous());
const auto *input = input_mat.ptr<cv::Vec3b>();
const auto num_samples = input_mat.total();
std::vector<cv::Vec3b> output(num_samples);
std::vector<int> idx(input_mat.total());
std::iota(idx.begin(), idx.end(), 0); // Equivalent to arange.
// Note: numpy uses PCG64 which does not exist in the std library.
std::mt19937 engine(0);
std::shuffle(idx.begin(), idx.end(), engine);
for (int i = 0; i < num_samples; i++) {
output[i] = input[idx[i]];
}
// Save as an image if necessary.
auto output_mat = cv::Mat(output, false);
cv::imwrite(output_filename, output_mat);
}
There are a couple of additional notes.
Note1: Due to the difference in the shuffle algorithm between python and std, the results are not exactly the same.
Note2: With your code, num_samples cannot be larger than the number of pixels in the input image, which seems to be a bug. Please check the length of the samples.
Note3: In both implementations, the most expensive part is shuffle. 60% for python and more than 80% for C++ is spent here. If you want to optimize further, this is definitely where you should exploit.
|
72,128,490 | 72,128,713 | Simple yet realistic billiard ball acceleration | I have a simple 2D game of pool. You can give a ball some speed, and it'll move around and hit other balls. But I want a ball to stop eventually, so I added some acceleration, by running this code every frame:
balls[i].ax = -balls[i].vx * 0.1;
balls[i].ay = -balls[i].vy * 0.1;
...
if(hypot(balls[i].vx, balls[i].vy) < 0.2){
balls[i].vx = 0;
balls[i].vy = 0;
}
And it works... But I find it weird, not realistic. I have no physics knowledge, but I'm pretty sure friction should not depend on speed.
How can I improve physics of slowing down without too much complexity?
| The rolling friction formula is this: F_k,r=μ_k,r_Fn. It only factors in the properties of the surface (μ_k) and the force on the ball (r_Fn). This should decelerate with a constant value, just adjust it until it looks roughly correct.
Example code:
x = 1 // mess around with this until it looks right
if (ball.xVelocity > x) { ball.xVelocity -= x } else { ball.xVelocity = 0 }
if (ball.yVelocity > x) { ball.yVelocity -= x } else { ball.yVelocity = 0 }
|
72,128,648 | 72,128,846 | How to create a `span<std::byte>` from a single generic object? | I have a parameter of type const T& and want to turn it into std::span<const std::byte> or whatever the magic type that std::as_bytes() spits out is.
Ranges have a number of constructors, mostly aimed at containers, arrays, etc. But I can't seem to turn a single object into such a span. I feel like this is not an unreasonable thing to do.
EDIT: As an example, what doesn't compile:
const std::span<const std::byte> my_span(std::ranges::single_view{ object });
| Pointer to individual object can be treated the same way as pointer to an array of single object. You can create a span like this:
const T& t = value();
auto s = std::span<const T, 1>{std::addressof(t), 1};
You can then use std::as_bytes:
auto bytes = std::as_bytes(std::span<const T, 1>{std::addressof(t), 1});
Helper functions would probably be appropriate:
template<class T>
std::span<T, 1>
singular_span(T& t)
{
return std::span<T, 1>{std::addressof(t), 1};
}
template<class T>
auto
singular_bytes(T& t)
{
return std::as_bytes(singular_span(t));
}
|
72,128,990 | 72,129,558 | How to use a button to stop a while loop that has a sleep timer? (Qt c++) | I would like to preface that I am very new to programming. So the answer may be obvious or I may have done something incorrectly; feel free to (politely) point that out. I am always excited to learn and be better!
I am trying to create and send test data using a while loop. The while loop has a sleep timer so that the data is only sent once per second. I would like the stop button to immediately stop the data from being sent (and disable the button) but because of the sleep timer, there is a lag between when the button is clicked and when the function is executed.
Here is what I have:
void DlgTestData::on_btnStart_clicked()
{
ui->btnStart->setEnabled(false);
ui->btnStop->setEnabled(true);
m_bSendingData = true;
while ( m_bSendingData )
{
CreateAndSendTestData(); //Only sends a single message
QThread::sleep(1`enter code here`)
}
}
void DlgTestData::on_btnStop_clicked()
{
m_bSendingData = false;
ui->btnStart->setEnabled(true);
ui->btnStop->setEnabled(false);
}
| Use a QTimer instead of a sleep. That way it can be stopped at any point, and it doesn't block other things that your application wants to do while it's waiting.
Make the QTimer a member pointer of your class:
class DlgTestData
{
...
private:
QTimer *m_timer;
};
Then initialize it in the constructor:
DlgTestData::DlgTestData()
{
...
// Create, but don't start the timer
m_Timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &DlgTestData::CreateAndSendTestData);
}
When your start button is pressed, simply start the timer.
void DlgTestData::on_btnStart_clicked()
{
...
m_timer->start(1000);
}
And then when the stop button is pressed, simply stop the timer.
void DlgTestData::on_btnStop_clicked()
{
...
m_timer.stop();
}
|
72,129,229 | 72,156,496 | error: (-215:Assertion failed) (int)_numAxes == inputs[0].size() in function 'getMemoryShapes' | im trying to use opencv to do face recognition using facenet512. i converted the model to onnx format using tf2onnx. i know that the input of the model should be an image like :(160,160,3). so i tried doing this using this script :
void convertDimention(cv::Mat input, cv::Mat &output)
{
vector<cv::Mat> channels(3);
cv::split(input, channels);
int size[3] = { 160, 160, 3 };
cv::Mat M(3, size, CV_32F, cv::Scalar(0));
for (int i = 0; i < size[0]; i++) {
for (int j = 0; j < size[1]; j++) {
for (int k = 0; k < size[2]; k++) {
M.at<float>(i,j,k) = channels[k].at<float>(i,j)/255;
}
}
}
M.copyTo(output);
}
after converting the image from (160,160) to (160,160,3) i still get this error :
error: (-215:Assertion failed) (int)_numAxes == inputs[0].size() in function 'getMemoryShapes'
full code :
#include <iostream>
#include <opencv2/dnn.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <vector>
using namespace std;
void convertDimention(cv::Mat input, cv::Mat &output)
{
vector<cv::Mat> channels(3);
cv::split(input, channels);
int size[3] = { 160, 160, 3 };
cv::Mat M(3, size, CV_32F, cv::Scalar(0));
for (int i = 0; i < size[0]; i++) {
for (int j = 0; j < size[1]; j++) {
for (int k = 0; k < size[2]; k++) {
M.at<float>(i,j,k) = channels[k].at<float>(i,j)/255;
}
}
}
M.copyTo(output);
}
int main()
{
cv::Mat input,input2, output;
input = cv::imread("image.png");
cv::resize(input,input, cv::Size(160,160));
convertDimention(input,input2);
cv::dnn::Net net = cv::dnn::readNetFromONNX("facenet512.onnx");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
cout << input.size << endl;
cout << input2.size << endl;
net.setInput(input2);
output = net.forward();
}
I know that i'm doing this in the wrong way(since i'm new to this). Is there any other way to change the dimensions so that it fits the model input ?
thanks in advance.
| using netron i was able to visualize the input of the model :
the origin of the problem was from the conversion of the model i just had to change this :
model_proto, _ = tf2onnx.convert.from_keras(model, output_path='facenet512.onnx')
to this :
nchw_inputs_list = [model.inputs[0].name] model_proto, _ = tf2onnx.convert.from_keras(model, output_path='facenet512.onnx',inputs_as_nchw=nchw_inputs_list)
i checked again in netron and the result were :
i can now use the model from opencv using cv::dnn::BlobFromImage()
|
72,129,236 | 72,130,778 | How to expand multiple index_sequence parameter packs to initialize 2d array in C++? | I'm trying to initialize my Matrix class with std::initializer_lists. I know I can do it with std::index_sequence, but I don't know how to expand them in one statement.
This is how I do it:
template<size_t rows, size_t cols>
class Matrix {
public:
Matrix(std::initializer_list<std::initializer_list<float>> il)
: Matrix(il,
std::make_index_sequence<rows>(),
std::make_index_sequence<cols>()) {}
private:
template<size_t... RowIs, size_t... ColIs>
Matrix(std::initializer_list<std::initializer_list<float>> il,
std::index_sequence<RowIs...>,
std::index_sequence<ColIs...>)
: values_{
{
il.begin()[RowIs].begin()[ColIs]...
}...
} {}
public:
float values_[rows][cols] = {};
};
It fails on the second expansion with error Pack expansion does not contain any unexpanded parameter packs. Maybe I can somehow specify which parameter pack I want to expand?
Hope for your help!
| I think the problem comes from the fact that RowIs and ColIs are expanded at the same time, i.e. both always having the same values during the initialization: 0, 1, 2...
You can check here that your current output (after fixing the compiler error) would be something like
[[1.1, 5.5, 9.9], [0, 0, 0], [0, 0, 0]] for the matrix below:
Matrix<3, 3> m{
{ 1.1, 2.2, 3.3 },
{ 4.4, 5.5, 6.6 },
{ 7.7, 8.8, 9.9 }
};
Because you only read fromil[0,0], il[1,1], and il[2,2] in order to set values_.
What you could do is to create a sequence with a flat index, from 0 to Rows*Cols - 1, and read every value from il with FlatIs/Cols and FlatIs%Cols:
[Demo]
#include <array>
#include <cstdint>
#include <fmt/ranges.h>
#include <initializer_list>
#include <utility>
template<std::size_t Rows, std::size_t Cols>
class Matrix {
public:
Matrix(std::initializer_list<std::initializer_list<float>> il)
: Matrix(il, std::make_index_sequence<Rows*Cols>())
{}
private:
template<std::size_t... FlatIs>
Matrix(std::initializer_list<std::initializer_list<float>> il,
std::index_sequence<FlatIs...>)
: values_{il.begin()[FlatIs/Cols].begin()[FlatIs%Cols]...}
{}
public:
std::array<std::array<float, Cols>, Rows> values_;
};
int main() {
Matrix<4, 3> m{
{ 1.1, 2.2, 3.3 },
{ 4.4, 5.5, 6.6 },
{ 7.7, 8.8, 9.9 },
{ 3.1, 4.1, 5.9 }
};
fmt::print("{}", m.values_);
}
// Outputs:
//
// [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6], [7.7, 8.8, 9.9], [3.1, 4.1, 5.9]]
|
72,129,780 | 72,130,307 | Subscripting/Indexing a Pointer in C++ | I'm working through some code for a class I'm taking, and since I'm not familiar with C++ I am confused by subscripting pointers.
My assumptions:
& prefixed to a variable name, gives you a pointer to the memory address of that value and is roughly inverse to * prefixed to a variable name, which in turn gives you the value that resides at a particular memory address.
Pointers are subscriptable, so that ptr[0] == ptr and ptr[n] == ptr + (n * data_bytes), where data_bytes depends on the particular type of the pointer (eg. 4 bytes wide for 32-bit ints).
The Problem:
When I want to subscript the memory address, I have to put it in a variable first, and I don't understand why I can't just subscript the variable directly.
Minimal Code Example:
#include <iostream>
using namespace std;
int main() {
int val = 1;
int *val_ptr = &val;
cout << &val << endl;
// works
cout << val_ptr[0] << endl;
// does not work
// cout << &val[0] << endl;
return 0;
}
Addendum
I am aware of some related questions, but they didn't really help me understand this specific issue.
I looked at:
What are the differences between a pointer variable and a reference variable in C++?
how does the ampersand(&) sign work in c++?
subscript operator on pointers
Subscripting integer variable using a pointer
and while this is almost certainly a duplicate (I will hardly be the first person that's confused by pointers), or maybe even has an answer that I overlooked in the linked questions, I'd appreciate any help!
| As per Ted Klein Bergmann's comment, there was a problem with operator precedence.
[] is considered before &. Do (&val)[0] instead.
So a working example would be
#include <iostream>
using namespace std;
int main() {
int val = 1;
// does work now
cout << (&val)[0] << endl;
return 0;
}
|
72,130,098 | 72,130,185 | Comparing multiple bits between two uint64_t's based on unique type id always returns true | I've got a map where keys are entity id's (uint32_t) and values are "signatures," aka uint64_t's with certain bits set that represent a type: std::unordered_map<uint32_t, uint64_t> m_entityComponents{};
My goal is to write a template function that accepts a variable amount of types and returns whether or not ALL of those types exist inside an entity. Let's call that function bool hasAllComponents(uint32_t entity).
To do this, I've written a method which returns a unique id for each type:
template <class T>
uint8_t getTypeId()
{
static uint8_t s_type = ++m_nextComponentType;
return s_type;
}
And then, given any number of types, I construct a new "signature" by calling getTypeId() using a fold expression to set each bit for every type present to 1:
template<typename... Types>
uint64_t getTypesSignature()
{
return ((1 << getTypeId<Types>()) | ... | 0);
}
Given these two helper functions, I should be able to check if an entity in my map has all of the passed in types with my hasAllComponents method, which uses a bitwise & operator to compare the cached signature in the map with the newly created one:
template<typename... Types>
bool hasAllComponents(uint32_t entity)
{
uint64_t signature = getTypesSignature<Types...>();
return (m_entityComponents[entity] & signature);
}
However, hasAllComponents still returns true when only some of the bits match, not all. I think the issue might be with my getTypesSignature fold logic not setting all bits correctly, although printing out the results looks fine to me. There's a flaw in my logic somewhere and would appreciate any help tracking it down!
| You are generating a signature that contains all the required bits set to 1, but you are not correctly checking if the entity's value actually has all of those same bits set to 1. You are checking if the value has any of those same bits is set to 1 instead.
In this comparison:
return (m_entityComponents[entity] & signature);
The result of the & operator will be a uint64_t, which is implicitly convertible to bool, so the return value will be true if the resulting uint64_t is non-zero, otherwise it will be false.
So, let's say the calculated signature is 107 (b01101011). That means any combination of values with any of those bits set will result in true, eg:
1: b00000001 & b01101011 = b00000001, != 0? true
2: b00000010 & b01101011 = b00000010, != 0? true
4: b00000100 & b01101011 = b00000000, != 0? false
8: b00001000 & b01101011 = b00001000, != 0? true
16: b00010000 & b01101011 = b00000000, != 0? false
32: b00100000 & b01101011 = b00100000, != 0? true
64: b01000000 & b01101011 = b01000000, != 0? true
107: b01101011 & b01101011 = b01101011, != 0? true
128: b10000000 & b01101011 = b00000000, != 0? false
255: b11111111 & b01101011 = b01101011, != 0? true
To make sure the value has all of the required bits are set, you simply need to change the comparison to this instead:
return ((m_entityComponents[entity] & signature) == signature);
The result will be true only if the value has at least all of the signature's bits set (it can have more), eg:
1: b00000001 & b01101011 = b00000001, == b01101011? false
2: b00000010 & b01101011 = b00000010, == b01101011? false
4: b00000100 & b01101011 = b00000000, == b01101011? false
8: b00001000 & b01101011 = b00001000, == b01101011? false
16: b00010000 & b01101011 = b00000000, == b01101011? false
32: b00100000 & b01101011 = b00100000, == b01101011? false
64: b01000000 & b01101011 = b01000000, == b01101011? false
107: b01101011 & b01101011 = b01101011, == b01101011? true
128: b10000000 & b01101011 = b00000000, == b01101011? false
255: b11111111 & b01101011 = b01101011, == b01101011? true
|
72,130,690 | 72,130,963 | Does boost atomic reference counting example contain a bug? | I'm referring to this example.
The authors use memory_order_release to decrement the counter. And they even state in the discussion section that using memory_order_acq_rel instead would be excessive. But wouldn't the following scenario in theory lead to that x is never deleted?
we have two threads on different CPUs
each of them owns an instance of a shared pointer, both pointers share ownership over the same control block, no other pointers referring that block exist
each thread has the counter in its cache and the counter is 2 for both of them
the first thread destroys its pointer, the counter in this thread now is 1
the second thread destroys its pointer, however cache invalidation signal from the first thread may still be queued, so it decrements the value from its own cache and gets 1
both threads didn't delete x, but there are no shared pointers sharing our control block => memory leak
The code sample from the link:
#include <boost/intrusive_ptr.hpp>
#include <boost/atomic.hpp>
class X {
public:
typedef boost::intrusive_ptr<X> pointer;
X() : refcount_(0) {}
private:
mutable boost::atomic<int> refcount_;
friend void intrusive_ptr_add_ref(const X * x)
{
x->refcount_.fetch_add(1, boost::memory_order_relaxed);
}
friend void intrusive_ptr_release(const X * x)
{
if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) {
boost::atomic_thread_fence(boost::memory_order_acquire);
delete x;
}
}
};
The quote from discussion section:
It would be possible to use memory_order_acq_rel for the fetch_sub
operation, but this results in unneeded "acquire" operations when the
reference counter does not yet reach zero and may impose a performance
penalty.
| All modifications of a single atomic variable happen in a global modification order. It is not possible for two threads to disagree about this order.
The fetch_sub operation is an atomic read-modify-write operation and is required to always read the value of the atomic variable immediately before the modification from the same operation in the modification order.
So it is not possible for the second thread to read 2 when the first thread's fetch_sub was first in the modification order. The implementation must assure that such a cache incoherence cannot happen, if necessary with the help of locks if the hardware doesn't support this atomic access natively. (That is what the is_lock_free and is_always_lock_free members of the atomic are there to check for.)
This is all independent of the memory orders of the operations. These matter only for access to other memory locations than the atomic variable itself.
|
72,131,086 | 72,131,130 | Using parent constructor instead of defining child | I have a base class Foo and two child classes Bar and Car. Foo is pure virtual. Bar inherits foo with its own constructor to assign a variable. However Car doesn't have a constructor.
#include <memory>
#include <iostream>
class Foo{
public:
virtual void T() = 0;
};
class Bar : public Foo{
protected:
int n;
public:
Bar(int n){
this->n = n;
}
virtual void T(){
std::cout << n << std::endl;
}
};
class Car : public Bar{
void T(){
std::cout << n << std::endl;
}
};
int main(){
Foo* f = new Car(10);//error
return 0;
}
What I'd like to do essentially, is instantiate new Car but instead of writing out the constructor for Car and then calling the parents constructor
Car(int n) : Bar(n){
}
It would be so much easier if by instantiate car, because a constructor isn't explicitly defined it automatically calls the parent's constructor?
Is that possible?
| You can apply inheriting constructors as:
class Car : public Bar {
using Bar::Bar;
...
};
Then
Car car(10); // Bar base subobject is initialized by Bar(10)
|
72,131,095 | 72,131,284 | The sum of a sequence | I'm trying to make a function for calculating this formula
#include <iostream>
#include <vector>
double Sequence(std::vector < double > & a) {
double result = 0;
for (int i = a.size() - 1; i > 0; i--) {
if (a[i] == 0) throw std::domain_error("Dividing with 0");
if (i > 1)
result += 1 / (a[i - 1] + 1 / a[i]);
else result += a[i - i];
std::cout << a[i] << " " << result << " " << "\n";
}
return result;
}
int main() {
std::vector<double>a{1,2,3,4,5};
try {
std::cout << Sequence(a);
} catch (std::domain_error e) {
std::cout << e.what();
}
return 0;
}
Code gives correct result for {1,2,3} sequence. However, if I add a few numbers to that sequence result becomes wrong. Could you help me to fix this?
| if (i > 1)
result += 1 / (a[i - 1] + 1 / a[i]);
else result += a[i - i];
This is wrong; it just happens to work if you have three or fewer terms.
The recurrence you actually want is
if (i == a.size() - 1) {
result = a[i];
} else {
result = a[i] + 1 / result;
}
you can see that this is a correct recurrence by the fact that
Tidying up some more things (removing the condition from inside the loop, fixing an off-by-one in the loop termination condition, and correcting the exception condition):
double Sequence(std::vector<double> &a) {
double result = a[a.size() - 1];
for (int i = a.size() - 1; i >= 0; i--) {
if (result == 0)
throw std::domain_error("Dividing with 0");
result = a[i] + 1 / result;
}
return result;
}
|
72,131,285 | 72,131,963 | Declare a constexpr static member that is a function of a potentially-absent member in a template parameter? | I have a templated class for which I would like to provide a constexpr integer whose value is determined by the presence or absence of a constexpr integer in the template parameter:
template<typename Traits>
class Foo
{
static constexpr int MaxDegree =
std::conditional<
std::is_integral<Traits::MaxDegree>::value,
std::integral_constant<int, Traits::MaxDegree>,
std::integral_constant<int, 0>
>::value;
};
struct TraitA { };
struct TraitB { constexpr static int MaxDegree = 1; };
int main()
{
std::cout
<< Foo<TraitA>::MaxDegree /* should be 0 */ << " "
<< Foo<TraitB>::MaxDegree; /* should be TraitB::MaxDegree == 1 */
<< "\n";
}
Obviously, this doesn't work since std::is_integral fails for TraitA. Is there anything that will work?
I'm constrained to c++11.
| Traits::MaxDegree
yields a compiler error, if the member doesn't exist. This means you cannot use this code as part of the expression directly.
You could use constexpr functions with SFINAE to implement this though:
template<class T>
constexpr typename std::enable_if<std::is_integral<decltype(T::MaxDegree)>::value, int>::type GetMaxDegree()
{
return T::MaxDegree;
}
template<class T>
constexpr int GetMaxDegree(...) // this one is only used, if the first version results in a substitution failure
{
return 0;
}
template<typename Traits>
class Foo
{
public:
static constexpr int MaxDegree = GetMaxDegree<Traits>();
};
|
72,131,693 | 72,133,797 | boost::asio::io_context::stop segfalt in gtest setup and teardown | Using C++17. I am trying to setup a gtest fixture that will create a fresh io_context to run timers on for each test case. My test segfault about 90% of the time. If I debug and step very slowly, I can get it to run all the way through.
I am not sure what's going on here. I've went and created a new thread and new ioservice every run, just to make sure there was no carry over from previous tests. Then I just deleted the test contents entirely to narrow it down. It throws on the stop call.
#include "gtest/gtest.h"
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
class TrafficLightTestSuite : public testing::Test
{
public:
protected:
boost::asio::io_context * m_ioContext;
boost::thread * m_ioThread;
void SetUp() override
{
std::cout << "Setup" << std::endl;
m_ioThread = new boost::thread([&]()
{
m_ioContext = new boost::asio::io_context();
std::cout << "IO Service created" << std::endl;
// Keep the io service alive until we are done
boost::asio::io_service::work work(*m_ioContext);
m_ioContext->run();
std::cout << "IO Context run exited" << std::endl;
delete m_ioContext;
m_ioContext = nullptr;
std::cout << "IO Context deleted" << std::endl;
});
}
void TearDown() override
{
std::cout << "Tear down stopping IO Context" << std::endl;
m_ioContext->stop();
m_ioThread->join();
std::cout << "Thread exit" << std::endl;
delete m_ioThread;
}
};
TEST_F(TrafficLightTestSuite, testTimeLapse)
{
std::cout << "Performing test" << std::endl;
}
Output when running:
Testing started at 1:49 PM ...
Setup
Performing test
Tear down stopping IO Context
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Output when stepping through with debugger:
Testing started at 1:55 PM ...
Setup
IO Service created
Performing test
Tear down stopping IO Context
IO Context run exited
IO Context deleted
Thread exit
Process finished with exit code 0
io_context has to be thread safe, how else would you tell it to stop?
Anyone spot a problem?
| The problem is that there is no guarantee that anything on a thread is going to execute before the main thread resumes execution. This caused problems where the ioservice was not created and running before the test case executed, where it was assumed that the ioservice would be running.
This can be fixed using a semaphore that can be waiting on, and queuing up a post on that semaphore before calling ioservice::run. That way, as soon as the ioservice runs, the semaphore posts and the test case cannot execute until that occurs.
class TrafficLightTestSuite : public testing::Test
{
public:
protected:
boost::asio::io_context m_ioContext {};
boost::asio::io_service::work m_work {m_ioContext}; // Keeps the ioservice running when nothing is posted
boost::thread m_ioThread {};
boost::interprocess::interprocess_semaphore m_semaphore {0};
void SetUp() override
{
// When the ioservice starts up, the semaphore will notify anyone that was waiting on it to run
m_ioContext.post([&]() { m_semaphore.post(); });
// Run the io service on its own thread, where completion handlers will be called
m_ioThread = boost::thread(boost::bind(&boost::asio::io_service::run, &m_ioContext));
// Test cases should wait on the semaphore to ensure the io service is running before they execute.
// In production environment, you'd probably init the ioservice in some manner of application setup and do a
// similar notification when everything was initialized.
m_semaphore.wait();
}
void TearDown() override
{
m_ioContext.stop();
m_ioThread.join();
}
};
TEST_F(TrafficLightTestSuite, testInitialColor)
{
// This is guaranteed not to execute until the ioservice is running
}
You could also make your own semaphore using a condition variable. If using C++20, there are standard semaphores available,
|
72,131,793 | 72,143,663 | Can you relink/modify relative shared library look up paths? | I am running into the following situation. Project A has libraries A1, A2, A3... That follow their own directory structure. For example:
Libaries/
|
|--Dir1/
| |
| |--A1.so
| |--A2.so
|
|--Dir2/
| |--A3.so
| |--A4.so
In this case Project A compiles just fine. The libraries of project A are dependencies for project B and a script (that I have no control over) copies them onto B's directory in a flat hierarchy i.e this
BLibraries/
|--A1.so
|--A2.so
|--A3.so
|--A4.so
So the relative paths are no longer the same.
B loads symbols from these libraries dynamically through dlopen. In this case, If A1 needs symbols from A2, B they appear as undefined and so B fails to load A1.
Is there a way I can poke the files Ai.so and tell them "Hey that other library whose symbols you need is actually over here now"?
|
Is there a way I can poke the files Ai.so and tell them "Hey that other library whose symbols you need is actually over here now"?
You can use patchelf to do that, but you shouldn't.
Since you control how A*.so is built, you should set their RPATH so that it works "out of the box". Adding -rpath=/path/to/BLibraries to A*.so link command is probably all that's needed.
|
72,131,818 | 72,132,018 | gcc-10-ar thinks the invalid "." option is being passed to it | I'm compiling a game using the Source Engine. When I run make, after a while the archiver tool complains about an invalid option ".":
/usr/bin/ar: invalid option -- '.'
this happens with every archiver I have installed: gcc-10-ar, llvm-10-ar, and busybox ar.
The command the makefile is trying to run is:
gcc-ar-10 ../lib/public/linux32/raytrace.a ./obj_raytrace_linux32/release/raytrace.o ./obj_raytrace_linux32/release/trace2.o ./obj_raytrace_linux32/release/trace3.o
I don't use the archiver tool often, but this looks like a valid command to me.
Normally the issue with those is that a dash is being prepended which makes the archiver tool think whatever is following it are the "mini options" like -lm
In my case there aren't any dashes at all. I think the . is from the path but that should be interpreted as a file path and not a command-line argument.
| The first argument to ar is supposed to be one or more characters indicating the operation to perform (optionally prefixed with -) and modifiers to this operation.
If you want to create a new archive from the object files, you probably want rcs, which asks ar to insert the listed files into the archive with replacement (r), create the archive if necessary (c) and to create an index for the archive (s).
So for example:
gcc-ar-10 rcs ../lib/public/linux32/raytrace.a ./obj_raytrace_linux32/release/raytrace.o ./obj_raytrace_linux32/release/trace2.o ./obj_raytrace_linux32/release/trace3.o
I assume that ar is giving you the error since it tries to interpret the first . of the first argument as one of these operation instructions.
See also man ar.
As for the linked repository (although I have no experience with it and this is just an observation based on looking at one file in it): It seems that the Makefile expects AR, if it is specified in the environment, to include not only the path to the executable, but also the above-mentioned options (see this line setting a default value).
This is not what is usually expected from the AR environment variable, so this is unconventional. A workaround is to add the rcs argument directly to the environment variable, e.g. if AR is already set in the environment as usual:
AR="$AR rcs" make
instead of
make
Don't set AR globally with these options, since other typical Makefiles will be confused by it.
|
72,131,930 | 72,132,196 | Why aren't temporary container objects pipeable in range-v3? | Why is the following
#include <iostream>
#include <string>
#include <range/v3/all.hpp>
std::vector<int> some_ints() {
return { 1,2,3,4,5 };
}
int main() {
auto num_strings = some_ints() |
ranges::views::transform([](int n) {return std::to_string(n); }) |
ranges::to_vector;
for (auto str : num_strings) {
std::cout << str << "\n";
}
return 0;
}
an error, while
int main() {
auto ints = some_ints();
auto num_strings = ints |
ranges::views::transform([](int n) {return std::to_string(n); }) |
ranges::to_vector;
for (auto str : num_strings) {
std::cout << str << "\n";
}
return 0;
}
is fine?
I would expect the lifetime of the temporary to be extended to the lifetime of the whole pipeline expression so I don't understand what the problem is.
The error from Clang is
<source>:10:36: error: overload resolution selected deleted operator '|'
auto num_strings = some_ints() |
~~~~~~~~~~~ ^
/opt/compiler-explorer/libs/rangesv3/0.11.0/include/range/v3/view/view.hpp:153:13: note: candidate function [with Rng = std::vector<int, std::allocator<int>>, ViewFn = ranges::detail::bind_back_fn_<ranges::views::transform_base_fn, (lambda at <source>:11:34)>] has been explicitly deleted
operator|(Rng &&, view_closure<ViewFn> const &) // ****** READ THIS *******
from Visual Studio I get
error C2280: 'std::vector<int,std::allocator<int>> ranges::views::view_closure_base_ns::operator |<std::vector<int,std::allocator<int>>,ranges::detail::bind_back_fn_<ranges::views::transform_base_fn,main::<lambda_1>>>(Rng &&,const ranges::views::view_closure<ranges::detail::bind_back_fn_<ranges::views::transform_base_fn,main::<lambda_1>>> &)': attempting to reference a deleted function
1> with
1> [
1> Rng=std::vector<int,std::allocator<int>>
1> ]
Both errors seem to be saying that the pipe operator is explicitly deleted for r-value references?
| Short answer would be because they are lazy and | does not transfer ownership.
I would expect the lifetime of the temporary to be extended to the lifetime of the whole pipeline expression so I don't understand what the problem is.
Yes, that is exactly what would happen, but nothing more. Meaning that as soon as the code hits ;, some_ints() dies and num_strings now contains "dangling" range. So a choice was made to forbid this example to compile.
|
72,132,309 | 72,142,187 | C++ {fmt} library: Is there a way to format repeated format fields? | I have a program with many formatted write statements that I'm using the fmt library for. Some of them have many fields, say 100 for example purposes, something like this:
fmt::print(file_stream, "{:15.5g}{:15.5g}{:15.5g}/*and so on*/", arg1, arg2, arg3/*same number of arguments*/);
Is there a straightforward way to truncate the fields so they don't all have to be written out? Obviously this example wouldn't work but it illustrates the idea:
fmt::print(file_stream, 100("{:15.5g"), arg1, arg2, arg3/*etc*/);
| You can put your arguments in an array and format part of this array as a view (using span or similar) with fmt::join (https://godbolt.org/z/bo1GrofxW):
#include <array>
#include <span>
#include <fmt/format.h>
int main() {
double arg1 = .1, arg2 = .2, arg3 = .3;
double args[] = {arg1, arg2, arg3};
fmt::print("{:15.5}", fmt::join(std::span(args, args + 2), ""));
}
Output:
0.1 0.2
|
72,132,658 | 72,134,496 | Qt Creator Release Build Quit Unexpectedly | After compiling any version (Debug and Release) of the application with Qt Creator, it only runs from under Qt Creator with the option: "Add build library search path to DYLD_LIBRARY_PATH and DYLD_FRAMEWORK_PATH".
I try compilation and use macdeployqt for creation dmg. App after start crash: "Quit Unexpectedly" because can't find libraries:
otool result:
App Contents/Frameworks after macdeployqt:
How to deploy app on Qt and run after compilation? How set rpath?
| I found solution, macdeployqt not copy all required libraries and some files to App, need manually copy to:
Plugins
cp -r $QT_MACOS_PATH/Plugins/ to App/Contents/Plugins/
Resources/qml
mkdir App/Contents/Resources/qml
cp -r $QT_MACOS_PATH/qml/ to App/Contents/Resources/qml/
Frameworks
cp -r $QT_MACOS_PATH/lib/*.framework to App/Contents/Frameworks
Then you can use macdeployqt for your application (Optional):
macdeployqt *.app
Now you can run your application. You can set path to Qt with your installer for distribution in App/Contents/Resources/qt.conf and not copy them all.
Of course, it is better not to do this, otherwise the size of the application will be very large. This only applies to the test poligon. For distribution, create an installer.
|
72,133,602 | 72,133,778 | Stationary element of matrix | I'm trying to write a function which will check if matrix has (at least one) stationary elements. An element of a matrix is stationary if its value is equal to the value of the elements located to the left, right, above and below it.
#include <iostream>
#include <vector>
bool Stationary(std::vector < std::vector < int >> a) {
int total_elements = 0, rows = a.size();
int up, down, left, right;
for (auto i: a)
for (auto j: i)
total_elements++;
if (total_elements % rows)
throw std::range_error("Ragged matrix");
int columns = total_elements / rows;
int count = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++) {
up = a[i][j + 1];
down = a[i][j - 1];
right = a[i + 1][j];
left = a[i - 1][j];
std::cout << up << " " << down << " " << right << " " << left << " " << a[i][j] << "\n";
if (up == down == right == left == a[i][j]) return true;
}
return false;
}
int main() {
std::vector<std::vector<int>>a{
{2,1,3},
{1,1,1},
{4,1,5}};
try {
if (Stationary(a))
std::cout << "Yes";
else std::cout << "No";
} catch (std::range_error e) {
std::cout << e.what();
}
return 0;
}
Problem with my code is access to random elements that are not integral parts of the matrix, because with the command i+1 or j+1 I go beyond the frame of the matrix. Could you help me to modify this without leaving the matrix frame?
| The problem is that you check the edges of the matrix and in a position like a[0][0] you step out of bounds when checking a[-1][0] and a[0][-1]. Instead start your loops at 1 and end at size() - 2 (inclusive).
Another suggestion is to not take the matrix by-value which copies the whole matrix. Take it by const& instead.
Example:
#include <iostream>
#include <stdexcept>
#include <vector>
bool Stationary(const std::vector<std::vector<int>>& a) {
// with less than 3 rows, it can't have 4 neighbours (left, right, above, below):
if (a.size() < 3) return false;
size_t cols = a[0].size();
for (size_t i = 1; i < a.size(); ++i)
if (a[i].size() != cols) throw std::range_error("Ragged matrix");
// start at 1 and end at size() - 2:
for (size_t y = 1; y < a.size() - 1; ++y) {
for (size_t x = 1; x < cols - 1; ++x) {
int value = a[y][x];
if (value == a[y - 1][x] &&
value == a[y + 1][x] &&
value == a[y][x - 1] &&
value == a[y][x + 1]) return true;
}
}
return false;
}
int main() {
std::vector<std::vector<int>> a{{2, 1, 3},
{1, 1, 1},
{4, 1, 5}};
std::cout << Stationary(a) << '\n';
}
|
72,133,687 | 72,133,808 | QT5 - Detecting when new files are added to a directory and retrieving their path | My problem is relatively simple. I have an application where I need to monitor a particular folder (the downloads folder, in my case) for added files. Whenever a file is added to that folder, I want to move that file to a completely different directory. I have been looking at QFileSystemWatcher; however, none of the signals it provides seems to be ideal for my situation.
Here is my current code:
connect(&m_fileWatcher, &QFileSystemWatcher::directoryChanged, this, &FileHandler::directoryChanged);
void FileHandler::directoryChanged(const QString &dir)
{
qDebug() << "File changed...." << string;
// Some other logic
}
This signal only gives me a string to work with which is the directory that witnessed a change. I don't know what kind of change took place (add, rename, or delete), and I also have no idea which file has changed.
I understand that I could store all of the files in the directory in some sort of data structure and do some other logic when this signal is emitted, but that doesn't seem very performant in this case since I'm dealing with the user's downloads folder (which could contain thousands of files).
How can I make this work? Should I refer to a different helper class provided by QT, or is there some other way I can do this while utilizing QFileSystemWatcher? I'm simply just looking for ideas.
Thank you.
| You’ve hit the limit of what the underlying OS provides: notification of change to the content of a directory.
If you wish to identify the file:
deleted you must have a prior list of files available for compare
added same as deleted
modified loop through the directory for the file with the most recent last modified date
IDK if you wish to use any specific filename container class from Qt or just a std::vector <std::filesystem::path> or the like for your cached folder contents.
|
72,133,917 | 72,133,974 | C++ structure reference from member reference | Given the following setup...
struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};
// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance that (ar) belongs to
...how do I get br and cr from ar without UB (undefined behaviour)?
| Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should return 0 in this case, since a is the 1st non-static data member of C, but best not to assume that) to help you access the C object, eg:
C& get_parent(A& ar)
{
return *reinterpret_cast<C*>(reinterpret_cast<char*>(&ar) - offsetof(C, a));
}
B& get_sister(A& ar)
{
return get_parent(ar).b;
}
Online Demo
|
72,134,088 | 72,285,933 | multiple definition of `std::logic_error::logic_error(std::logic_error const&) | I am cross-compiling a windows application from my Linux host machine and I am getting a linking error of multiple definitions between two files in the std!
/usr/lib/gcc/i686-w64-mingw32/7.3-win32/libstdc++.a(cow-stdexcept.o):(.text$_ZNSt11logic_errorC2ERKS_+0x0): multiple definition of `std::logic_error::logic_error(std::logic_error const&)'
/home/user1/work/windows-release/test/test.o:/usr/lib/gcc/i686-w64-mingw32/7.3-win32/include/c++/stdexcept:113: first defined here
collect2: error: ld returned 1 exit status
in stdexcept:113 I found the definition of the following class
class logic_error : public exception
{
__cow_string _M_msg;
public:
/** Takes a character string describing the error. */
explicit
logic_error(const string& __arg) _GLIBCXX_TXN_SAFE;
#if __cplusplus >= 201103L
explicit
logic_error(const char*) _GLIBCXX_TXN_SAFE;
#endif
#if _GLIBCXX_USE_CXX11_ABI || _GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS
logic_error(const logic_error&) _GLIBCXX_USE_NOEXCEPT;
logic_error& operator=(const logic_error&) _GLIBCXX_USE_NOEXCEPT;
#endif
virtual ~logic_error() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;
/** Returns a C-style character string describing the general cause of
* the current error (the same string passed to the ctor). */
virtual const char*
what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;
# ifdef _GLIBCXX_TM_TS_INTERNAL
friend void*
::_txnal_logic_error_get_msg(void* e);
# endif
};
These are my build flags
-g -Wall -fno-strict-aliasing -D_WIN32_WINNT=0x0501 -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++11 -Wno-unused-parameter -Wno-deprecated-declarations -Wno-placement-new -Wno-unused-local-typedefs -Wno-deprecated -Wextra -DBOOST_LOG_DYN_LINK -O3 -O -MMD -MP -MT
| Building the code with CXX_FLAGS += -D_GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS solved the issue.
by looking at the symbols of test.o using nm -C test.o, I found that the copy constructor was defined and had an address mentioned next to it, I made an assumption that the compiler automatically created the copy constructor for me as it didn't find its prototype in the class declaration because of #if _GLIBCXX_USE_CXX11_ABI || _GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS and that's why by defining _GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS the complier would know that its implemented somewhere else so don't create it!
|
72,134,259 | 72,146,392 | in-tree include directory with bazel custom toolchain | Is it possible to configure a Bazel custom toolchain to include directories in the repository?
Assume that I have following in the root of my repository:
sysroots/armhf/include/myheader.h
sysroots/amd64/include/myheader.h
myproject1/component.cpp
myproject2/component.cpp
I'd like to configure toolchain such that when I run bazel build --config armhf, component.cpp files including myheader.h would get the header from sysroot/armhf/include directory, and when I run bazel build --config amd64, file from corresponding sysroot/amd64 directory were used.
This needs to work without having to modify projects containing component.cpp files.
Essentially I would like to check in platform specific headers and binaries in the source repository along with the code.
| If you haven't found it yet, you need to write C++ toolchains. The Configure C++ Toolchains Tutorial is a good place to start, if you have more specific questions they'll get better answers as separate questions. I'm going to answer specifically about the paths here.
Most of the paths are just normal paths relative to the execution root. That typically means external/<repo_name>/<package>/<name> for paths in external repositories, or just <package>/<name> for paths in the main repository. bazel-toolchain's pkg_path_from_label function implements this logic, for example. In your case, that's sysroots/armhf/include for the first path.
cxx_builtin_include_directories is special. Paths there have unique syntaxes to generate absolute paths. The relevant one looks like "%package(@your_toolchain//relative/clang/include)%", with @your_toolchain replaced with your repository's name. In your case that means something like "%package(@//sysroots/armhf)%/include/myheader.h". Depending on where the package boundary is (deepest folder with a BUILD file) more or less of that might need to be in the %package() part.
Those directives get expanded when generating compiler command lines. I'm not aware of any documentation besides the source.
|
72,134,451 | 72,134,571 | Make functions instantiate its generic parameter | What would be an equivalent to the following C++ program in rust?
#include <iostream>
#include <vector>
template <typename T>
T stuff() {
return T();
}
int main() {
std::vector<int> vec = stuff<std::vector<int>>();
vec.push_back(1);
for (auto &&i : vec) {
std::cout << i << std::endl;
}
}
I tried the following:
trait Newable{
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
I tried using a newtype for this -
struct NwVec<T>{
vec: Vec<T>
}
impl<T> Newable<T> for NwVec<T>{
fn new() -> Self {
NwVec { vec: Vec::new() }
}
}
and used it like so:
fn main() {
let x: NwVec<i32> = stuff::<NwVec<i32>>();
}
but I get a
error[E0277]: the trait bound `NwVec<i32>: Newable<NwVec<i32>>` is not satisfied
--> src\main.rs:2:25
|
2 | let x: NwVec<i32> = stuff();
| ^^^^^ the trait `Newable<NwVec<i32>>` is not implemented for `NwVec<i32>`
|
= help: the following implementations were found:
<NwVec<T> as Newable<T>>
note: required by a bound in `stuff`
Is there a way to achieve what the C++ program achieves?
P.S.: I am rather new to rust, I am really sorry if the solution to this is trivial.
| Maybe there was a mixup when you entered the code that you say gave you the error you provided, because that same code did not yield that specific error when I tried it.
Either way, you were close. Consider this code:
trait Newable {
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
#[derive(Debug)]
struct NwVec<T> {
vec: Vec<T>
}
impl<T> Newable for NwVec<T> {
fn new() -> Self {
NwVec { vec: Vec::new() }
}
}
fn main() {
let x: NwVec<i32> = stuff::<NwVec<i32>>();
println!("{x:?}");
}
Playground
All I changed was:
Added #[derive(Debug)] to NwVec<T> so we could print it out
I removed the type parameter <T> on Newable<T> from your original impl<T> Newable<T> for NwVec<T>. This is because the Newable trait itself, as provided in your post, is not generic, so it takes no type parameter.
I imagine this is something of a learning exercise, but in case you were curious, you may be interested in std::default::Default which is a trait somewhat similar to your Newable in that implementations provide a simple and consistent way to create a "default" version of something. Vec itself is an implementer, so you can call e.g. Default::default() or Vec::default() wherever a Vec<T> is expected. Check this playground.
|
72,134,789 | 72,134,831 | Error Missing Type specifer - int assumed . Note C++ does not support default init | In order to make two objects, User1 and User2, of a class User sending and receiving messages,
#include <iostream>
using namespace std;
class reply
{
public:
User* sender;
};
class User
{
BlockingQueue<Message > queue;
public:
void sendMessage()
{
};
void run()
{ //......
}
};
In the Player class, I get an error indicating that Player* sender is not a member of the Message class!
And in the Message class, i get this error:
Severity Code Description Project File Line Suppression State
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int
Can you please help me with this?
| You have to add a forward declaration of player before Message
class Player; <<<<=====
class Message
{
public:
Player* sender ;
std::string text;
};
see here for explanation What are forward declarations in C++?
and yes - it should be std::string
|
72,135,134 | 72,135,568 | Pointer to const object as a data member | Accordingly to C++ best practices on IsoCpp we shouldn't have a const or reference data member: C.12: Don’t make data members const or references
But it does not specify if a pointer to a const object is allowed or not. Consider the example:
class Connection {
gsl::not_null<const Network*> m_network;
...
public:
[[nodiscard]] const Network* getNetwork() const;
...
}
// Implementation
const Network* Connection::getNetwork() const {
return m_network;
}
Is it still conformant with the best practice described? The pointer isn't const but the data the pointer points to is.
Should we remove const from member declaration but still mark the getter return type as a pointer to const?
| It depends.
The reason this recommendation exists, is to make your type copyable and assignable, with both having matching semantics.
So consider this:
struct Connection {
Network const& network;
/**/
};
Copying this is perfectly fine, right? But then assigning breaks because network will not be reseatable.
So in this case, replacing that member with an e.g. std::shared_ptr<Network const> is fine. Presumably several connections can use the same network.
But -- if you do not want sharing but each object to have its own copy of the member, then you are left with reconstructing that member on assignment, because the old object cannot be changed. Depending on the object that might not be what you want to do.
For example:
struct Connection {
std::shared_ptr<Network const> network;
std::unique_ptr<std::vector<Entry> const> properties;
};
Aside from a pointer-to-vector being bad form (double indirection for no good reason). Reconstructing a vector anew requires a new memory allocation, while just reusing the old will not (assuming there was enough memory allocated).
Granted, this is a bit of constructed example, and there would maybe be a way to go around that. But the point is, that the similarty of your copy and assignment will heavily depend on the quality of the copy and assignment of the member object.
In such a case the same reasoning that applied to the situation without the pointer similarly applies to the situation with the pointer. You will have to decide whether that is acceptable for your type.
However, I hold that not every type must be assignable. You can make the conscious decision to have a type that just cannot be assigned to. Then and only then, just have a const member without any indirection.
|
72,135,880 | 72,136,171 | why can't compare string in #if expression in c++ | i want to write code like this but i can't:
#define COLOR "red"
#define RED "red"
#define BLUE "blue"
int main()
{
// following code can't be compiled
#if (COLOR==RED)
cout<<"red"<<endl;
#endif
// following code can work
if(COLOR==RED)
cout<<"red"<<endl;
else
cout<<"notred"<<endl;
}
so how can i realize string compare in #if expression? or may be this is not possible?
BTW i know i can realize in other ways like following:
#define COLOR 1
#define RED 1
#define BLUE 2
// can be compiled and word correctly
#if(COLOR==RED)
cout<<"red"<<endl;
#endif
| Because #if only works with integers
expression is a C expression of integer type, subject to stringent restrictions. It may contain...
see https://gcc.gnu.org/onlinedocs/gcc-3.0.1/cpp_4.html#SEC38
|
72,135,948 | 72,175,346 | Is seastar::thread a stackful coroutine? |
Seastar allows writing such code, by using a seastar::thread object
which comes with its own stack.
The seastar::thread allocates a 128KB stack, and runs the given
function until then it blocks on the call to a future's get() method.
Outside a seastar::thread context, get() may only be called on a
future which is already available. But inside a thread, calling get()
on a future which is not yet available stops running the thread
function, and schedules a continuation for this future, which
continues to run the thread's function (on the same saved stack) when
the future becomes available.
The above sentences are quoted from seastar tutorial, Does this mean that seastar::thread is a kind of stackful coroutine?
| Yes, seastar::thread and "stackful coroutines" are indeed very similar concepts.
Note that Seastar also supports stackless coroutines, using the new C++20 coroutines feature. This is now almost always preferable over stackful coroutines (seastar::thread): stackless coroutines are lighter and are useful also in heavily concurrent operations (where a stack per waiter is a big waste), have nicer support in the C++ language. Stackless coroutines also cooperate better with future-based code - when you write a function assuming it is running in a seastar::thread, i.e., using get() on unready futures, you can only call this function from inside a seastar::thread. In contrast, if you write a stackless coroutine with the new C++ syntax - you can call it from any future-based or coroutine-based code.
|
72,136,018 | 72,136,074 | "auto" keyword: How to customize it? | Title is vague, I know. Consider this:
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T>
using StrongRef = std::shared_ptr<T>&;
struct Person {
std::string m_name;
Person(const std::string& l_name) : m_name(l_name) {}
};
class Container{
Ref<Person> m_person;
public:
People(const std::string& l_name) {
m_person = std::make_shared<Person>(l_name);
}
~People() {}
StrongRef<Person> GetPerson() { return m_person; } //returning a ref to a shared
//pointer, so it doesn't increase the use_count
};
int main(){
Container container("Pedro");
/*Here lies my problem. The auto keyword is presuming a shared_ptr, not a shared_ptr&*/
auto person = container.GetPerson();
/*I want it auto keyword to be StrongRef<Person> not std::shared_ptr<Person>*/
}
Is there a way for my auto keyword to be a StrongRef instead of deducing std::shared_ptr?
| You can tell auto you want a reference like
auto& person = container.GetPerson();
This does have one drawback though as if GetPerson changes to return by value, then you are trying to bind an lvalue reference to an rvalue and that will result in a compiler error.
To get around this, you can use a forwarding reference like
auto&& person = container.GetPerson();
Now, if container.GetPerson() return an rvalue, person will be an rvalue reference and it will extend the lifetime of the temporary object to match the lifetime of person.
If container.GetPerson() returns an lvalue, then person will be a plain old lvalue reference to the returned object just like if you had used auto& instead.
|
72,136,026 | 72,136,051 | Boolean function returning 24, and acting inconsistent across multiple compilers | Alright, this is driving me nuts and I have no idea what's going on. I have some code I'm making for school that basically takes in a string and a start and end index, and spits out true if the string is a palindrome, and false if it isn't. I added some extra stuff to make sure that it works if you give it a sentence with spaces and punctuation, and besides a small logic error that makes it return true if the middle two letters are different, it works..... almost. It has a super funny error where it seems to act differently on different compilers. On repl.it, I get a stack smash detected message for basically any input, but for some things, like inputting Hello, World! I get a segmentation fault. When I run it on Visual Studios 2019 it returns 24 for every false input, I don't even know how a boolean even returns something like 24, but if I change the function from type bool to type int, then it works perfectly.... except for repl.it, where I still get stack smashing. I also don't want to just leave it at an int and call it a day because that feels like a bandaid, what the heck is going on??
tldr; Boolean function returning 24 on Visual Studios, and stack smashing on others, changing the function return type to int instead of bool fixes it on Visual Studios, but not for others.
#include <iostream>
#include <string>
using namespace std;
bool isPalindrom(string, int, int);
int main() {
string str = "R aceCar";// should return true
bool thing = isPalindrom(str,0,str.length()-1);
cout << thing << endl;
}
bool isPalindrom(string str, int start, int end){
if(end - start == 1 && (tolower(str[start]) == tolower(str[end])) || start == end){
return 1;
}
else{
if((str[start] >= 'a' && str[start] <= 'z') || (str[start] >= 'A' && str[start] <= 'Z')){
if((str[end] >= 'a' && str[end] <= 'z') || (str[end] >= 'A' && str[end] <= 'Z')){
if(tolower(str[start]) == tolower(str[end])){
// cout << str[start] << ' ' << str[end] <<endl;
isPalindrom(str, start+1, end-1);
}
else{
return 0;
}
}
else{
isPalindrom(str, start, end -1);
}
}
else{
isPalindrom(str, start+1, end);
}
}
}
| you are not returning a value from isPalindrom, - your compiler is surely warning you about it, mine did
1>C:\work\ConsoleApplication1\ConsoleApplication1.cpp(68): warning C4715: 'isPalindrom': not all control paths return a value
you probably - its your logic - just want
if (tolower(str[start]) == tolower(str[end])) {
// cout << str[start] << ' ' << str[end] <<endl;
return isPalindrom(str, start + 1, end - 1); <<<<===
}
else {
return 0;
}
}
else {
return isPalindrom(str, start, end - 1); <<<<====
}
}
else {
return isPalindrom(str, start + 1, end); <<<<====
}
with those edits your code now says 0 - which I assume means that "R ceCar" is not a palindrome
Also this really should be
bool isPalindrome()
|
72,136,127 | 72,136,617 | std map access element while creating new one thread safety | If I have a map<int, Fruit> x. On one thread I try to read the data of one element x[10].type, while on another thread I create a new element Fruit &new_fruit = x[7]. Is this thread safe? Since from what I can understand as long as it is not the same key/element it should be fine.
| You're probably referring to iterator invalidation, when you say that from what you understand, it's safe as long as you're not reading/writing to the same key from different threads.
However, thread safety doesn't work like that. Unless it is explicitly guaranteed (or proven,) you must assume that this kind of access to a data structure is unsafe. And by "this kind of access" I mean non-synchronized non-const access to the data structure and its meta-data from more than one thread.
If you need convincing, just think about the balanced binary search tree (e.g. red-black or AVL tree) that is almost always used to implement a std::map. When you insert an element (as x[7] can do,) it will re-organize (or "rotate") other nodes, and also will update the calculated heights or number of children in the nodes.
Any non-trivial datastructure/container that doesn't give you guarantees about data races and thread safety must be considered as thread-unsafe and protected with external critical sections. Unless proven otherwise. Carefully.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.