logo
down
shadow

Map, pair-vector or two vectors...?


Map, pair-vector or two vectors...?

Content Index :

Map, pair-vector or two vectors...?
Tag : cpp , By : user123585
Date : November 23 2020, 01:01 AM

Any of those help If iteration needs to be fast, you don't want std::map<...>: its iteration is a tree-walk which quickly gets bad. std::map<...> is really only reasonable if you have many mutations to the sequence and you need the sequence ordered by the key. If you have mutations but you don't care about the order std::unordered_map<...> is generally a better alternative. Both kinds of maps assume you are looking things up by key, though. From your description I don't really see that to be the case.
std::vector<...> is fast to iterated. It isn't ideal for look-ups, though. If you keep it ordered you can use std::lower_bound() to do a std::map<...>-like look-up (i.e., the complexity is also O(log n)) but the effort of keeping it sorted may make that option too expensive. However, it is an ideal container for keeping a bunch objects together which are iterated.
// version using std::vector<std::pair<Nuclide, double> >
// - it would just use std::vector<std::pair<Nuclide, double>::iterator as iterator
auto nuclide_projection = [](Sample::key& key) -> Nuclide& {
    return key.first;
}
auto value_projecton = [](Sample::key& key) -> double {
    return key.second;
}

// version using two std::vectors:
// - it would use an iterator interface to an integer, yielding a std::size_t for *it
struct nuclide_projector {
    std::vector<Nuclide>& nuclides;
    auto operator()(std::size_t index) -> Nuclide& { return nuclides[index]; }
};
constexpr nuclide_projector nuclide_projection;
struct value_projector {
    std::vector<double>& values;
    auto operator()(std::size_t index) -> double& { return values[index]; }
};
constexpr value_projector value_projection;
template <typename Iterator>
void print(std::ostream& out, Iterator begin, Iterator end) {
    for (; begin != end; ++begin) {
         out << "nuclide=" << nuclide_projection(*begin) << ' '
             << "value=" << value_projection(*begin) << '\n';
    }
}

Comments
No Comments Right Now !

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

Share : facebook icon twitter icon

Pair of vectors instead of a vector<pair>?


Tag : cpp , By : user179271
Date : March 29 2020, 07:55 AM
I hope this helps . Maybe you are looking something like flat_(multi)map/set from Boost.Container ?

Vector of pairs or pair of vectors?


Tag : cpp , By : Jonathan Bernard
Date : March 29 2020, 07:55 AM
may help you . In my code I'm dealing with a set of measurements (a vector of float), in which each element has two associated uncertainties (say +up/-down). Let's say I want to dump on screen these values, something like , This:

sorting vector of pair of vectors


Tag : cpp , By : Andrew L.
Date : March 29 2020, 07:55 AM
this one helps. You may have a particularly complicated data structure with a super specific and arbitrarily ordering that you want to define on it, but no matter. The nice thing about std::sort is that it's completely accommodating:
std::sort(A.begin(), A.end(), MyComparator);
typedef pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > Elem;

bool MyComparator(const Elem& a, const Elem& b) {
    // return true if a should go before b in the sort

    // step 1 is apparently to do a vector comparison
    for (size_t i = 0; i < a.second.second.size(); ++i) {
        if (i == b.second.second.size()) {
            return false;           
        }
        else if (a[i] < b[i]) {
            return true;
        }
        else if (a[i] > b[i]) {
            return false;
        }
    }
    if (a.second.second.size() < b.second.second.size()) {
        return true;
    }

    // if we got here, the two vectors compare equal
    // so onto the next steps 2, 3, ...
    // etc.
}

Is it possible to get scipy.integrate.odeint to work with a pair of vectors (or vector of vectors)


Tag : python , By : yogan
Date : March 29 2020, 07:55 AM
this one helps. As Warren mentioned, the answer is that odeint does require 1-D arrays. The trick is to set up the function passed to odeint so that it converts the 1-D array passed in as the second in the vector form desired - in this case, 2 3-D vectors, perform the calculations in vector form, then reshape the result back as a 1-D array.
The answer demonstrates the technique, using the convenient numpy reshape function.
def position_and_velocity (x, t, params):
    # x = (S, V) as vectors
    # Ordinary differential equation - velocity of an object in frictionless free-fall.
    G = params
    g = np.array ([0, 0, -G])
    # convert the 6 element vector to 2 3 element vectors of displacement and velocity
    # to use vector formulation of the math
    s,v = x.reshape (2,3)
    acceleration = np.array ([v * t, g])
    # reshape the two vector results back into one for odeint
    return np.reshape (acceleration, 6)

