C++ C++;-仅使用非连续索引的值声明数组
我该如何组合C++ C++;-仅使用非连续索引的值声明数组,c++,arrays,C++,Arrays,我该如何组合 string test[8]; test[3] = "Bar"; test[7] = "Foo"; 变成一个单独的声明? 可能类似于字符串测试[8]={3:“Bar”,7:“Foo”}?您不能。如果你想特别使用一个数组,你只需要声明一个比你需要的大的数组。您可以手动分配更多数据,但可能需要其他数据结构 string test[8]; test[3] = "Bar"; test[7] = "Foo"; 您还可以制作地图: #include <iostream> #in
string test[8];
test[3] = "Bar";
test[7] = "Foo";
变成一个单独的声明?可能类似于
字符串测试[8]={3:“Bar”,7:“Foo”}代码>?
您不能。如果你想特别使用一个数组,你只需要声明一个比你需要的大的数组。您可以手动分配更多数据,但可能需要其他数据结构
string test[8];
test[3] = "Bar";
test[7] = "Foo";
您还可以制作地图:
#include <iostream>
#include <map>
using namespace std;
int main(int argc, char *argv[]) {
map<int,string> aMap;
aMap[3] = "Bar";
aMap[7] = "Foo";
}
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[]){
map aMap;
aMap[3]=“Bar”;
aMap[7]=“Foo”;
}
编辑:
这是一个地图参考你是std::array
的粉丝吗?然后你可以这样做:
#include <array>
#include <initializer_list>
#include <iostream>
#include <string>
template<typename T, unsigned n>
std::array<T, n> sparse_array(std::initializer_list<std::pair<unsigned, T>> inits)
{
std::array<T, n> result;
for (auto&& p : inits)
{
result[p.first] = std::move(p.second);
}
return result;
}
int main()
{
auto test = sparse_array<std::string, 8>({
{3, "Bar"},
{7, "Foo"}
});
std::cout << test[7] << test[3] << '\n';
}
#包括
#包括
#包括
#包括
模板
std::array稀疏数组(std::initializer\u list inits)
{
std::数组结果;
用于(自动和p:inits)
{
结果[p.first]=std::move(p.second);
}
返回结果;
}
int main()
{
自动测试=稀疏数组({
{3,“Bar”},
{7,“Foo”}
});
std::cout你试图做的事情是如此危险。想象一下你想要的是:
string test[];//this is not valid the
test[3] = "Bar";
test[99999] = "Foo";
由于数组是结果数据,它将在内存中分配(99999+1)项,这绝对不是正确的方法
您可以使用地图:
std::map<std::size_t,std::string> test;
test[3] = "Bar";
test[7] = "Foo";
请参阅@fredoverflow solution,它是处理数组的一种非常好的方法。无法完成。数组没有“空”空格。但是,如果您描述了您实际试图解决的问题,可能有人会想出一种替代方法。是的,听起来很像XY。而且您需要使用mapIt可以有“”
blanks但是为什么在数组中的特定位置需要有Bar
和Foo
?编译器真的接受string test[];
而括号之间没有数字吗?
std::array<std::pair<std::size_t,string>,2> test={{3,"Bar"},{7,"Foo"}};