FAQ Database Discussion Community


Sort structs depending on non-static value (C++)

c++,sorting,std
I have an EnemyRhombus class. It is a unit, which can move to different points on the map. I want to process points, to which it can move, in order of increasing distance to them. To do it I want to sort the points. Code 1: class EnemyRhombus { public:...

Source code of std:: namespace

c++,std
I want to use the std::string namespace + member, but I do not want the size of my file to increase by the size of the #include <string> file. Is there anywhere that I can find the source code of the std:: namespace so I can just extract the string...

c++ argument of type x is incompatible with parameter of type with atexit

c++,std
I get this error when I try to run a function with theatexti() in std. I don't understand the error. Here is the error: IntelliSense: argument of type "void (Demo3Main::*)()" is incompatible with parameter of type "void (__cdecl *)()" and here is the code: Demo3Main::Demo3Main(void) : BaseEngine( 50 ) {...

How can I make the sign appear at the end of the fill when using std::cout and std::stringstream?

c++,std,cout,stringstream
I have the following code for formatting a printout to always be 4 digits with sign included: std::stringstream pitch; pitch.precision(0); pitch.width(4); pitch.fill('0'); pitch << std::showpos << (int)(m_values["Pitch_1"]); I would also like to show the sign ("+"/"-"), but I want it to precede the fill, as follows: +002 However, the code...

Compile errors when including std::mutex before jemalloc.h

c++,c++11,include,std,ratio
This //CSocket.h #ifndef __SERVER_CSOCKET_H__ #define __SERVER_CSOCKET_H__ #include "winsock2.h" #include "ws2tcpip.h" #include <thread> #include <stdio.h> #include <string> (cpp includes only the header) //CSocket.cpp #include "CSocket.h" produces the following error messages in c:\program files (x86)\microsoft visual studio 12.0\vc\include\ratio ratio(122): error C2065: 'INTMAX_MAX': undeclared identifier ratio(133): See reference to the instance of the...

Remove by iterator from std::vector

c++,vector,std
For removing an iterator from std::vector I can do these two things: std::vector<int>& vec = myNumbers; // use shorter name vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); Or I can do this: auto it = find(vec.begin(), vec.end(), number_in); vec.erase(it); The second is more intuitive, I guess, but which one is faster? EDIT: Elements...

Printing out the hex vale of an unsigned char array in C++

c++,string,hex,std,cout
I want to print out the hex value of an unsigned char array using the cout function. The most obvious approach would be something like the following. unsigned char str[] = "foo bar baz\n"; for(unsigned short int i = 0; i < sizeof(str); i++){ std::cout << std::hex << str[i] <<...

How efficient smart pointers are?

c++,pointers,c++11,std
I know, that std::shared_ptr uses reference counting, so it has copy&move semantics, on the other hand std::unique_ptr (hence the name unique) only has move semantics, so trying to copy it is a compile error. However, its not quite clear for me how big of a deal is that. Can I...

namespace std overloading less than

c++,c++11,tuples,std
I was curious about why this piece of code doesn't work: #include "stdafx.h" #include <iostream> #include <tuple> #include <string> #include <vector> #include <algorithm> typedef std::tuple<int, std::string> intString; bool operator<(intString& lhs, intString& rhs){ return std::tie(std::get<1>(lhs), std::get<0>(lhs)) < std::tie(std::get<1>(rhs), std::get<0>(rhs)); } void printIntStrings(std::vector<intString>& v){ for (intString& i : v){ std::cout <<...

C++ LNK2019 unresolved external symbol stdlib

c++,std,unresolved-external
I have a program that requires atol() in one of its functions. So I included stdlib.h but it doesn't seem to see it. EDIT: I'm aware to use it, I should include stdlib.h. I did that but I'm still getting this error. The function: void intstr( char *t ) {...

Stats properties among documents R

r,statistics,std,text-mining
I have a table, such as: test_data <- data.frame( doc = c(1,1,2,2,2,3,3), word = c("person", "grand", "person", "moment", "bout", "person", "moment"), frenq= c(9,8,5,4,3,5,3)) I would like to calculate mean and std for each "word" and create a new table such as. word freq (number of docs) mean std personn 19...

How to use std::regex to find the next match in a string?

c++,regex,c++11,std
Trying to use std::regex in a scanner. So all it is supposed to do in my case is to find the first match starting at const char *p of the input sequence. It is not supposed to skip anything. It just needs to match as long as the expression is...

Move element in array

c++,arrays,std,stdvector
I have a 2d array of vectors of pointers to Entities in a game. The array represents a grid of game world to improve performance when detecting collisions. When an entity moves I check if it moves over to another grid-tile (of course) but this is where everything goes to...

Is it allowed to write to a ofstream when it is not opened in c++

c++,std,ofstream
I have a code like this: # in class definition std::ofstream m_myFile; ## some where in code m_myFile.open(filename); and then in several places, I am writing to file as follow: m_myFile << "some data to file"<<std::endl; This is working well, now I need to add a flag to system that...

Where does nullptr_t reside?

c++,c++11,std,nullptr
A bit of prehistory. I've been writing a game engine for quite some time. It's divided into several static libraries, like "utils", "rsbin" (resource system), "window", which are then linked into a single executable. It is a crossplatform engine, being compiled for Windows and for Android. Under Windows, I compile...

How to print a type vector> to screen c++?

c++,vector,tuples,std
Let's say I have std::vector<std::tuple<string ,int ,int>> tupleVector; tupleVector.push_back(std::tuple<string ,int ,int>("Joe", 2, 3)); tupleVector.push_back(std::tuple<string ,int ,int>("Bob", 4, 5)); How can I iterate on the vector to print all values of this vector containing a tuple?...

erase-remove idiom: did I just delete something?

c++,std,stdvector
I am using the erase-remove idiom: template <typename T> bool garbageCollectVector(std::vector<T>& v) { // Use the erase-remove idiom in combination with a lambda expression v.erase( std::remove_if(v.begin(), v.end(), [this](const T& elem) -> bool { return this->shouldRemove(elem); } ), v.end()); return /* what to return? */; } and want to return whether...

Generate a series of increasing numbers by a constant floating point value

c++,c++11,std
I know iota function, but it will just work integer values since it is calling ++ operator. I want to generate increasing float numbers by lets say 0.5 like [0.5, 1, 1.5....], and insert them to my vector The final solution I came up with is : double last =...

Cannot include std::thread header in wxWidgets application

c++,multithreading,std,wxwidgets
I have the following code: #include "wx\wx.h" class BClient : public wxApp { virtual bool OnInit(); virtual int OnQuit(); }; IMPLEMENT_APP(BClient) bool BClient::OnInit() { return true; } int BClient::OnQuit() { return 0; } As soon I try to add the line #include <thread> I receive this errors: Error 10 error...

std::list c++ is sequential then how it can take constant time for insert and erase operations anywhere within the sequence

c++,std
in c++ reference i read "Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions." my doubt is if it is sequential then how it can take constant time to delete and insert a node.Any way we have to...

std::map Members refering all to one address

c++,std,stdmap
I am using std::map, similar to the implemtentation in webrtc (see here). My Map is defined like that: typedef std::map <std::string, BaseOption*> OptionMap; And the BaseOption (Option) is defined: class BaseOption { public: virtual ~BaseOption() {} }; template<typename T> class Option : public BaseOption { public: explicit Option(T* v) {value...

Python— Mean and Standard Deviation over groups of columns

python,numpy,std,mean
I am using Python and I have a black and white .FIT image file that is 2048 x 2048 pixels and each pixel has a single value. I need to find the standard deviation of the pixel values for the first 64 columns. By this i mean, i need to...

Removing an element from std::list of std::unique_pointer

c++,std,unique-ptr
According to this thread Returning a pointer to a vector element , it is recommended to use the following code when inserting an object into a vector and returning its pointer: // in your class std::vector<std::unique_ptr<SceneGraphNode>> m_children; SceneGraphNode* addChild(std::string name) { std::unique_ptr<SceneGraphNode> child(new SceneGraphNode(this,name)); myList.push_back(std::move(child)); return myList.back().get(); } I plan...

Is it safe to reuse a std container after std::move? [duplicate]

c++,c++11,std,move-semantics
This question already has an answer here: Reusing a moved container? 3 answers If I have a std::list, for example, and I use std::move() to move its information into a std::map, is it safe to reuse the list by populating it with more data so that I can add...

“cout << cout” - what does the output stand for?

c++,std
After a long day of coding i accidentaly wrote cout << "some text" << cout; instead of cout << "some text" << endl; Now it printed out a memory address. What does it point to ? ...

String to Char Array not working

c++,arrays,string,char,std
I noticed that if my string is empty, the char array does not become empty either. See the below code: std::copy(strUsername.begin(), strUsername.end(), sRecord.m_strUsername); sRecord.m_strUsername is a char[1064], but if it is already populated and i try doing a copy (or strcpy) with strUsername as empty, nothing happens, even though I...

Delete std::thread after calling join?

c++,multithreading,c++11,std,stdthread
I have some code that dynamically allocates a new std::thread from the C++11 <thread> header, like this: std::thread *th = new thread( /* my args */); Some time later, I call join: th->join(); Since I dynamically allocated the thread, do I also need to call delete th; to free the...

atof Function not working in program

c++,string,double,std
In my c++ program I am required to make a class called ComplexNumber that holds information for a complex number. I had written all the functions in the header file and moved the functions over to the .cpp file. The atof function for my current program is not working. It...

“Expression: list iterators incompatible” happening randomly during iteration through a list

c++,list,iterator,std
I have been trying to use std::list, however my work has been sabotaged by following error: Debug Assertion Failed! Program: C:\Windows\system32\MSVCP120D.dll File: c:\program files (x86)\microsoft visual studio 12.0\vc\include\list Line: 289 Expression: list iterators incompatible For information on how your program can cause an assertion failure, see the Visual C++ documentation...

How do I write an int to a stringstream?

c++,std
I have std::stringstream with 1 byte: std::stringstream message; message.write((const char[]) {0x55}, 1); std::string res(message.str()); How append int a = 1; (4 bytes)? I want to get as values stored in the message's underlying std::string: 0x55 0x00 0x00 0x00 0x01 And right tool I chose for the job with the sequence...

Basic Password Generator - How to get different rand(number) when is called

c++,random,std
The output now is HHHHHHHHHHHHHHHHHHHH. What I would like the program to do is randomNum to have a different value each time it goes through the loop. so it would be like AacCEe... And goes on. #include <stdio.h> #include <iostream> #include <cstdlib> #include <time.h> using namespace std; int main(){ srand(time(0));...

iterator over multiple std containers subsequently

c++,std,stdvector
I have the following class (which obviously does not yet work as intended): class A { private: std::vector<int> firstVector, secondVector; public: std::vector<int>::iterator begin(){ return firstVector.begin(); } std::vector<int>::iterator end(){ return secondVector.end(); } }; How can I define an iterator which will go over the two member containers subsequently, e.g. after firstVector.end()-1...

find element with max value from std::map [duplicate]

c++,std,stdmap
This question already has an answer here: C++ Help finding the max value in a map 6 answers I'm trying to get the element with max value from std::map, int main() { map<int, int> m; m[1] = 100; m[2] = -1; auto x = std::max_element(m.begin(), m.end(), m.value_comp()); cout <<...

What happens to an object instance after applying std::move

c++,std,move-semantics
I am trying to understand how std::move and rvalues work in C++ 11. I keep seeing the similar example in tutorials like this: Suppose we have this class : class Class { public: Class(Class &&b) { a = b.a; } int *a; } int main() { Class object1(5); Class object2(std::move(object1));...

Vectors disjunction

c++,vector,std
Which is the most elegant way to implement a logical disjunction between two std::vectors in c++? as example: vector a = {0,1,2,3,4,5,6,7,8,9}; vector b = {0,1,2,3,4}; vector c = a-b; print c = {5,6,7,8,9} ...

How to create iterator without type names?

c++,templates,iterator,std,c++03
For example I have a std::map<int, string> _m; and I want to iterate through it. So I have to write something like this: std::map<int, string>::iterator it = _m.begin(). The question is whether it is possible to create that iterator without using type names. Compiler knows the type of _m at...

c++ error: Function 'get_time' could not be resolved - Ubuntu g++

c++,ubuntu,std
I have the following piece of C++ code on my class, to convert a ISO 8601 string to a time_t structure: #include <iostream> #include <sstream> #include <string> #include <iomanip> #include <ctime> .... class code... struct tm tempTime; std::stringstream ss(data); ss >> std::get_time(&tempTime, "%FT%TZ"); std::time_t time = mktime(&tempTime); .... class code......

'array' in namespace 'std' does not name a template type

c++,arrays,c++11,std
I receive the following error: 'array' in namespace 'std' does not name a template type. I changed my compiler to g++ 4.9. Still having issues. I think that I may have an old version of the std library but am not sure on how to proceed to fix that. #ifndef...

std::move to a function

c++,std,move
I have this example code: #include <iostream> class Struct { public: Struct() { std::cout << "0" << std::endl; } Struct(Struct&) { std::cout <<"1"<<std::endl;} Struct(const Struct&) { std::cout << "2" << std::endl; } }; class Struct2 { public: Struct s; Struct2() {} void setMember(const Struct& aux) { s = aux; }...

'for each' is not a member of std. C++11 support already enabled

c++,c++11,netbeans,std,codeblocks
The code from my professor's homework assignment is as follows. This is straight out of the box, I have not modified my professor's code. There is more to the program, but this is where the error happens. Problem line in bold. std::cout << "\nAll remaining courses with enrollments:\n"; allCourses =...

specific gnuplot by data grouping

data,gnuplot,std,mean
I'm new in gnuplot and sorry that my problem formulation might be unprecise, but I don't know how to find the tools/commnds needed to solve my problem. The code for plotting I would like to integrate in my bash file. I have a data set like: 285 1 50 7.35092...

Why does unique_ptr::~unique_ptr need the definition of T?

c++,c++11,std,smart-pointers
If I have a class 'Bar': // bar.h class Bar { public: Bar() { } }; that I forward declare to use with an std::unique_ptr in another class 'Foo': // foo.h #include <memory> class Bar; class Foo { public: Foo(); private: std::unique_ptr<Bar> bar_; }; and whose definition I include in...

E2316 'any_of' is not a member of 'std'

c++,std,c++builder,stl-algorithm,c++builder-6
So I'm trying to use std::any_of() function, but C++ Builder 6 says that there is an error: [C++ Error] Unit1.cpp(93): E2316 'any_of' is not a member of 'std' But I have #include <algorithm> in my Unit1.h #ifndef Unit1H #define Unit1H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include...

finding a memory allocation error with omnet++

c++,gdb,std,valgrind,omnet++
I am doing networks simulations under omnet++ & veins(v2.0-rc1), for this purpose I experiment 4 scenarios with 20 repetitions for both one. I am getting some errors (i guess that is a memory allocation error) during the simulations of the 3rd & 4th scenarios wich share a common functionnality (ack)....

std::ofstream open file and replace in specific offset

c++,std,fstream,ofstream
I want to open a file (without re-creating it) and write to a specific offset. This is the current code : std::ofstream file(conf_file_path, std::ios::app); file.seekp(offset, std::ios::beg); const auto& output = file.write(conf_str, conf_str_len); But it always writes to the end of file (probably due to the app flag) If I don't...

C++ STL priority queue getting bad_alloc

c++11,std,priority-queue
I'm trying to use a STL priority queue, defined as: template <typename T> using min_queue = std::priority_queue<T, std::vector<T>, std::greater<T>>; When running the following code: Label kNN(int k, const Matrix &trainingSet, const std::vector<Label> &trainingLabels, Matrix &evSet, int i1, const DistanceF &f) { Timer timer("kNN Timer"); min_queue<std::pair<double, Label>> distances; for (int i...

Why is the common type of bool and int8_t an int32_t in C++?

c++,c++11,boolean,std
I'm curious about some of the behavior of the builtin bool type in C++. As I understand it, std::common_type determines the common type using implicit convertibility. I would expect that an expression with bool and another type would cause bool to convert to that type. For instance, I can see...

std::vector that holds class methods

c++,vector,enums,std,std-function
I have done this to enumerate my class members enum MemberType {A, B, C, D}; class Hello { public: std::vector<std::function<void(Hello*, void)>> m_members; void func() { }; Hello() { m_members[A] = func(); } }; What is wrong here?...

make_heap vs priority_queue efficiency when needed once per frame

c++,sorting,std
I tried to find information about this particular use, but I could not. In a simulation software (that acts like a video game), I'm building an event manager that prioritize the events based on a value submitted by the event creator. The event queue will be parsed once per frame...

Split or trim string into one line

c++,string,std
I have a String which looks like this : string str = "1. Hallo \n2.Hello\n3.Bonjour\n4.Merhaba\n"; in the end I want to have sth like that: string str_line_3 = "3.Bonjour\n"; Im searching here for easy methods. To find the '\n' in a loop is to ugly imo ! Ideas ? edit:...

Add same value multiple times to std::vector (repeat)

c++,vector,std
I want to add a value multiple times to an std::vector. E.g. add the interger value 1 five times to the vector: std::vector<int> vec; vec.add(1, 5); vec should be of the form {1,1,1,1,1} afterwards. Is there a clean c++ way to do so?...

Rust “use” vs. C++ “using namespace”

namespaces,std,rust
Is it considered bad style to declare multiple "use" statements in Rust? I am a C++ programmer that recently began trying out Rust. One thing I've noticed as I review Rust code is that in many Rust programs there will be a bunch of use statements at the top of...

Using rand() to get a number but that number can't be the number that was last generated

c++,random,std
I want to use std::rand() to generate a number between 0 and amountOfNumbers, but the generated number can't be the same number that was last generated. I wrote this function: void reroll() { int newRand; while (true) { newRand = std::rand() % (amountOfNumbers); if (newRand == lastNumber) { continue; }...

Can't verify the conversion from time_point to tm and tm back to time_point

c++,std,chrono,ctime
I created a current time_point and converted it to structure tm and printed it's values. Now converted this tm structure to time_point. On comparing the first and second time_points, it is telling that they're different. But the values of structure are exactly same. Can someone spot, where I'm doing wrong?...

How to make function like operator