s = np.array ([0, 0, 5])
v = np.array ([40, 10, 0])
SV0 = np.array ([s, v])
# pass reshaped displacement and velocity vector to odeint
soln = odeint (position_and_velocity, np.reshape (SV0, 6), t, args = (G,))

Working with a vector of pair vectors?


Tag : cpp , By : Tom Smith
Date : March 29 2020, 07:55 AM
seems to work fine I've been search around Google but I didn't find what I need. I'm trying to create a vector that allows me to add 3 (and after I'll need to store 4) variables, access and sort them. , First to access to the different elements:
for (auto& x :chromosomes) 
    cout <<x.first<<": "<<x.second.first<<" "<<x.second.second<<endl; 
sort(chromosomes.begin(), chromosomes.end(),
             [](auto &x, auto &y) { return x.second.first<y.second.first;});
sort(chromosomes.begin(), chromosomes.end(),
            [](auto &x, auto &y) { return x.second.first<y.second.first 
                          || (x.second.first==y.second.first 
                                 && x.second.second<y.second.second );});
struct Chromosome {
    string name; 
    int WSA; 
    double fault_percent;  
};   

vector <Chromosome> chromosomes;  
sort(chromosomes.begin(), chromosomes.end(),
            [](auto &x, auto &y) { return x.WSA<y.WSA 
                          || (x.WSA==y.WSA && x.fault_percent<y.fault_percent );});
Related Posts Related QUESTIONS :
  • Template argument deduction for inheriting specializations
  • dlopen undefined reference
  • Member function of class with template arguments and default arguments outside class
  • Is it possible to implement a non-owning "slightly smart" pointer on top of standard weak pointers?
  • how to configure the AcquireCredentialsHandleA correctly
  • Using private versions of global extern variables with OpenMP
  • Eigen Block wrong amount of columns and rows
  • Memory alignment rules in inheritance
  • Is nullptr falsy?
  • tm_wday returns a large integer outside 0-6 range
  • Scope a using declaration, inside a header
  • How to specify constructor's template arguments inside a new expression?
  • Sort an array via x86 Assembly (embedded in C++)?? Possible?
  • How to Replace only Part of the Variable using #define
  • How do you compare the performace of valarrays vs built-in arrays?
  • Is it normal for C++ static initialization to appear twice in the same backtrace?
  • c++ generate a good random seed for psudo random number generators
  • Why isn't my operator overloading working properly?
  • Getting meaningful error messages from fstream's in C++
  • C++: Converting Julian dates to Gregorian
  • Could someone explain this interesting behaviour with Sleep(1)?
  • Is it possible to roll a significantly faster version of modf
  • Updating pointer using signals and slots
  • How are classes more secure than structures?
  • finding "distance" between two pixel's colors
  • C++ Greatest Number Verification
  • Why does my token return NULL and how can I fix it?(c++)
  • C++ enforce conditions on inherited classes
  • what happened if an exception is not captured?
  • Redundant naming in C/C++ typedefs/structs
  • question about STL thread-safe and STL debugging
  • killing a separate thread having a socket
  • Returning the size of available virtual memory at run-time in C++
  • Parallel computing for integrals
  • How do I force my std::map to deallocate memory used?
  • C++ Templates: implicit conversion, no matching function for call to ctor
  • Adding python script to c++ project
  • C++ private pointer "leaking"?
  • Initializing Primitive Array to One Value
  • how is push_back implemented in STL vector?
  • C++ Profiling: KiFastSystemCallRet
  • Multiple rows with a single INSERT in SQLServer 2008
  • Use super class's address/pointer in initialization list
  • double fork using vfork
  • Convert char pointer (char*) to struct
  • Does anyone have good tips for using pc-lint?
  • C++ How fast is passing around objects?
  • 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++
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com