Home > Net >  How to push strings (char by char) into a vector of strings
How to push strings (char by char) into a vector of strings

Time:10-24

This code is just a prototype, how I'm expecting my output..
My program should be able to insert char by char to particular index of vector;

This program works fine for vector<vector<int>>

#include<bits/stdc  .h>

using namespace std;

int main()
{
  
  vector<vector<string>>v;

  for(auto i=0;i<5;i  )
  v.emplace_back(vector<string>());
  
  v[0].emplace_back('z');
  v[1].emplace_back('r');
  v[0].emplace_back('x');
  v[1].emplace_back('g');
  
  for(auto i:v){
  for(auto j:i)
  cout<<j<<" ";cout<<endl;}
  
  
  return 0;
}

My Expected output:
z x
r g

Error:
no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char)’ { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

CodePudding user response:

You are trying to store char (character) in string vector that is not something C ignore.

what you should be doing is storing strings in the string container (vector in this case)

#include<bits/stdc  .h>

using namespace std;

int main()
{
  
  vector<vector<string>>v;

  for(auto i=0;i<5;i  )
    v.emplace_back(vector<string>());

  v[0].emplace_back("z"); // here you are doing 'z' that is a character instead 
  v[1].emplace_back("r"); // use "z" which signifies a string
  v[0].emplace_back("x");
  v[1].emplace_back("g");
  
  for(auto i:v){
    for(auto j:i)
        cout<<j<<" ";
    cout<<endl;
  }

  return 0;
}

Keep coding keep loving C

PS : Just one advice if you are just using vectors and strings only include them

# include <vector> 
# include <string> 

because #include<bits/stdc .h> includes a lot of things

CodePudding user response:

It seems you need something like the following

#include <iostream>
#include <string>
#include <vector>

int main() 
{
    std::vector<std::vector<std::string>> v( 2 );
    
    v[0].emplace_back( 1, 'z' );
    v[1].emplace_back( 1, 'r' );
    v[0][0].append( 1, ' ' );
    v[1][0].append( 1, ' ' );
    v[0][0].append( 1, 'x' );
    v[1][0].append( 1, 'g' );
  
    for ( const auto &item : v )
    {
        std::cout << item[0] << '\n';
    }
    
    return 0;
}

The program output is

z x
r g

Otherwise declare the vector like

std::vector<std::vector<char>> v;

For example

#include <iostream>
#include <string>
#include <vector>

int main() 
{
    std::vector<std::vector<char>> v( 2 );
    
    v[0].emplace_back( 'z' );
    v[1].emplace_back( 'r' );
    v[0].emplace_back( 'x' );
    v[1].emplace_back( 'g' );
  
    for ( const auto &line : v )
    {
        for ( const auto &item : line )
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    
    return 0;
}
  • Related