How to fix " no viable conversion from 'std::vector<int, std::allocator<int>>::iterator' to 'unsigned int' "?

I am new to Vector while solving Twosum problem from leetcode, encountered following Compilation error :

Line 4: Char 26: error: no viable conversion from 'std::vector<int, std::allocator<int>>::iterator' (aka '__normal_iterator<int *, std::vector<int, std::allocator<int>>>') to 'unsigned int'
    for(unsigned int i=nums.begin();i<nums.end();i++)

Here is my code:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for(unsigned int i=nums.begin();i<nums.end();i++)
        {
            for(int j=i+1;j<=nums.end();j++)
            {
                if(nums[i]+nums[j]==target)
                {
                    vector<int> vec;
                    vec[0]=i;
                    vec[1]=j;
                    break;
                }
            }
        }
        return vec;
     }
};

I tried googling this but didn’t get much. Just wanted to know what does this error mean and how to fix it.

>Solution :

Clearly what you meant to write is

    for(unsigned int i=0;i<nums.size();i++)
    {
        for(int j=i+1;j<nums.size();j++)
        {

You are getting confused between iterators and indexes. You also made a mistake using j<= instead of j<.

Also you should note that the type of a vector index is size_t, so the above would be better written as

    for(size_t i=0;i<nums.size();i++)
    {
        for(size_t j=i+1;j<nums.size();j++)
        {

Another serious mistake is here

                vector<int> vec;
                vec[0]=i;
                vec[1]=j;

This is the common but completely unjustified belief that vectors resize themselves when you assign to an index that does not exist. If you want a vector of size 2 then create it so

                vector<int> vec(2);
                vec[0]=i;
                vec[1]=j;

Or create it at size zero (the default) and add the new items using push_back.

                vector<int> vec;
                vec.push_back(i);
                vec.push_back(j);

A final mistake (nothing to do with vectors specifically) is that you’ve declared your vector inside the loop, but you are trying to return it outside the loop. That’s not allowed.

Leave a Reply