Search code examples
c++vectorinitialization

C++ vector initialization produces unexpected output


I have the following code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> nums = {2, 3, 4, 5};
    sort(nums.begin(), nums.end());
    int target = 20;
    int N = nums.size();
    int clo = 1e9;
    vector<int> res(3);
    for (int i = 0; i < N; i ++) {
        for (int j = i + 1; j < N; j ++) {
            int t = target - nums[i] - nums[j];
            int l = j + 1, r = N - 1;
            while (l <= r) {
                int m = (l + r) / 2;
                if (nums[m] <= t) {
                    l = m + 1;
                }
                else r = m - 1;
            }
            int dif = abs(target - nums[i] - nums[j] - nums[l]);
            if (dif < clo) {
                clo = dif;
                res = {nums[i], nums[j], nums[l]};
                printf("%d %d %d-------", nums[i], nums[j], nums[l]);
                printf("%d %d %d\n", res[0], res[1], res[2]);
            }
        }
    }
}

specifically these two lines

printf("%d %d %d-------", nums[i], nums[j], nums[l]);
printf("%d %d %d\n", res[0], res[1], res[2]);

which are producing different outputs on some iterations

Why is that happening?

I've tried doing res[0] = nums[i], res[1] = nums[j], res[2] = nums[l] instead that that works perfectly.

I think the problem might be the initialization using curly braces?

sidenote: I'm trying to solve this problem


Solution

  • Try this. Should give leftmost of the target number present.

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        vector<int> nums = {2, 3, 4, 5};
        sort(nums.begin(), nums.end());
        int target = 20;
        int N = nums.size();
        int clo = 1e9;
        vector<int> res(3);
        for (int i = 0; i < N; i ++) {
            for (int j = i + 1; j < N; j ++) {
                int t = target - nums[i] - nums[j];
                int l = j + 1, r = N;
                while (l < r) {
                    int m = (l + r) / 2;
                    if (t > nums[m]) {
                        l = m + 1;
                    }
                    else r = m;
                }
                int dif = abs(target - nums[i] - nums[j] - nums[l]);
                if (dif < clo) {
                    clo = dif;
                    res = {nums[i], nums[j], nums[l]};
                    printf("%d %d %d-------", nums[i], nums[j], nums[l]);
                    printf("%d %d %d\n", res[0], res[1], res[2]);
                }
            }
        }
    }