Search Results

Search found 5493 results on 220 pages for 'boost regex'.

Page 9/220 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Boost Thread Hanging on _endthreadex

    - by FranticPedantic
    I think I am making a simple mistake, but since I noticed there are many boost experts here, I thought I would ask for help. I am trying to use boost threads(1_40) on windows xp. The main program loads a dll, starts the thread like so (note this is not in a class, the static does not mean static to a class but private to the file). static boost::thread network_thread; network_start() { // do network stuff until quit is signaled } DllClass::InitInstance() { network_thread = boost::thread(boost::bind<void>(network_start)); } DllClass::ExitInstance() { //signal quit (which works) //the following code is slightly verbose because I'm trying to figure out what's wrong try { if (network_thread.joinable() ) { network_thread.join(); } else { TRACE("Too late!"); } } catch (boost::thread_interrupted&) { TRACE("NET INTERRUPTED"); } } The problem is that the main thread is hanging on the join, and the network thread is hanging at the end of _endthreadex. What am I misunderstanding?

    Read the article

  • Generating a reasonable ctags database for Boost

    - by Robert S. Barnes
    I'm running Ubuntu 8.04 and I ran the command: $ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/stdlibcpp /usr/include/c++/4.2.4/ to generate a ctags database for the standard C++ library and STL ( libstdc++ ) on my system for use with the OmniCppComplete vim script. This gave me a very reasonable 4MB tags file which seems to work fairly well. However, when I ran the same command against the installed Boost headers: $ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/boost /usr/include/boost/ I ended up with a 1.4 GB tags file! I haven't tried it yet, but that seems likes it's going to be too large to be useful. Is there a way to get a slimmer, more usable tags file for my installed Boost headers? Edit Just as a note, libstdc++ includes TR1, which has allot of Boost libs in it. So there must be something weird going on for libstdc++ to come out with a 4 MB tags file and Boost to end up with a 1.4 GB tags file.

    Read the article

  • Modelling boost::Lockable with semaphore rather than mutex (previously titled: Unlocking a mutex fr

    - by dan
    I'm using the C++ boost::thread library, which in my case means I'm using pthreads. Officially, a mutex must be unlocked from the same thread which locks it, and I want the effect of being able to lock in one thread and then unlock in another. There are many ways to accomplish this. One possibility would be to write a new mutex class which allows this behavior. For example: class inter_thread_mutex{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } I should point out that the above code doesn't guarantee FIFO access, since if one thread calls lock() while another calls unlock(), this first thread may acquire the lock ahead of other threads which are waiting. (Come to think of it, the boost::thread documentation doesn't appear to make any explicit scheduling guarantees for either mutexes or condition variables). But let's just ignore that (and any other bugs) for now. My question is, if I decide to go this route, would I be able to use such a mutex as a model for the boost Lockable concept. For example, would anything go wrong if I use a boost::unique_lock< inter_thread_mutex for RAII-style access, and then pass this lock to boost::condition_variable_any.wait(), etc. On one hand I don't see why not. On the other hand, "I don't see why not" is usually a very bad way of determining whether something will work. The reason I ask is that if it turns out that I have to write wrapper classes for RAII locks and condition variables and whatever else, then I'd rather just find some other way to achieve the same effect. EDIT: The kind of behavior I want is basically as follows. I have an object, and it needs to be locked whenever it is modified. I want to lock the object from one thread, and do some work on it. Then I want to keep the object locked while I tell another worker thread to complete the work. So the first thread can go on and do something else while the worker thread finishes up. When the worker thread gets done, it unlocks the mutex. And I want the transition to be seemless so nobody else can get the mutex lock in between when thread 1 starts the work and thread 2 completes it. Something like inter_thread_mutex seems like it would work, and it would also allow the program to interact with it as if it were an ordinary mutex. So it seems like a clean solution. If there's a better solution, I'd be happy to hear that also. EDIT AGAIN: The reason I need locks to begin with is that there are multiple master threads, and the locks are there to prevent them from accessing shared objects concurrently in invalid ways. So the code already uses loop-level lock-free sequencing of operations at the master thread level. Also, in the original implementation, there were no worker threads, and the mutexes were ordinary kosher mutexes. The inter_thread_thingy came up as an optimization, primarily to improve response time. In many cases, it was sufficient to guarantee that the "first part" of operation A, occurs before the "first part" of operation B. As a dumb example, say I punch object 1 and give it a black eye. Then I tell object 1 to change it's internal structure to reflect all the tissue damage. I don't want to wait around for the tissue damage before I move on to punch object 2. However, I do want the tissue damage to occur as part of the same operation; for example, in the interim, I don't want any other thread to reconfigure the object in such a way that would make tissue damage an invalid operation. (yes, this example is imperfect in many ways, and no I'm not working on a game) So we made the change to a model where ownership of an object can be passed to a worker thread to complete an operation, and it actually works quite nicely; each master thread is able to get a lot more operations done because it doesn't need to wait for them all to complete. And, since the event sequencing at the master thread level is still loop-based, it is easy to write high-level master-thread operations, as they can be based on the assumption that an operation is complete when the corresponding function call returns. Finally, I thought it would be nice to use inter_thread mutex/semaphore thingies using RAII with boost locks to encapsulate the necessary synchronization that is required to make the whole thing work.

    Read the article

  • Compiling OpenSSL for boost asio for Microsoft Visual Studio 2010

    - by user560106
    I compiled boost with bjam, and then I compiled OpenSSL. Both of them work separately. I set up the links in Visual Studio 10 to point to my OpenSSL library directory. But when I attempt to compile example boost ssl asio programs I get 44 unresolved external linker errors like this one: 1testing.obj : error LNK2019: unresolved external symbol _SSLv23_server_method referenced in function "public: void __thiscall boost::asio::ssl::detail::openssl_context_service::create(struct ssl_ctx_st * &,enum boost::asio::ssl::context_base::method)" (?create@openssl_context_service@detail@ssl@asio@boost@@QAEXAAPAUssl_ctx_st@@W4method@context_base@345@@Z) Can you please give me step-by-step instructions on properly linking OpenSSL to boost? Thank you so much

    Read the article

  • Linker Issues with boost::thread under linux using Eclipse and CMake

    - by OcularProgrammer
    I'm in the process of attempting to port some code across from PC to Ubuntu, and am having some issues due to limited experience developing under linux. We use CMake to generate all our build stuff. Under windows I'm making VS2010 projects, and under Linux I'm making Eclipse projects. I've managed to get my OpenCV stuff ported across successfully, but am having major headaches trying to port my threaded boost apps. Just so we're clear, the steps I have followed so-far on a clean Ubuntu 12 installation. (I've done 2 clean re-installs to try and fix potential library cock-ups, now I'm just giving up and asking): Install Eclipse and Eclipse CDT using my package manager Install CMake and CMake Gui using my package manager Install libboost-all-dev using my package manager So-far that's all I've done. I can create the eclipse project using CMake with no errors, so CMake is successfully finding my boost install. When I try and build through eclipse is when I get issues; The app I'm attempting to build uses boost::asio for some UDP I/O and boost::thread to create worker threads for the asio I/O services. I can successfully compile each module, but when I come to link I get spammed with errors such as: /usr/bin/c++ CMakeFiles/RE05DevelopmentDemo.dir/main.cpp.o CMakeFiles/RE05DevelopmentDemo.dir/RE05FusionListener/RE05FusionListener.cpp.o CMakeFiles/RE05DevelopmentDemo.dir/NewEye/NewEye.cpp.o -o RE05DevelopmentDemo -rdynamic -Wl,-Bstatic -lboost_system-mt -lboost_date_time-mt -lboost_regex-mt -lboost_thread-mt -Wl,-Bdynamic /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libboost_thread-mt.a(thread.o): In function `void boost::call_once<void (*)()>(boost::once_flag&, void (*)()) [clone .constprop.98]': make[2]: Leaving directory `/home/david/Code/Build/Support/RE05DevDemo' (.text+0xc8): undefined reference to `pthread_key_create' /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libboost_thread-mt.a(thread.o): In function `boost::this_thread::interruption_enabled()': (.text+0x540): undefined reference to `pthread_getspecific' make[1]: Leaving directory `/home/david/Code/Build/Support/RE05DevDemo' /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libboost_thread-mt.a(thread.o): In function `boost::this_thread::disable_interruption::disable_interruption()': (.text+0x570): undefined reference to `pthread_getspecific' /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libboost_thread-mt.a(thread.o): In function `boost::this_thread::disable_interruption::disable_interruption()': (.text+0x59f): undefined reference to `pthread_getspecific' Some Gotchas that I have collected from other StackOverflow posts and have already checked: The boost libs are all present at /usr/lib I am not getting any compile errors for inability to find the boost headers, so they must be getting found. I am trying to link statically, but I believe eclipse should be passing the correct arguments to make that happen since my CMakeLists.txt includes SET(Boost_USE_STATIC_LIBS ON) I'm officially out of ideas here, I have tried doing local builds of boost and a bunch of other stuff with no more success. I even re-installed Ubuntu to ensure I haven't completely fracked the libs directories and links with multiple weird versions or anything else. Any help would be muchly appreciated.

    Read the article

  • Using concurrently 2 versions of boost

    - by idimba
    I'm using RHEL 5.3, which is shipped with gcc 4.1.2 and boost 1.33. There're some features I want, that are missing in the boost 1.33. Therefore the thought was to upgrade to fresh boost release 1.43. Is it possible to use concurrently some header-only library(s) from boost 1.43 and the rest from 1.33? For example I want to use unorded_map, which is missing in boost 1.33. Is it possible to use concurrently binary boost libraries from different releases?

    Read the article

  • libstdc++ - compiling failing because of tr1/regex

    - by Radek Šimko
    I have these packages installed on my OpenSUSE 11.3: i | libstdc++45 | Standard shared library for C++ | package i | libstdc++45-devel | Contains files and libraries for development | package But when i'm trying to compile this C++ code: #include <stdio.h> #include <tr1/regex> using namespace std; int main() { int test[2]; const tr1::regex pattern(".*"); test[0] = 1; if (tr1::regex_match("anything", pattern) == false) { printf("Pattern does not match.\n"); } return 0; } using g++ -pedantic -g -O1 -o ./main.o ./main.cpp It outputs this errors: ./main.cpp: In function ‘int main()’: ./main.cpp:13:43: error: ‘printf’ was not declared in this scope radek@mypc:~> nano main.cpp radek@mypc:~> g++ -pedantic -g -O1 -o ./main.o ./main.cpp /tmp/cc0g3GUE.o: In function `basic_regex': /usr/include/c++/4.5/tr1_impl/regex:771: undefined reference to `std::tr1::basic_regex<char, std::tr1::regex_traits<char> >::_M_compile()' /tmp/cc0g3GUE.o: In function `bool std::tr1::regex_match<char const*, char, std::tr1::regex_traits<char> >(char const*, char const*, std::tr1::basic_regex<char, std::tr1::regex_traits<char> > const&, std::bitset<11u>)': /usr/include/c++/4.5/tr1_impl/regex:2144: undefined reference to `bool std::tr1::regex_match<char const*, std::allocator<std::tr1::sub_match<char const*> >, char, std::tr1::regex_traits<char> >(char const*, char const*, std::tr1::match_results<char const*, std::allocator<std::tr1::sub_match<char const*> > >&, std::tr1::basic_regex<char, std::tr1::regex_traits<char> > const&, std::bitset<11u>)' collect2: ld returned 1 exit status What packages should i (un)install to make the code work on my PC?

    Read the article

  • How do I insert format str and don't remove the matched regular expression in input string in boost:

    - by Yadollah
    I want to put space between punctuations and other words in a sentence. But boost::regex_replace() replaces the punctuation with space, and I want to keep a punctuation in the sentence! for example in this code the output should be "Hello . hi , " regex e1("[.,]"); std::basic_string<char> str = "Hello.hi,"; std::basic_string<char> fmt = " "; cout<<regex_replace(str, e1, fmt)<<endl; Can you help me?

    Read the article

  • Help with Boost Grammar

    - by Decmanc04
    I have been using the following win32 console code to try to parse a B Machine Grammar embedded within C++ using Boost Spirit grammar template. I am a relatively new Boost user. The code compiles, but when I run the .exe file produced by VC++2008, the program partially parses the input file. I believe the problem is with my grammar definition or the functions attached as semantic atctions. The code is given below: // BIFAnalyser.cpp : Defines the entry point for the console application. // // /*============================================================================= Copyright (c) Temitope Jos Onunkun 2010 http://www.dcs.kcl.ac.uk/pg/onun/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // // B Machine parser using the Boost "Grammar" and "Semantic Actions". // // // //////////////////////////////////////////////////////////////////////////// #include <boost/spirit/core.hpp> #include <boost/tokenizer.hpp> #include <iostream> #include <string> #include <fstream> #include <vector> #include <utility> /////////////////////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////////////////// // // Semantic actions // //////////////////////////////////////////////////////////////////////////// vector<string> strVect; namespace { //semantic action function on individual lexeme void do_noint(char const* str, char const* end) { string s(str, end); if(atoi(str)) { ; } else { strVect.push_back(s); cout << "PUSH(" << s << ')' << endl; } } //semantic action function on addition of lexemes void do_add(char const*, char const*) { cout << "ADD" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on subtraction of lexemes void do_subt(char const*, char const*) { cout << "SUBTRACT" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on multiplication of lexemes void do_mult(char const*, char const*) { cout << "\nMULTIPLY" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; cout << "\n"; } //semantic action function on division of lexemes void do_div(char const*, char const*) { cout << "\nDIVIDE" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on simple substitution void do_sSubst(char const* str, char const* end) { string s(str, end); //use boost tokenizer to break down tokens typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; boost::char_separator<char> sep("-+/*:=()"); // default char separator Tokenizer tok(s, sep); Tokenizer::iterator tok_iter = tok.begin(); pair<string, string > dependency; //create a pair object for dependencies //save first variable token in simple substitution dependency.first = *tok.begin(); //create a vector object to store all tokens vector<string> dx; // for( ; tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } vector<string> d_hat; //stores set of dependency pairs string dep; //pairs variables as string object for(int unsigned i=1; i < dx.size()-1; i++) { dependency.second = dx.at(i); dep = dependency.first + "|->" + dependency.second + " "; d_hat.push_back(dep); } cout << "PUSH(" << s << ')' << endl; for(int unsigned i=0; i < d_hat.size(); i++) cout <<"\n...\n" << d_hat.at(i) << " "; cout << "\nSIMPLE SUBSTITUTION\n"; } //semantic action function on multiple substitution void do_mSubst(char const* str, char const* end) { string s(str, end); //use boost tokenizer to break down tokens typedef boost::tokenizer<boost::char_separator<char> > Tok; boost::char_separator<char> sep("-+/*:=()"); // default char separator Tok tok(s, sep); Tok::iterator tok_iter = tok.begin(); // string start = *tok.begin(); vector<string> mx; for( ; tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { mx.push_back(*tok_iter ); } mx.push_back("END\n"); //add a marker "end" for(unsigned int i=0; i<mx.size(); i++) { // if(mx.at(i) == "END" || mx.at(i) == "||" ) // break; // else if( mx.at(i) == "||") // do_sSubst(str, end); // else // { // do_sSubst(str, end); // } cout << "\nTokens ... " << mx.at(i) << " "; } cout << "PUSH(" << s << ')' << endl; cout << "MULTIPLE SUBSTITUTION\n"; } } //////////////////////////////////////////////////////////////////////////// // // Simple Substitution Grammar // //////////////////////////////////////////////////////////////////////////// // Simple substitution grammar parser with integer values removed struct Substitution : public grammar<Substitution> { template <typename ScannerT> struct definition { definition(Substitution const& ) { multi_subst = (simple_subst [&do_mSubst] >> +( str_p("||") >> simple_subst [&do_mSubst]) ) ; simple_subst = (Identifier >> str_p(":=") >> expression)[&do_sSubst] ; Identifier = alpha_p >> +alnum_p//[do_noint] ; expression = term >> *( ('+' >> term)[&do_add] | ('-' >> term)[&do_subt] ) ; term = factor >> *( ('*' >> factor)[&do_mult] | ('/' >> factor)[&do_div] ) ; factor = lexeme_d[( (alpha_p >> +alnum_p) | +digit_p)[&do_noint]] | '(' >> expression >> ')' | ('+' >> factor) ; } rule<ScannerT> expression, term, factor, Identifier, simple_subst, multi_subst ; rule<ScannerT> const& start() const { return multi_subst; } }; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "************************************************************\n\n"; cout << "\t\t...Machine Parser...\n\n"; cout << "************************************************************\n\n"; // cout << "Type an expression...or [q or Q] to quit\n\n"; //prompt for file name to be input cout << "Please enter a filename...or [q or Q] to quit:\n\n "; char strFilename[256]; //file name store as a string object cin >> strFilename; ifstream inFile(strFilename); // opens file object for reading //output file for truncated machine (operations only) Substitution elementary_subst; // Simple substitution parser object string str, next; // inFile.open(strFilename); while (inFile >> str) { getline(cin, next); str += next; if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; parse_info<> info = parse(str.c_str(), elementary_subst, space_p); if (info.full) { cout << "\n-------------------------\n"; cout << "Parsing succeeded\n"; cout << "\n-------------------------\n"; } else { cout << "\n-------------------------\n"; cout << "Parsing failed\n"; cout << "stopped at: \": " << info.stop << "\"\n"; cout << "\n-------------------------\n"; } } cout << "Please enter a filename...or [q or Q] to quit\n"; cin >> strFilename; return 0; } The contents of the file I tried to parse, which I named "mf7.txt" is given below: debt:=(LoanRequest+outstandingLoan1)*20 || newDebt := loanammount-paidammount The output when I execute the program is: ************************************************************ ...Machine Parser... ************************************************************ Please enter a filename...or [q or Q] to quit: c:\tplat\mf7.txt PUSH(LoanRequest) PUSH(outstandingLoan1) ADD LoanRequest outstandingLoan1 MULTIPLY LoanRequest outstandingLoan1 PUSH(debt:=(LoanRequest+outstandingLoan1)*20) ... debt|->LoanRequest ... debt|->outstandingLoan1 SIMPLE SUBSTITUTION Tokens ... debt Tokens ... LoanRequest Tokens ... outstandingLoan1 Tokens ... 20 Tokens ... END PUSH(debt:=(LoanRequest+outstandingLoan1)*20) MULTIPLE SUBSTITUTION ------------------------- Parsing failedstopped at: ": " ------------------------- My intention is to capture only the variables in the file, which I managed to do up to the "||" string. Clearly, the program is not parsing beyond the "||" string in the input file. I will appreciate assistance to fix the grammar. SOS, please.

    Read the article

  • How does the ? make a quantifier lazy in regex

    - by Uriel Katz
    I've been looking into regex lately and figured that the ? operator makes the *,+, or ? lazy. My question is how does it do that? Is it that *? for example is a special operator, or does the ? have an effect on the *? In other words, does regex recognize *? as one operator in itself, or does regex recognize *? as the two separate operators * and ?? If it is the case that *? is being recognized as two separate operators, how does the ? affect the * to make it lazy. If ? means that the * is optional, shouldn't this mean that the * doesn't have to exists at all. If so, then in a statement .*? wouldn't regex just match separate letters and the whole string instead of the shorter string? Please explain, I'm desperate to understand.

    Read the article

  • Boost Thread Synchronization

    - by Dave18
    I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'? #include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } boost::mutex mutex; void thread() { for (int i = 0; i < 100; ++i) { wait(1); mutex.lock(); std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; mutex.unlock(); } } int main() { boost::thread t1(thread); boost::thread t2(thread); t1.join(); t2.join(); }

    Read the article

  • Trying to use boost lambda, but my code won't compile

    - by hamishmcn
    Hi, I am trying to use boost lambda to avoid having to write trivial functors. For example, I want to use the lambda to access a member of a struct or call a method of a class, eg: #include <vector> #include <utility> #include <algorithm> #include <boost/lambda/lambda.hpp> using namespace std; using namespace boost::lambda; vector< pair<int,int> > vp; vp.push_back( make_pair<int,int>(1,1) ); vp.push_back( make_pair<int,int>(3,2) ); vp.push_back( make_pair<int,int>(2,3) ); sort(vp.begin(), vp.end(), _1.first > _2.first ); When I try and compile this I get the following errors: error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>' with [ T=boost::lambda::placeholder<1> ] error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>' with [ T=boost::lambda::placeholder<2> ] Since vp contains pair<int,int> I thought that _1.first should work. What I am doing wrong?

    Read the article

  • boost::asio::async_resolve Problem

    - by Moo-Juice
    Hi All, I'm in the process of constructing a Socket class that uses boost::asio. To start with, I made a connect method that took a host and a port and resolved it to an IP address. This worked well, so I decided to look in to async_resolve. However, my callback always gets an error code of 995 (using the same destination host/port as when it worked synchronously). code: Function that starts the resolution: // resolve a host asynchronously template<typename ResolveHandler> void resolveHost(const String& _host, Port _port, ResolveHandler _handler) const { boost::asio::ip::tcp::endpoint ret; boost::asio::ip::tcp::resolver::query query(_host, boost::lexical_cast<std::string>(_port)); boost::asio::ip::tcp::resolver r(m_IOService); r.async_resolve(query, _handler); }; // eo resolveHost Code that calls this function: void Socket::connect(const String& _host, Port _port) { // Anon function for resolution of the host-name and asynchronous calling of the above auto anonResolve = [this](const boost::system::error_code& _errorCode, boost::asio::ip::tcp::resolver_iterator _epIt) { // raise event onResolve.raise(SocketResolveEventArgs(*this, !_errorCode ? (*_epIt).host_name() : String(""), _errorCode)); // perform connect, calling back to anonymous function if(!_errorCode) connect(*_epIt); }; // Resolve the host calling back to anonymous function Root::instance().resolveHost(_host, _port, anonResolve); }; // eo connect The message() function of the error_code is: The I/O operation has been aborted because of either a thread exit or an application request And my main.cpp looks like this: int _tmain(int argc, _TCHAR* argv[]) { morse::Root root; TextSocket s; s.connect("somehost.com", 1234); while(true) { root.performIO(); // calls io_service::run_one() } return 0; } Thanks in advance!

    Read the article

  • Boost Property_Tree iterators, how to handle them?

    - by Andry
    Hello... I am sorry but I asked a question about the same argument before, but my problem concerns another aspect of the one described in that question (How to iterate a boost...). My problem is this, take a look at the following code: #include <iostream> #include <string> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/algorithm/string/trim.hpp> int main(int argc, char** argv) { using boost::property_tree::ptree; ptree pt; read_xml("try.xml", pt); ptree::const_iterator end = pt.end(); for (ptree::const_iterator it = pt.begin(); it != end; it++) std::cout << "Here " << it->? << std::endl; } Well, as told me in the previous question, there is the possibility to use iterators on property_tree in Boost, but I do not know what type it is... and what methods or properties I can use... Well, I assume that it must be another ptree or something representing another xml hierarchy to be browsed again (if I want) but documentation about this is very bad... I do not know why, but in boost docs I cannot find nothing good about this... just something about a macro to browse nodes, but this approach is one I would really like to avoid... Well, the question is so... Once getting the iterator on a ptree, how can I access node name, value, parameters (a node in a xml file)? Thankyou

    Read the article

  • Boost threading/mutexs, why does this work?

    - by Flamewires
    Code: #include <iostream> #include "stdafx.h" #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> using namespace std; boost::mutex mut; double results[10]; void doubler(int x) { //boost::mutex::scoped_lock lck(mut); results[x] = x*2; } int _tmain(int argc, _TCHAR* argv[]) { boost::thread_group thds; for (int x = 10; x>0; x--) { boost::thread *Thread = new boost::thread(&doubler, x); thds.add_thread(Thread); } thds.join_all(); for (int x = 0; x<10; x++) { cout << results[x] << endl; } return 0; } Output: 0 2 4 6 8 10 12 14 16 18 Press any key to continue . . . So...my question is why does this work(as far as i can tell, i ran it about 20 times), producing the above output, even with the locking commented out? I thought the general idea was: in each thread: calculate 2*x copy results to CPU register(s) store calculation in correct part of array copy results back to main(shared) memory I would think that under all but perfect conditions this would result in some part of the results array having 0 values. Is it only copying the required double of the array to a cpu register? Or is it just too short of a calculation to get preempted before it writes the result back to ram? Thanks.

    Read the article

  • Using boost::random to select from an std::list where elements are being removed

    - by user144182
    See this related question on more generic use of the Boost Random library. My questions involves selecting a random element from an std::list, doing some operation, which could potentally include removing the element from the list, and then choosing another random element, until some condition is satisfied. The boost code and for loop look roughly like this: // create and insert elements into list std::list<MyClass> myList; //[...] // select uniformly from list indices boost::uniform_int<> indices( 0, myList.size()-1 ); boost::variate_generator< boost::mt19937, boost::uniform_int<> > selectIndex(boost::mt19937(), indices); for( int i = 0; i <= maxOperations; ++i ) { int index = selectIndex(); MyClass & mc = myList.begin() + index; // do operations with mc, potentially removing it from myList //[...] } My problem is as soon as the operations that are performed on an element result in the removal of an element, the variate_generator has the potential to select an invalid index in the list. I don't think it makes sense to completely recreate the variate_generator each time, especially if I seed it with time(0).

    Read the article

  • codingbat wordEnds using regex

    - by polygenelubricants
    I'm trying to solve wordEnds from codingbat.com using regex. This is the simplest as I can make it with my current knowledge of regex: public String wordEnds(String str, String word) { return str.replaceAll( String.format( ".*?(?=%s)(?<=(.|^))%1$s(?=(.|$))|.+", java.util.regex.Pattern.quote(word) ), "$1$2" ); } String.format is used to inject word into the pattern for both readability and convenience (it's injected twice). Pattern.quote isn't necessary to pass their tests, but I think it's required for a proper regex-based solution. The regex has two major parts: If after matching as few characters as possible ".*?", word can still be found "(?=%s)", then lookbehind to capture any character immediately preceding it "(?<=(.|^))", match word "%1$s" and lookforward to capture any character following it "(?=(.|$))". The initial "if" test ensures that the atomic lookbehind captures only if there's a word Using lookahead to capture the following character doesn't consume it, so it can be used as part of further matching Otherwise match what's left "|.+" Groups 1 and 2 would capture empty strings I think this works in all cases, but it's obviously quite complex. I'm just wondering if others can suggest a simpler regex to do this. Note: I'm not looking for a solution using indexOf and a loop. I want a regex-based replaceAll solution. I also need a working solution that I can just copy-paste into codingbat and passes.

    Read the article

  • Regex pattern failing

    - by Scott Chamberlain
    I am trying a substring to find from the beginning of the string to the point that has the escape sequence "\r\n\r\n" my regex is Regex completeCall = new Regex(@"^.+?\r\n\r\n", RegexOptions.Compiled); it works great as long as you only have strings like 123\r\n\r\n however once you have the pattern 123\r\n 456\r\n\r\n the pattern no longer matches. Any advice on what I am doing wrong? Regex completeCall = new Regex(@"^.+?\r\n\r\n", RegexOptions.Compiled); Regex junkLine = new Regex(@"^\D", RegexOptions.Compiled); private void ClientThread() { StringBuilder stringBuffer = new StringBuilder(); (...) while(true) { (...) Match match = completeCall.Match(stringBuffer.ToString()); while (Match.Success) //once stringBuffer has somthing like "123\r\n 456\r\n\r\n" Match.Success always returns false. { if (junkLine.IsMatch(match.Value)) { (...) } else { (...) } stringBuffer.Remove(0, match.Length); // remove the processed string match = completeCall.Match(stringBuffer.ToString()); // check to see if more than 1 call happened while the thread was sleeping. } Thread.Sleep(1000); }

    Read the article

  • Nested Groups in Regex

    - by cryptic-star
    I'm constructing a regex that is looking for dates. I would like to return the date found and the sentence it was found in. In the code below, the strings on either side of date_string should check for the conditions of a sentence. For your sake, I've omitted the regex for date_string - sufficed to say, it works for picking out dates. While the inside of date_string isn't important, it is grouped as one entire regex. "((?:[^.|?|!]*)"+date_string+"(?:[^.|?|!]*[.|?|!]\s*))" The problem is that date_string is only matching the last number of any given date, presumably because the regex in front of date_string is matching too far and overrunning the date regex. For example, if I say "Independence Day is July 4.", I will get the sentence and 4, even though it should match 'July 4'. In case you're wondering, my regex inside date_string are ordered in such a way that 'July 4' should match first. Is there any way to do this all in one regex? Or do I need to split it up somehow (i.e. split up all text into sentences, and then check each sentence)?

    Read the article

  • Boost and XML (c++)

    - by Nuno
    Hi, Is there any good way (and a simple way too) using boost to read and write xml files? I can't seem to find any simple sample to read xml files using boost? (can you point me some simple sample that use boost for reading and writing xml files) If not boost, is out there any good and simple library to read and write xml files that you can recommend? (it must be a c++ library) Thanks Nuno

    Read the article

  • How Important is Boost to Learn for C++ Developers

    - by mahesh
    I am curious to learn Boost. But i wanted to ask how important it is to learn. What pre-requisite one should need before jumping on Boost. Why i am curious to know about Boost is that many people are talking about Boost on IRC's channels and here in StackOverflow. Thanks in advance.

    Read the article

  • How to remove compiler flag when building Boost

    - by mlo
    I need to build Boost with a non-standard set of flags (due to a conflict between Boost threading and C++/CLI). I'm adding the required flag (/clr) using CXXFLAGS, but this flag conflicts with the Boost default /EHs flag (/clr implies /EHa which is incompatible with /EHs), so that needs to be suppressed. Is there a mechanism like CXXFLAGS to suppress a default Boost flag or must I edit all of the compiler specification files by hand?

    Read the article

  • Signals and threads - good or bad design decision?

    - by Jens
    I have to write a program that performs highly computationally intensive calculations. The program might run for several days. The calculation can be separated easily in different threads without the need of shared data. I want a GUI or a web service that informs me of the current status. My current design uses BOOST::signals2 and BOOST::thread. It compiles and so far works as expected. If a thread finished one iteration and new data is available it calls a signal which is connected to a slot in the GUI class. My question(s): Is this combination of signals and threads a wise idea? I another forum somebody advised someone else not to "go down this road". Are there potential deadly pitfalls nearby that I failed to see? Is my expectation realistic that it will be "easy" to use my GUI class to provide a web interface or a QT, a VTK or a whatever window? Is there a more clever alternative (like other boost libs) that I overlooked? following code compiles with g++ -Wall -o main -lboost_thread-mt <filename>.cpp code follows: #include <boost/signals2.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <iostream> #include <iterator> #include <string> using std::cout; using std::cerr; using std::string; /** * Called when a CalcThread finished a new bunch of data. */ boost::signals2::signal<void(string)> signal_new_data; /** * The whole data will be stored here. */ class DataCollector { typedef boost::mutex::scoped_lock scoped_lock; boost::mutex mutex; public: /** * Called by CalcThreads call the to store their data. */ void push(const string &s, const string &caller_name) { scoped_lock lock(mutex); _data.push_back(s); signal_new_data(caller_name); } /** * Output everything collected so far to std::out. */ void out() { typedef std::vector<string>::const_iterator iter; for (iter i = _data.begin(); i != _data.end(); ++i) cout << " " << *i << "\n"; } private: std::vector<string> _data; }; /** * Several of those can calculate stuff. * No data sharing needed. */ struct CalcThread { CalcThread(string name, DataCollector &datcol) : _name(name), _datcol(datcol) { } /** * Expensive algorithms will be implemented here. * @param num_results how many data sets are to be calculated by this thread. */ void operator()(int num_results) { for (int i = 1; i <= num_results; ++i) { std::stringstream s; s << "["; if (i == num_results) s << "LAST "; s << "DATA " << i << " from thread " << _name << "]"; _datcol.push(s.str(), _name); } } private: string _name; DataCollector &_datcol; }; /** * Maybe some VTK or QT or both will be used someday. */ class GuiClass { public: GuiClass(DataCollector &datcol) : _datcol(datcol) { } /** * If the GUI wants to present or at least count the data collected so far. * @param caller_name is the name of the thread whose data is new. */ void slot_data_changed(string caller_name) const { cout << "GuiClass knows: new data from " << caller_name << std::endl; } private: DataCollector & _datcol; }; int main() { DataCollector datcol; GuiClass mc(datcol); signal_new_data.connect(boost::bind(&GuiClass::slot_data_changed, &mc, _1)); CalcThread r1("A", datcol), r2("B", datcol), r3("C", datcol), r4("D", datcol), r5("E", datcol); boost::thread t1(r1, 3); boost::thread t2(r2, 1); boost::thread t3(r3, 2); boost::thread t4(r4, 2); boost::thread t5(r5, 3); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); datcol.out(); cout << "\nDone" << std::endl; return 0; }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >