【问题标题】:How to push strings (char by char) into a vector of strings如何将字符串(逐个字符)推入字符串向量
【发布时间】:2021-12-10 06:43:59
【问题描述】:

这段代码只是一个原型,我期待我的输出..
我的程序应该能够逐个字符地将字符插入到向量的特定索引;

此程序适用于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;
}

我的预期输出:
z x
r g

错误:
no matching function for call to ‘std::__cxx11::basic_string&lt;char&gt;::basic_string(char)’ { ::new((void *)__p) _Up(std::forward&lt;_Args&gt;(__args)...); }

【问题讨论】:

  • 那么当你运行它时会发生什么?
  • @askman 我收到类似这样的错误“没有匹配函数调用 'std::__cxx11::basic_string::basic_string(char)' { ::new((void * )__p) _Up(std::forward<_args>(__args)...); }"
  • 您可以将其添加到您的帖子中吗?它会让人们更容易帮助你
  • 这将适用于整数向量的向量...猜测是因为字符串与 c_strings 不同...我不能像这样将字符推回
  • 您不能将 char 推送到字符串向量中。更改为 char 向量。矢量>v;

标签: c++ string c++11 vector stl


【解决方案1】:

看来你需要类似下面的东西

#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;
}

程序输出是

z x
r g

否则声明向量像

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

例如

#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;
}

【讨论】:

    【解决方案2】:

    您正试图将 char(字符)存储在 C++ 不会忽略的字符串向量中。

    您应该做的是将字符串存储在字符串容器中(在本例中为向量)

    #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;
    }
    

    PS : 如果你只使用向量和字符串只包含它们,只有一个建议

    # include <vector> 
    # include <string> 
    

    因为#include包含了很多东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2013-08-21
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      相关资源
      最近更新 更多