HARI OM SHARMA
HARI OM SHARMA

Reputation: 13

How to take vector as input in C++?

I need to take a vector as an input in a C++ program.

The following is my code:

int main() {
        vector<int> nums;
        int target;
        
        cin >> nums;
        cin >> target;
        
        Solution mine;
        mine.twoSum(nums,target);
}

And following is the error shown by the compiler:

Line 32: Char 13: error: invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'vector<int>')
        cin >> nums;
        ~~~ ^  ~~~~

Upvotes: 0

Views: 1006

Answers (3)

Andreas DM
Andreas DM

Reputation: 11008

How to take vector as input in C++?

std::cin has no overload that takes a vector


I suggest that you read the first line of input (assuming space separated) into a string and then the target afterwards

std::string line;
int         target;

std::getline(std::cin, line);
std::cin >> target;

You can then create a string stream out of the first line

std::istringstream iss(line);

And then create a vector using the constructor that takes two iterators

std::vector<int> nums(std::istream_iterator<int>{ iss },
                      std::istream_iterator<int>{});

Upvotes: 0

Gary Strivin&#39;
Gary Strivin&#39;

Reputation: 908

Problem:

You're attempting to read nums directly from std::cin with the operator >>. There isn't any overload of the operator for operator>> that takes a std::ostream (std::cin type) and std::vector<int> (nums's type), so there is a type error.

Solution:

You have to read each number and push one by one to the vector.

Example code:

Here there is an example where the last number goes to target and the rest to the nums.

#include <iostream>
#include <vector>

void readVectorFromStdCin(std::vector<int>& to_read)
{
    for(int n; std::cin >> n;)
        to_read.push_back(n);
}

int main()
{
    std::vector<int> nums;
    int target;

    readVectorFromStdCin(nums);
    target = nums[nums.size()-1];
    nums.pop_back();

    Solution mine;
    mine.twoSum(nums,target);
}

Upvotes: 0

Caleth
Caleth

Reputation: 62779

You need to determine how to distinguish between elements, and also where the end is.

E.g. if you read ints until there are none left in the input, you will have read in the value intended for target.

template<typename T, typename A>
std::istream& operator>>(std::istream& is, std::vector<T, A> & vec) 
{
    for(T value;/* you need to define this condition*/ && (is >> value);) 
    {
        vec.push_back(std::move(value));
    }
    return is;
}

Upvotes: 1

Related Questions