如何将字符串(逐个字符)推入字符串向量
Posted
技术标签:
【中文标题】如何将字符串(逐个字符)推入字符串向量【英文标题】: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<char>::basic_string(char)’ ::new((void *)__p) _Up(std::forward<_Args>(__args)...);
【问题讨论】:
那么当你运行它时会发生什么? @askman 我收到类似这样的错误“没有匹配函数调用 'std::__cxx11::basic_string看来你需要类似下面的东西
#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
【讨论】:
以上是关于如何将字符串(逐个字符)推入字符串向量的主要内容,如果未能解决你的问题,请参考以下文章