FAQ Database Discussion Community


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...

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...

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...

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...

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...

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?...

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] <<...

“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 ? ...

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...

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...

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 <<...

Allocating std vector content with dynamic objects

c++,malloc,std,stdvector
I have a std::vector< MyObject* > my_vector; Which is not empty and i want to allocate and push a certain amount of MyObject* in it. I know the number of objects to push. Is there a better way (optimized/faster) to do it than: int object_count = 10000; for(int index =...

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...

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......

need help to search element from vector of struct

c++,function,c++11,std
I have vector of struct partationPartItemTag_t type typedef struct partationPartItemTag { std::string partition; std::string partGroupId; std::string mathTuid; std::string partNumber; tag_t itemTag; }partationPartItemTag_t; I want to find element from vector having value for partition == 'a' and partGroupId == 'b' I have written following code and its working fine with C++11...

std::hash specialization remains unused by std::unordered_map

c++,templates,c++11,std,unordered-map
I am trying to extend std::hash<T> by supplying a specialization for const char, so that I can use const char* as key type in std::unordered_map. This is what I tried: #include <unordered_map> #include <functional> #include <stdio.h> #include <string.h> #include <ctype.h> namespace std { template<> struct hash<const char*> { size_t operator()(const...

std::get for own class with tuple as member

c++,templates,std
I have a class like this: template<typename ... TTypes> class Composite { public: std::tuple<TTypes...> &getRefValues() { return values; } private: std::tuple<TTypes...> values; }; Can I define std::get for my class Composite? It should basically call the already defined std::get for the private tuple values. I was able to implement a...

“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...

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...

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...

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...

c++ std::async literally async with respect to thread assignment of tasks

c++,multithreading,asynchronous,std
I've successfully used std::async in the past, but lately in checking the fidelity of some new code, I've run into an oddity that has me stumped. I'm sure there should be a simple explanation and a proper solution, but I can't find a discussion of it anywhere. The following bit...

How to use opencv::split(). Get crash

c++,opencv,std
How to use split() correctly? Why I get crash after doing splitting image to std::vector of channels? cv::Mat imgOrig = cv::imread("cat.png", CV_LOAD_IMAGE_COLOR); { std::vector<cv::Mat> Ichannels; cv::split(ImgOrig, Ichannels); // have 3 channels here } // crash here. When going out of scope UPDATE: std::vector Ichannels(3) fixes problem. According to this answer...

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 =...

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 <<...

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...

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...

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?...

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...

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...

'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::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?...

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));...

To check objects inside std::array has identical member data

c++,std,equality
Cards.h class Card { public: // Card suits struct Suit { // Suits in order enum Enum { Clubs, Diamonds, Hearts, Spades, }; }; // Card rank struct Rank { // Ranks with aces low enum Enum { Ace, Two, King, .... ... }; }; // constructors //get & set...

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?...

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; }...

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));...

C++: std::equal segmentation fault with my container

c++,std,c++14
I'm implementing a container like std::vector, with the aim of learning C++ and its idioms. With the purpose of overloading the operator ==, i first wrote my own version: bool operator==(const Vector& other) const{ if (_size == other._size) { for (int i = 0; i < _size; i++) if (!(_elements[i]...

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...

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...

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 ) {...

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...

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:...

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...

How to make function like operator