简体   繁体   中英

Invalid operands to binary expression error upon printing vector values

My program is taking in file values separated by whitespaces, but I get this weird error when I try to print out the vector(in-loop vector works, but the one I saved the data to to be parsed afterwards, I get invalid operands error). This is what the error looks like:

joj.cpp:36:13: error: invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and
      'std::__1::__vector_base<std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >,
      std::__1::allocator<std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > > >::value_type' (aka
      'std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >'))
                std::cout << data[i] << " ";
                ~~~~~~~~~ ^  ~~~~~~~

And this is my code:

#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

int main()
{
    std::vector<std::vector<unsigned int> > data;
    
    
    std::ifstream file("primer_vhoda.txt");

    std::string line;
    while(std::getline(file, line))
    {
        std::vector<unsigned int>   lineData;
        std::stringstream  lineStream(line);

        int value;
        while(lineStream >> value)
        {
            lineData.push_back(value);
        }
        data.push_back(lineData);
    
        for(int i = 0; i<lineData.size(); i++)
            std::cout << lineData[i] << " ";
    }
    
    for(int i = 0; i<data.size();i++){
        std::cout << data[i] << " ";
    }

}

What I'm trying to print is my data vector( data.push_back(lineData); ) but I can't seem to find the problem, thanks for help

data[i] is a std::vector<unsigned int> - there is no operator<< overload for that. You need to loop over the inner vector, too. Example:

for(auto& inner_vector : data) {
    for(auto value : inner_vector) {
        std::cout << value << ' ';
    }
    std::cout << '\n'; // if you want a newline after each row
}

Or using pre C++11 (without range-based for loops):

for(size_t i = 0; i < data.size(); ++i) {
    for(size_t j = 0; j < data[i].size(); ++j) {
        std::cout << data[i][j] << ' ';
    }
    std::cout << '\n'; // if you want a newline after each row
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM