سؤال

لديّ خريطة متعددة محددة من قبل

typedef std::pair<int, int> comp_buf_pair; //pair<comp_t, dij>
typedef std::pair<int, comp_buf_pair> node_buf_pair;
typedef std::multimap<int, comp_buf_pair> buf_map; //key=PE, value = pair<comp_t, dij>
typedef buf_map::iterator It_buf; 
int summ (int x, int y) {return x+y;}


int total_buf_size = 0;
std::cout << "\nUpdated buffer values" << std::endl;
for(It_buf it = bufsz_map.begin(); it!= bufsz_map.end(); ++it)
{
    comp_buf_pair it1 = it->second;
    // max buffer size will be summ(it1.second)
    //total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), &summ); //error??
    std::cout << "Total buffers required for this config = " << total_buf_size << std::endl;
    std::cout << it->first << " : " << it1.first << " : " << it1.second << std::endl;

}

أرغب في تلخيص جميع القيم التي أشار إليها it1.second كيف يمكن ل std :: تراكم الوظيفة الوصول إلى قيم التكرار الثانية؟

هل كانت مفيدة؟

المحلول

مشكلتك هي مع وظيفة Summ ، فأنت في الواقع بحاجة إلى شيء أفضل من ذلك لتكون قادرًا على التعامل مع نوعين غير متطابقة.

إذا كنت محظوظًا ، فقد يعمل هذا:

int summ(int x, buf_map::value_type const& v) { return x + v.second; }

إذا كنت محظوظًا (اعتمادًا على كيفية accumulate تم تنفيذه) ، يمكنك دائمًا:

struct Summer
{
  typedef buf_map::value_type const& s_type;
  int operator()(int x, s_type v) const { return x + v.second.first; }
  int operator()(s_type v, int x) const { return x + v.second.first; }
};

ثم استخدم:

int result = std::accumulate(map.begin(), map.end(), 0, Summer());

نصائح أخرى

أعتقد أنك ستحتاج فقط إلى تغيير summ وظيفة لأخذ map value_type بدلاً من ذلك. هذا لم يخبره تمامًا ولكنه يجب أن يعطي الفكرة.

int summ (int x, const buf_map::value_type& y) 
{
    return x + y.second;
}

ونسميها:

total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), 0, &summ);

لماذا تعبث مع أزواج تحتوي على أزواج؟ إنه معقد للغاية وسوف يخطئ في ارتكاب أخطاء. لماذا لا تحدد البنية؟

Accumulate هو تعميم لتجميع: إنه يحسب المبلغ (أو بعض العمليات الثنائية الأخرى) من init وجميع العناصر في النطاق [first, last).

... تتم تهيئة النتيجة لأول مرة إلى init. ثم ، لكل مؤلف i في [first, last), ، من البداية إلى النهاية ، يتم تحديثه بواسطة result = result + *i (في الإصدار الأول) أو result = binary_op(result, *i) (في الإصدار الثاني).

sgi.com

لم تكن محاولتك الإصدار الأول أو الثاني ، فقد فاتتك الجزء الرئيسي

total_buf_size = std::accumulate(bufsz_map.begin(), bufsz_map.end(), 0, &summ);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top