Search Results

Search found 2886 results on 116 pages for 'std'.

Page 3/116 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • issue with std::advance on std::sets

    - by tim
    I've stumbled upon what I believe is a bug in the stl algorithm advance. When I'm advancing the iterator off of the end of the container, I get inconsistent results. Sometimes I get container.end(), sometimes I get the last element. I've illustrated this with the following code: #include <algorithm> #include <cstdio> #include <set> using namespace std; typedef set<int> tMap; int main(int argc, char** argv) { tMap::iterator i; tMap the_map; for (int i=0; i<10; i++) the_map.insert(i); #if EXPERIMENT==1 i = the_map.begin(); #elif EXPERIMENT==2 i = the_map.find(4); #elif EXPERIMENT==3 i = the_map.find(5); #elif EXPERIMENT==4 i = the_map.find(6); #elif EXPERIMENT==5 i = the_map.find(9); #elif EXPERIMENT==6 i = the_map.find(2000); #else i = the_map.end(); #endif advance(i, 100); if (i == the_map.end()) printf("the end\n"); else printf("wuh? %d\n", *i); return 0; } Which I get the following unexpected (according to me) behavior in experiment 3 and 5 where I get the last element instead of the_map.end(). [tim@saturn advance]$ uname -srvmpio Linux 2.6.18-1.2798.fc6 #1 SMP Mon Oct 16 14:37:32 EDT 2006 i686 athlon i386 GNU/Linux [tim@saturn advance]$ g++ --version g++ (GCC) 4.1.1 20061011 (Red Hat 4.1.1-30) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [tim@saturn advance]$ g++ -DEXPERIMENT=1 advance.cc [tim@saturn advance]$ ./a.out the end [tim@saturn advance]$ g++ -DEXPERIMENT=2 advance.cc [tim@saturn advance]$ ./a.out the end [tim@saturn advance]$ g++ -DEXPERIMENT=3 advance.cc [tim@saturn advance]$ ./a.out wuh? 9 [tim@saturn advance]$ g++ -DEXPERIMENT=4 advance.cc [tim@saturn advance]$ ./a.out the end [tim@saturn advance]$ g++ -DEXPERIMENT=5 advance.cc [tim@saturn advance]$ ./a.out wuh? 9 [tim@saturn advance]$ g++ -DEXPERIMENT=6 advance.cc [tim@saturn advance]$ ./a.out the end [tim@saturn advance]$ g++ -DEXPERIMENT=7 advance.cc [tim@saturn advance]$ ./a.out the end [tim@saturn advance]$ From the sgi website (see link at top), it has the following example: list<int> L; L.push_back(0); L.push_back(1); list<int>::iterator i = L.begin(); advance(i, 2); assert(i == L.end()); I would think that the assertion should apply to other container types, no? What am I missing? Thanks!

    Read the article

  • Why is std::tr1::shared_ptr<>.reset() so expensive?

    - by Paul Oyster
    Profiling some code that heavily uses shared_ptrs, I discovered that reset() was surprisingly expensive. For example: struct Test { int i; Test() { this->i = 0; } Test(int i) { this->i = i; } } ; ... auto t = make_shared<Test>(1); ... t.reset(somePointerToATestObject); Tracing the reset() in the last line (under VC++ 2010), I discovered that it creates a new reference-counting object. Is there a cheaper way, that reuses the existing ref-count and does not bother the heap?

    Read the article

  • operator<< cannot output std::endl -- Fix?

    - by dehmann
    The following code gives an error when it's supposed to output just std::endl: #include <iostream> #include <sstream> struct MyStream { std::ostream* out_; MyStream(std::ostream* out) : out_(out) {} std::ostream& operator<<(const std::string& s) { (*out_) << s; return *out_; } }; template<class OutputStream> struct Foo { OutputStream* out_; Foo(OutputStream* out) : out_(out) {} void test() { (*out_) << "OK" << std::endl; (*out_) << std::endl; // ERROR } }; int main(int argc, char** argv){ MyStream out(&std::cout); Foo<MyStream> foo(&out); foo.test(); return EXIT_SUCCESS; } The error is: stream1.cpp:19: error: no match for 'operator<<' in '*((Foo<MyStream>*)this)->Foo<MyStream>::out_ << std::endl' stream1.cpp:7: note: candidates are: std::ostream& MyStream::operator<<(const std::string&) So it can output a string (see line above the error), but not just the std::endl, presumably because std::endl is not a string, but the operator<< definition asks for a string. Templating the operator<< didn't help: template<class T> std::ostream& operator<<(const T& s) { ... } How can I make the code work? Thanks!

    Read the article

  • Insert an element to std::set using constructor

    - by Dave17
    is it possible to insert a new element to std::set like in case of std::list for example: //insert one element named "string" to sublist of mylist std::list< std::list<string> > mylist; mylist.push_back(std::list<string>(1, "string")); Now, mylist has one element of type std::string in its sub-list of type std::list. How can you do the same in if std::set is the sub-set of std::list my list i.e std::list<std::set <string>> mylist; if you can't then why not?

    Read the article

  • Confused about std::runtime_error vs. std::logic_error

    - by David Gladfelter
    I recently saw that the boost program_options library throws a logic_error if the command-line input was un-parsable. That challenged my assumptions about logic_error vs. runtime_error. I assumed that logic errors (logic_error and its derived classes) were problems that resulted from internal failures to adhere to program invariants, often in the form of illegal arguments to internal API's. In that sense they are largely equivalent to ASSERT's, but meant to be used in released code (unlike ASSERT's which are not usually compiled into released code.) They are useful in situations where it is infeasible to integrate separate software components in debug/test builds or the consequences of a failure are such that it is important to give runtime feedback about the invalid invariant condition to the user. Similarly, I thought that runtime_errors resulted exclusively from runtime conditions outside of the control of the programmer: I/O errors, invalid user input, etc. However, program_options is obviously heavily (primarily?) used as a means of parsing end-user input, so under my mental model it certainly should throw a runtime_error in the case of bad input. Where am I going wrong? Do you agree with the boost model of exception typing?

    Read the article

  • Why is 'using namespace std;' considered a bad practice in C++?

    - by Mana
    Okay, sorry for the simplistic question, but this has been bugging me ever since I finished high school C++ last year. I've been told by others on numerous occasions that my teacher was wrong in saying that we should have "using namespace std;" in our programs, and that std::cout and std::cin are more proper. However, they would always be vague as to why this is a bad practice. So, I'm asking now: Why is "using namespace std;" considered bad? Is it really that inefficient, or risk declaring ambiguous vars(variables that share the same name as a function in std namespace) that much? Or does this impact program performance noticeably as you get into writing larger applications? I'm sorry if this is something I should have googled to solve; I figured it would be nice to have this question on here regardless in case anyone else was wondering.

    Read the article

  • C++ find multiple keys from a std::multimap

    - by sch0ck9
    I have a STL::multimap and I search to populate a std::list with value which key is duplicated. Can I find/insert to a std::list the value of elements for all key where count 1 without counting them one by one? std::multimap<int, std::string> mm ; mm[0] = "a" ; mm[1] = "b" ; mm[0] = "c" ; mm[2] = "j" ; mm[2] = "k" ; std::list<std::string> lst ; lst might contains "a" ,"c","j","k" ; I try this template <class K, class V> class extract_value { private: K last_key_ ; std::list<V> m_list_value ; std::pair<K, V> first_elem ; public: extract_value(const K& k_): last_key_(k_) { } void operator() (std::pair<const K, V> elem) { if (last_key_ == elem.first) { m_list_value.push_back(elem.second) ; } else { // First entry last_key_ = elem.first; first_elem= elem ; } } std::list<V> get_value() { return m_list_value ; } }; ex_ = for_each(mm.begin(),mm.end(), extract_value<int, std::string>(0)) ; std::list<std::string> lst = ex_.get_value() ; I'm not sure that this code compile.

    Read the article

  • Makefile : Build in a separate directory tree

    - by Simone Margaritelli
    My project (an interpreted language) has a standard library composed by multiple files, each of them will be built into an .so dynamic library that the interpreter will load upon user request (with an import directive). Each source file is located into a subdirectory representing its "namespace", for instance : The build process has to create a "build" directory, then when each file is compiling has to create its namespace directory inside the "build" one, for instance, when compiling std/io/network/tcp.cc he run an mkdir command with mkdir -p build/std/io/network The Makefile snippet is : STDSRC=stdlib/std/hashing/md5.cc \ stdlib/std/hashing/crc32.cc \ stdlib/std/hashing/sha1.cc \ stdlib/std/hashing/sha2.cc \ stdlib/std/io/network/http.cc \ stdlib/std/io/network/tcp.cc \ stdlib/std/io/network/smtp.cc \ stdlib/std/io/file.cc \ stdlib/std/io/console.cc \ stdlib/std/io/xml.cc \ stdlib/std/type/reflection.cc \ stdlib/std/type/string.cc \ stdlib/std/type/matrix.cc \ stdlib/std/type/array.cc \ stdlib/std/type/map.cc \ stdlib/std/type/type.cc \ stdlib/std/type/binary.cc \ stdlib/std/encoding.cc \ stdlib/std/os/dll.cc \ stdlib/std/os/time.cc \ stdlib/std/os/threads.cc \ stdlib/std/os/process.cc \ stdlib/std/pcre.cc \ stdlib/std/math.cc STDOBJ=$(STDSRC:.cc=.so) all: stdlib stdlib: $(STDOBJ) .cc.so: mkdir -p `dirname $< | sed -e 's/stdlib/stdlib\/build/'` $(CXX) $< -o `dirname $< | sed -e 's/stdlib/stdlib\/build/'`/`basename $< .cc`.so $(CFLAGS) $(LDFLAGS) I have two questions : 1 - The problem is that the make command, i really don't know why, doesn't check if a file was modified and launch the build process on ALL the files no matter what, so if i need to build only one file, i have to build them all or use the command : make path/to/single/file.so Is there any way to solve this? 2 - Any way to do this in a "cleaner" way without have to distribute all the build directories with sources? Thanks

    Read the article

  • std::thread and class constructor and destructor

    - by toeplitz
    When testing threads in C++11 I have created the following example: #include <iostream> #include <thread> class Foo { public: Foo(void) { std::cout << "Constructor called: " << this << std::endl; } ~Foo(void) { std::cout << "Destructor called: " << this << std::endl; } void operator()() const { std::cout << "Operatior called: " << this << std::endl; } }; void test_normal(void) { std::cout << "====> Standard example:" << std::endl; Foo f; } void test_thread(void) { std::cout << "====> Thread example:" << std::endl; Foo f; std::thread t(f); t.detach(); } int main(int argc, char **argv) { test_normal(); test_thread(); for(;;); } Which prints the following: Why is the destructor called 6 times for the thread? And why does the thread report different memory locations?

    Read the article

  • right usage of std::uncaught_exception in a destructor

    - by Vokuhila-Oliba
    There are some articles concluding "never throw an exception from a destructor", and "std::uncaught_exception() is not useful", for example: http://www.gotw.ca/gotw/047.htm (written by Herb Sutter) But it seems that I am not getting the point. So I wrote a small testing example (see below). Since everything is fine with the testing example I would very appreciate some comments regarding what might be wrong with it. testing results: ./main Foo::~Foo(): caught exception - but have pending exception - ignoring int main(int, char**): caught exception: from int Foo::bar(int) ./main 1 Foo::~Foo(): caught exception - but *no* exception is pending - rethrowing int main(int, char**): caught exception: from Foo::~Foo() // file main.cpp // build with e.g. "make main" // tested successfully on Ubuntu-Karmic with g++ v4.4.1 #include <iostream> class Foo { public: int bar(int i) { if (0 == i) throw(std::string("from ") + __PRETTY_FUNCTION__); else return i+1; } ~Foo() { bool exc_pending=std::uncaught_exception(); try { bar(0); } catch (const std::string &e) { // ensure that no new exception has been created in the meantime if (std::uncaught_exception()) exc_pending = true; if (exc_pending) { std::cerr << __PRETTY_FUNCTION__ << ": caught exception - but have pending exception - ignoring" << std::endl; } else { std::cerr << __PRETTY_FUNCTION__ << ": caught exception - but *no* exception is pending - rethrowing" << std::endl; throw(std::string("from ") + __PRETTY_FUNCTION__); } } } }; int main(int argc, char** argv) { try { Foo f; // will throw an exception in Foo::bar() if no arguments given. Otherwise // an exception from Foo::~Foo() is thrown. f.bar(argc-1); } catch (const std::string &e) { std::cerr << __PRETTY_FUNCTION__ << ": caught exception: " << e << std::endl; } return 0; }

    Read the article

  • conflicting declaration when filling a static std::map class member variable

    - by Max
    I have a class with a static std::map member variable that maps chars to a custom type Terrain. I'm attempting to fill this map in the class's implementation file, but I get several errors. Here's my header file: #ifndef LEVEL_HPP #define LEVEL_HPP #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "libtcod.hpp" namespace yarl { namespace level { class Terrain { // Member Variables private: std::bitset<5> flags; // Member Functions public: explicit Terrain(const std::string& flg) : flags(flg) {} (...) }; class Level { private: static std::map<char, Terrain> terrainTypes; (...) }; } } #endif and here's my implementation file: #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "Level.hpp" #include "libtcod.hpp" using namespace std; namespace yarl { namespace level { /* fill Level::terrainTypes */ map<char,Terrain> Level::terrainTypes['.'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[','] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['\''] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['`'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[178] = Terrain("11111"); // wall (...) } } I'm using g++, and the errors I get are src/Level.cpp:15: error: conflicting declaration ‘std::map, std::allocator yarl::level::Level::terrainTypes [46]’ src/Level.hpp:104: error: ‘yarl::level::Level::terrainTypes’ has a previous declaration as ‘std::map, std::allocator yarl::level::Level::terrainTypes’ src/Level.cpp:15: error: declaration of ‘std::map, std::allocator yarl::level::Level::terrainTypes’ outside of class is not definition src/Level.cpp:15: error: conversion from ‘yarl::level::Terrain’ to non-scalar type ‘std::map, std::allocator ’ requested src/Level.cpp:15: error: ‘yarl::level::Level::terrainTypes’ cannot be initialized by a non-constant expression when being declared I get a set of these for each map assignment line in the implementation file. Anyone see what I'm doing wrong? Thanks for your help.

    Read the article

  • std::basic_string full specialization (g++ conflict)

    - by SoapBox
    I am trying to define a full specialization of std::basic_string< char, char_traits<char>, allocator<char> > which is typedef'd (in g++) by the <string> header. The problem is, if I include <string> first, g++ sees the typedef as an instantiation of basic_string and gives me errors. If I do my specialization first then I have no issues. I should be able to define my specialization after <string> is included. What do I have to do to be able to do that? My Code: #include <bits/localefwd.h> //#include <string> // <- uncommenting this line causes compilation to fail namespace std { template<> class basic_string< char, char_traits<char>, allocator<char> > { public: int blah() { return 42; } size_t size() { return 0; } const char *c_str() { return ""; } void reserve(int) {} void clear() {} }; } #include <string> #include <iostream> int main() { std::cout << std::string().blah() << std::endl; } The above code works fine. But, if I uncomment the first #include <string> line, I get the following compiler errors: blah.cpp:7: error: specialization of ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ after instantiation blah.cpp:7: error: redefinition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ /usr/include/c++/4.4/bits/stringfwd.h:52: error: previous definition of ‘class std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ blah.cpp: In function ‘int main()’: blah.cpp:22: error: ‘class std::string’ has no member named ‘blah’ Line 52 of /usr/include/c++/4.4/bits/stringfwd.h: template<typename _CharT, typename _Traits = char_traits<_CharT>, typename _Alloc = allocator<_CharT> > class basic_string; As far as I know this is just a forward delcaration of the template, NOT an instantiation as g++ claims. Line 56 of /usr/include/c++/4.4/bits/stringfwd.h: typedef basic_string<char> string; As far as I know this is just a typedef, NOT an instantiation either. So why are these lines conflicting with my code? What can I do to fix this other than ensuring that my code is always included before <string>?

    Read the article

  • Vector of vectors of T in template<T> class

    - by topright
    Why this code does not compile (Cygwin)? #include <vector> template <class Ttile> class Tilemap { typedef std::vector< Ttile > TtileRow; typedef std::vector< TtileRow > TtileMap; typedef TtileMap::iterator TtileMapIterator; // error here }; error: type std::vector<std::vector<Ttile, std::allocator<_CharT> >, std::allocator<std::vector<Ttile, std::allocator<_CharT> > > >' is not derived from typeTilemap'

    Read the article

  • Error while linking libvorbisfile.dylib into Mac application

    - by computergeek6
    I'm working on a program that loads sounds from Ogg Vorbis files, but whatever I do, the XCode project just doesn't seem to want to link libvorbisfile.a into my program. I keep getting linking errors: "_ov_read", referenced from: GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o "_ov_clear", referenced from: GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o "_ov_info", referenced from: GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o "_ov_open", referenced from: GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o GSound::GSound(GWorld*, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in GSound.o ld: symbol(s) not found

    Read the article

  • How to bind std::map to Lua with LuaBind

    - by MahanGM
    Is this possible in lua to achieve? player.scripts["movement"].properties["stat"] = "stand" print (player.scripts["movement"].properties["stat"]) I've done getter method in c++ with this approach: luabind::object FakeScript::getProp() { luabind::object obj = luabind::newtable(L); for(auto i = this->properties.begin(); i != this->properties.end(); i++) { obj[i->first] = i->second; } return obj; } But I'm stuck with setter. The first line in lua code which I'm trying to set value "stand" for key "stat" is not going to work and it keep redirecting me to the getter method. Setter method only works when I drop ["stat"] from properties. I can do something like this for setter in my script: player.scripts["movement"].properties = {stat = "stand"} But this isn't what I want because I have to go through my real keys in c++ to determine which key is placed in setter argument table value. This is my map in class: std::map<std::string, std::string> properties;

    Read the article

  • How to std::find using a Compare object?

    - by dehmann
    I am confused about the interface of std::find. Why doesn't it take a Compare object that tells it how to compare two objects? If I could pass a Compare object I could make the following code work, where I would like to compare by value, instead of just comparing the pointer values directly: typedef std::vector<std::string*> Vec; Vec vec; std::string* s1 = new std::string("foo"); std::string* s2 = new std::string("foo"); vec.push_back(s1); Vec::const_iterator found = std::find(vec.begin(), vec.end(), s2); // not found, obviously, because I can't tell it to compare by value delete s1; delete s2; Is the following the recommended way to do it? template<class T> struct MyEqualsByVal { const T& x_; MyEqualsByVal(const T& x) : x_(x) {} bool operator()(const T& y) const { return *x_ == *y; } }; // ... vec.push_back(s1); Vec::const_iterator found = std::find_if(vec.begin(), vec.end(), MyEqualsByVal<std::string*>(s2)); // OK, will find "foo"

    Read the article

  • Exporting classes containing std:: objects (vector, map, etc) from a dll

    - by RnR
    I'm trying to export classes from a DLL that contain objects such as std::vectors and std::stings - the whole class is declared as dll export through: class DLL_EXPORT FontManager { The problem is that for members of the complex types I get this warning: warning C4251: 'FontManager::m__fonts' : class 'std::map<_Kty,_Ty' needs to have dll-interface to be used by clients of class 'FontManager' with [ _Kty=std::string, _Ty=tFontInfoRef ] I'm able to remove some of the warnings by putting the following forward class declaration before them even though I'm not changing the type of the member variables themselves: template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>; template class DLL_EXPORT std::vector<tCharGlyphProviderRef,std::allocator<tCharGlyphProviderRef> >; std::vector<tCharGlyphProviderRef> m_glyphProviders; Looks like the forward declaration "injects" the DLL_EXPORT for when the member is compiled but is it safe? Does it realy change anything when the client compiles this header and uses the std container on his side? Will it make all future uses of such a container DLL_EXPORT (and possibly not inline?)? And does it really solve the problem that the warning tries to warn about? Is this warning anything I should be worried about or would it be best to disable it in the scope of these constructs? The clients and the dll will always be built using the same set of libraries and compilers and those are header only classes... I'm using Visual Studio 2003 with the standard STD library. ---- Update ---- I'd like to target you more though as I see the answers are general and here we're talking about std containers and types (such as std::string) - maybe the question really is: Can we disable the warning for standard containers and types available to both the client and the dll through the same library headers and treat them just as we'd treat an int or any other built-in type? (It does seem to work correctly on my side.) If so would should be the conditions under which we can do this? Or should maybe using such containers be prohibited or at least ultra care taken to make sure no assignment operators, copy constructors etc will get inlined into the dll client? In general I'd like to know if you feel designing a dll interface having such objects (and for example using them to return stuff to the client as return value types) is a good idea or not and why - I'd like to have a "high level" interface to this functionality... maybe the best solution is what Neil Butterworth suggested - creating a static library?

    Read the article

  • C++'s std::string pools, debug builds? std::string and valgrind problems

    - by Den.Jekk
    Hello, I have a problem with many valgrind warnings about possible memory leaks in std::string, like this one: 120 bytes in 4 blocks are possibly lost in loss record 4,192 of 4,687 at 0x4A06819: operator new(unsigned long) (vg_replace_malloc.c:230) by 0x383B89B8B0: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.8) by 0x383B89C3B4: (within /usr/lib64/libstdc++.so.6.0.8) by 0x383B89C4A9: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, unsigned long, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.8) I'm wondering: does std::string (GCC 4.1.2) use any memory pools? if so, is there any way to disable the pools (in form of a debug build etc.)? Regards, Den

    Read the article

  • Why is this std::bind not converted to std::function?

    - by dauphic
    Why is the nested std::bind in the below code not implicitly converted to an std::function<void()> by any of the major compilers (VS2010/2012, gcc, clang)? Is this standard behavior, or a bug? #include <functional> void bar(int, std::function<void()>) { } void foo() { } int main() { std::function<void(int, std::function<void()>)> func; func = std::bind(bar, 5, std::bind(foo)); std::cin.get(); return 0; }

    Read the article

  • How to convert c++ std::list element to multimap iterator

    - by user63898
    Hello all, I have std::list<multimap<std::string,std::string>::iterator> > Now i have new element: multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test") I want to avoid the need to set temp multimap and do insert to the new element just to get its iterator back so i could to push it back to the: std::list<multimap<std::string,std::string>::iterator> > can i somehow avoid this creation of the temp multimap. Thanks

    Read the article

  • Class templating std::set key types

    - by TomFLuff
    I have a class to evaluate set algebra but wish to template it. At the minute it looks a bit like this set.h: template<typename T> class SetEvaluation { public: SetEvaluation<T>(); std::set<T> evaluate(std::string in_expression); } set.cpp template<typename T> std::set<T> SetEvaluation<T>::evaluate(std::string expression) { std::set<T> result; etc etc... } But i'm getting undefined reference errors when compiling. Is it possible to declare the return type as std::set<T> and then pass std::string as the class template param. There are no errors in the class but only when I try to instantiate SetEvaluation<std::string> Can anyone shed light on this problem? thanks

    Read the article

  • Read whole ASCII file into C++ std::string

    - by Arrieta
    Hello, I need to read a whole file into memory and place it in a C++ std::string. If I were to read it into a char, the answer would be very simple: std::ifstream t; int lenght; t.open("file.txt", "r"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the lenght) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... do stuff with buffer here ... Now, I want to do the exact same thing, but using a std::string instead of a char. I want to avoid loops, i. e., I don't want to: std::ifstream t; t.open("file.txt", "r"); std::string buffer; std::string line; while(t){ std::getline(t, line); // ... append line to buffer and go on } t.close() any ideas?

    Read the article

  • When to use typedef?

    - by futlib
    I'm a bit confused about if and when I should use typedef in C++. I feel it's a balancing act between readability and clarity. Here's a code sample without any typedefs: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { static std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int> lookup_table; std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int>::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } Pretty ugly IMO. So I'll add some typedefs within the function to make it look nicer: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { typedef std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } The code is still a bit clumsy, but I get rid of most nightmare material. But there's still the int vector iterators, this variant gets rid of those: typedef std::vector<int>::const_iterator Input_iterator; int sum(Input_iterator first, Input_iterator last) { typedef std::tuple<Input_iterator, Input_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } This looks clean, but is it still readable? When should I use a typedef? As soon as I have a nightmare type? As soon as it occurs more than once? Where should I put them? Should I use them in function signatures or keep them to the implementation?

    Read the article

  • Convert C++Builder AnsiString to std::string via boost::lexical_cast

    - by David Klein
    For a school assignment I have to implement a project in C++ using Borland C++ Builder. As the VCL uses AnsiString for all GUI Components I have to convert all of my std::strings to AnsiString for the sake of displaying. std::string inp = "Hello world!"; AnsiString outp(inp.c_str()); works of course but is a bit tedious to write and code duplication I want to avoid. As we use Boost in other contexts I decided to provide some helper functions go get boost::lexical_cast to work with AnsiString. Here is my implementation so far: std::istream& operator>>(std::istream& istr, AnsiString& str) { istr.exceptions(std::ios::badbit | std::ios::failbit | std::ios::eofbit); std::string s; std::getline(istr,s); str = AnsiString(s.c_str()); return istr; } In the beginning I got Access Violation after Access Violation but since I added the .exceptions() stuff the picture gets clearer. When the conversion is performed I get the following Exception: ios_base::eofbit set [Runtime Error/std::ios_base::failure] Does anyone have an idea how to fix it and can explain why the error occurs? My C++ experience is very limited. The conversion routine the other way round would be: std::ostream& operator<<(std::ostream& ostr,const AnsiString& str) { ostr << (str.c_str()); return ostr; } Maybe someone will spot an error here too :) With best regards! Edit: At the moment I'm using the edited version of Jem, it works in the beginning. After a while of using the programm the Borland Codeguard mentions some pointer arithmetic in already freed regions. Any ideas how this could be related? The Codeguard log (I'm using the german version, translations marked with stars): ------------------------------------------ Fehler 00080. 0x104230 (r) (Thread 0x07A4): Zeigerarithmetik in freigegebenem Speicher: 0x0241A238-0x0241A258. **(pointer arithmetic in freed region)** | d:\program files\borland\bds\4.0\include\dinkumware\sstream Zeile 126: | { // not first growth, adjust pointers | _Seekhigh = _Seekhigh - _Mysb::eback() + _Ptr; |> _Mysb::setp(_Mysb::pbase() - _Mysb::eback() + _Ptr, | _Mysb::pptr() - _Mysb::eback() + _Ptr, _Ptr + _Newsize); | if (_Mystate & _Noread) Aufrufhierarchie: **(stack-trace)** 0x00411731(=FOSChampion.exe:0x01:010731) d:\program files\borland\bds\4.0\include\dinkumware\sstream#126 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 0x00405759(=FOSChampion.exe:0x01:004759) D:\Projekte\Schule\foschamp\src\Server\Ansistringkonverter.h#31 0x004080C9(=FOSChampion.exe:0x01:0070C9) D:\Projekte\Schule\foschamp\lib\boost_1_34_1\boost/lexical_cast.hpp#151 Objekt (0x0241A238) [Größe: 32 Byte] war erstellt mit new **(Object was created with new)** | d:\program files\borland\bds\4.0\include\dinkumware\xmemory Zeile 28: | _Ty _FARQ *_Allocate(_SIZT _Count, _Ty _FARQ *) | { // allocate storage for _Count elements of type _Ty |> return ((_Ty _FARQ *)::operator new(_Count * sizeof (_Ty))); | } | Aufrufhierarchie: **(stack-trace)** 0x0040ED90(=FOSChampion.exe:0x01:00DD90) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#28 0x0040E194(=FOSChampion.exe:0x01:00D194) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#143 0x004115CF(=FOSChampion.exe:0x01:0105CF) d:\program files\borland\bds\4.0\include\dinkumware\sstream#105 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 Objekt (0x0241A238) war Gelöscht mit delete **(Object was deleted with delete)** | d:\program files\borland\bds\4.0\include\dinkumware\xmemory Zeile 138: | void deallocate(pointer _Ptr, size_type) | { // deallocate object at _Ptr, ignore size |> ::operator delete(_Ptr); | } | Aufrufhierarchie: **(stack-trace)** 0x004044C6(=FOSChampion.exe:0x01:0034C6) d:\program files\borland\bds\4.0\include\dinkumware\xmemory#138 0x00411628(=FOSChampion.exe:0x01:010628) d:\program files\borland\bds\4.0\include\dinkumware\sstream#111 0x00411183(=FOSChampion.exe:0x01:010183) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#465 0x0040933D(=FOSChampion.exe:0x01:00833D) d:\program files\borland\bds\4.0\include\dinkumware\streambuf#151 0x00405988(=FOSChampion.exe:0x01:004988) d:\program files\borland\bds\4.0\include\dinkumware\ostream#679 0x00405759(=FOSChampion.exe:0x01:004759) D:\Projekte\Schule\foschamp\src\Server\Ansistringkonverter.h#31 ------------------------------------------ Ansistringkonverter.h is the file with the posted operators and line 31 is: std::ostream& operator<<(std::ostream& ostr,const AnsiString& str) { ostr << (str.c_str()); **(31)** return ostr; } Thanks for your help :)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >