c++字符串数组初始化
c++ string array initialization
我知道我可以在C++中做到这一点:
string s[] = {"hi", "there"};
但是,在不delcare string s[]
的情况下,有没有以这种方式delcare数组?
例如
void foo(string[] strArray){
// some code
}
string s[] = {"hi", "there"}; // Works
foo(s); // Works
foo(new string[]{"hi", "there"}); // Doesn't work
在C++11中,您可以。事先要注意:不要new
数组,没有必要这样做。
首先,string[] strArray
是一个语法错误,应该是string* strArray
或string strArray[]
。我假设这只是为了示例的目的,您不传递任何大小参数。
#include <string>
void foo(std::string* strArray, unsigned size){
// do stuff...
}
template<class T>
using alias = T;
int main(){
foo(alias<std::string[]>{"hi", "there"}, 2);
}
请注意,如果您不需要将数组大小作为额外的参数传递,那会更好,谢天谢地,有一种方法:Templates!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
请注意,这将只匹配堆栈数组,如int x[5] = ...
。或者临时的,通过使用上面的alias
创建的。
int main(){
foo(alias<int[]>{1, 2, 3});
}
在C++11之前,不能使用类型[]初始化数组。然而,最新的c++11提供了(统一的)初始化,所以你可以这样做:
string* pStr = new string[3] { "hi", "there"};
请参阅http://www2.research.att.com/~bs/C++0xFAQ.html#uniform init
有了对C++11初始值设定项列表的支持,这很容易:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
如果没有这一点(例如,对于Visual C++10.0),你可以做这样的事情:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
在C++11及更高版本中,您还可以使用初始化器列表初始化std::vector
。例如:
using namespace std; // for example only
for (auto s : vector<string>{"one","two","three"} )
cout << s << endl;
所以,你的例子会变成:
void foo(vector<string> strArray){
// some code
}
vector<string> s {"hi", "there"}; // Works
foo(s); // Works
foo(vector<string> {"hi", "there"}); // also works
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组