logo
down
shadow

Fastest way to find pair in a vector, remove it while iterating


Fastest way to find pair in a vector, remove it while iterating

Content Index :

Fastest way to find pair in a vector, remove it while iterating
Tag : cpp , By : Ari
Date : November 29 2020, 04:01 AM

this one helps. It is really hard to say what the "fastest way" to do anything is. Even "fast enough" is problematic without knowing your constraints exactly. Therefore, I'm going to give you a few tips to get a (probably) "faster" program; whether it will be fast enough is up to you to decide.
First of all, you probably want to change your sort criterion. Instead of sorting on the second component (the end of the interval, I assume,) you need to sort on the first component and then on the second. This way, an interval that starts sooner will be earlier in the array, and among intervals with the same start, the one that is shortest will be first.
displacement = 0
for all elements in the array, do:
    if current element should be removed, then:
        increment "displacement"
    else:
        move current element back "displacement" places

delete last "displacement" elements
let original vector be A, and the new vector of pairs be B,
t0 = -1
t1 = -1
for all elements in A, do:
    if start time of current element is greater than "t1", then:
         append the pair (t0, t1) to B
         t0 = start time of current element
         t1 = end time of current element
    else:
         t1 = max(t1, end time of current element)
append the pair (t0, t1) to B
remove first element of B (because it is (-1, -1))

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Clojure: Iterating over a vector of vectors to find the first vector that meets a certain condition


Tag : development , By : yossi
Date : March 29 2020, 07:55 AM
around this issue To learn Clojure I'm working on a little Tic Tac Toe game. After completing the first part of the game with relative ease, I've struggled trying to build an intelligent computer player. , First of all, I advice you to use this structure for board position:
(def board [[1 1 0] 
            [0 0 0] 
            [1 0 1]])
(def winning-sets
  '([[0 0] [0 1] [0 2]] 
    [[1 0] [1 1] [1 2]] 
    [[2 0] [2 1] [2 2]]
    [[0 0] [1 0] [2 0]] 
    [[0 1] [1 1] [2 1]] 
    [[0 2] [1 2] [2 2]]
    [[0 0] [1 1] [2 2]]
    [[0 2] [1 1] [2 0]]))
