0

下一个被munmap_chunk()破坏的代码:无效指针

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> modules = {3,5,7};
vector<int> remainders = {2,3,2};
vector<int> m_bigs(modules.size());

int main() {
    int m_big = 1;
    for(int r : remainders) { m_big *= r; };
    transform(m_bigs.begin(), m_bigs.end(), remainders.begin(), remainders.end(), [m_big](int m, int r){ cout << m_big / r << endl; return m_big / r; });
    for(int m : m_bigs) { cout << m << endl; };

    return 0;
}

输出是

6 4 6 4 6 0

但预期是

6 4 6 6 4 6

4

1 回答 1

1
template < class InputIterator1, class InputIterator2,
           class OutputIterator, class BinaryOperator >
  OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
                             InputIterator2 first2, OutputIterator result,
                             BinaryOperator binary_op );

您试图在位置 resters.end()... 插入元素 IN 余数是个坏主意。

正确的代码将是

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> modules = {3,5,7};
vector<int> remainders = {2,3,2};
vector<int> m_bigs(modules.size());

int main() {
    int m_big = 1;
    for(int r : remainders) { m_big *= r; };
    transform(m_bigs.begin(), m_bigs.end(), remainders.begin(), m_bigs.begin(), [m_big](int m, int r){ cout << m_big / r << endl; return m_big / r; });
    for(int m : m_bigs) { cout << m << endl; };

    return 0;
}
于 2012-07-20T09:05:26.597 回答