FAQ Database Discussion Community


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

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

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

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

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

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

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

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

No matching function for call to std::transform, unresolved overloaded function type

c++,stl,compiler-errors,std
I have the following, correct and compiling code: #include <iostream> #include <map> #include <algorithm> template<typename K, typename V> void write_map(const std::multimap<K, V> mm) { std::cout << "MultiMap content:"<< std::endl << std::endl; for(auto it = mm.begin(); it != mm.end(); it++) std::cout << it->first << "\t" << it->second << std::endl; } template<typename...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

How to make function like operator