(defn check 
  [target combo] 
  (= (map #(count (filter (partial = %) combo)) [target 0]) '(2 1)))

(defn extract 
  [coords] 
  (apply vector (map (fn [[f s]] ((board f) s)) coords))) 

(filter #(check 1 (extract %)) winning-sets)
user=> (filter #(check 1 (extract %)) winning-sets)
([[0 0] [0 1] [0 2]] 
 [[2 0] [2 1] [2 2]] 
 [[0 0] [1 0] [2 0]] 
 [[0 0] [1 1] [2 2]])

Iterating in a sorted manner over a std::vector<std::pair<T,U> > object


Tag : cpp , By : yatil
Date : March 29 2020, 07:55 AM
Hope this helps I am reading a object from a database of type Foo, as defined below. This object is a vector of Foo Members, where a Foo Members consists of a string id and a container object. , You can use std::sort
#include <algorithm>

bool comparator(const FooMember& i, const FooMember& j)
{
    std::string str1 = i.first;
    boost::algorithm::to_lower(str1);
    std::string str2 = j.first;
    boost::algorithm::to_lower(str2);
    return (str1 < str2); 
}

void sortFoo(Foo& value) {
    std::sort (value.begin(), value.end(), comparator);
}

Fastest way to find all-pair shortest paths in a undirected cycle


Tag : algorithm , By : demize95
Date : March 29 2020, 07:55 AM
To fix this issue In one pass starting from A traverse the graph clockwise, and for every node compute the distance from A. Let's say the distance to the node X is a[X]. This way for any pair (X, Y) of nodes the distance will be:
min(abs(aX - aY), total - abs(aY - aX))
min(abs(aB - aF), total - abs(aB - aF)) = 
min(abs( 1 -  3),     6 - abs( 1 -  3)) = 
min(           2,                    4) =
2

Fastest way to find a vector in a vector of vectors


Tag : cpp , By : S. Fenz
Date : March 29 2020, 07:55 AM

Find int in Vector of pairs vector <pair <int, vector <SavingsAccount*>>> using find_if


Tag : cpp , By : Jonathan Bernard
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further My data structure is: , Use a lambda as predicate for std::find_if():
#include <algorithm>
#include <utility>
#include <vector>
#include <iostream>

using namespace std;

struct SavingsAccount{};

int main()
{
    vector<pair<int, vector<SavingsAccount>>> accVec;
    vector<pair<int, vector<SavingsAccount>>>::iterator iter;

    do {
        cout << "Enter The Account Number In Which You Want To Deposit: ";
        int accID;
        cin >> accID;

        iter = find_if(accVec.begin(), accVec.end(),
                       [=](pair<int, vector<SavingsAccount>> const &accPair) {
                           return accPair.first == accID;
                       }
        );

        if (iter == accVec.end()) {
            cout << endl << "ERROR: Account Does Not Exist. Try Again." << endl;
        }
    } while (iter == accVec.end());
}
#include <algorithm>
#include <utility>
#include <vector>
#include <iostream>

using namespace std;

struct SavingsAccount{};

class AccountFinder
{
    int accID;

public:
    AccountFinder(int accID) : accID{ accID } {};

    bool operator()(pair<int, vector<SavingsAccount>> const &accPair)
    {
        return accPair.first == accID;
    }
};

int main()
{
    vector<pair<int, vector<SavingsAccount>>> accVec;
    vector<pair<int, vector<SavingsAccount>>>::iterator iter;

    do {
        cout << "Enter The Account Number In Which You Want To Deposit: ";
        int accID;
        cin >> accID;

        iter = find_if(accVec.begin(), accVec.end(), AccountFinder(accID));

        if (iter == accVec.end()) {
            cout << endl << "ERROR: Account Does Not Exist. Try Again." << endl;
        }
    } while (iter == accVec.end());
}
Related Posts Related QUESTIONS :
  • template type's ctor arguments at instantiation time
  • Get list of windows in taskbar on Windows 7?
  • Curl connection options
  • Best cross-platform solution for network server?
  • simple c++ file opening issue
  • Switching from C++ (with a lot of STL use) to C for interpreter building
  • How can I access the JPEG image pixels as a 3D array like we do in MATLAB?
  • What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
  • Avoid allocating in constructor or preserve simplicity (and RAII?)
  • Can C++ raise an error when std array initialization is too small?
  • Reference to end is ambiguous
  • Problem with basic usage of std::enable_if
  • How to print out a decimal number as octal number using setiosflags in C++
  • Open Visual Studio with solution and specific file and line
  • Enum value based on template type
  • Is there any way to swap nodes in std::list?
  • How to copy QString into wchar_t buffer
  • Make the compiler generate an empty default function for an std::function
  • Insert or push_back to end of a std::vector?
  • Best practice for const temporary types
  • Include CSV File in Complied Binary
  • Issue with binding non static function to callback
  • How can read from some files and write content of them with different form into files with same names
  • Why does auto deduce this variable as double and not float?
  • no instance of overloaded function "std::make_unique" matches the argument list, but works with unique_ptr con
  • How to see array size from a pointer in c++
  • Error taking address of temporary in Eclipse
  • Using an iterator to go through a vector and modify the contents
  • Are extern extern "C", and extern "C" extern, allowed?
  • Can't solve C2660 and C2065 Errors
  • C referencing C++ extern
  • How to write the definition of a derived class in c++?
  • Why when I include <cmath> I need to use the namespace std too?
  • How to assign a 32-bit unsigned integer to a bit field containing 32 bits
  • Why does the same class being defined in multiple .cpp files not cause a linker multiple definition error?
  • C++ 11db error when trying to quit the program in xcode. beginner level
  • Add content of a vector into a Capnproto map object
  • Recursively Pass Template Template To a Template Template Function
  • Swap rows in a 2D array with std::swap. How does it work?
  • Is there any situation in which an object's storage might change during its lifetime?
  • clang++ always generates empty profraw coverage reports
  • Do memory leaks persist after program completion if the OS does not clear it?
  • How to link library using cmake
  • How to use getters and setters without generating a copy?
  • Generating multiple amounts of the same sprite broken
  • function in c++ why my compiler didn't recognize the error()
  • Relationship between copy(...) and copy(seq, ...)
  • Are <cmath> functions required to be `noexcept` in C++17?
  • How to find a struct list item
  • How can you handle DLL versions when referencing C++ DLL's over COM from VBScript with CreateObject?
  • Do not understand how c++ set works
  • Actual build date in C++
  • How to link to already compiled external shared libraries in RCPP using Makevars?
  • combination of enable_if + std::less + sizeof... makes MSVC fail
  • Can you call the destructor without calling the constructor?
  • How do I prevent a function from freeing memory of a local variable?
  • Why am I getting an exception with a push involved with a shared pointer?
  • Resizing an array by pointer
  • avoiding dynamic_cast without increasing coupling
  • I cannot solve the else part in my if-else ladder?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com