我得到的错误是“expected a ;”。
const int SIZE = 9;
vector<string>possiblePalindromes(SIZE) = // error is shown here
{ "A man a plan a canal Panama",
"The rain in Spain",
"No lemon, no melon",
"radar",
"CS1D",
"Was it a cat I saw?",
"Racecar",
"Saddleback",
"dad" };
我的问题是,这不是有效的声明吗?如果我删除 (SIZE),错误就会消失,但我的意图是声明具有特定大小和一组预定义值的 vector 。这样当我决定遍历 vector 时,比如
for (int i = 0; i < SIZE; ++i)
我可以直接引用 vector 的 SIZE,而不是某个常量“9”。
我对这不起作用的暗示是,当我这样做时
vector<string>possiblePalindromes(SIZE)
我正在声明具有 9 个字符串默认值的大小为 9 的 vector 。这意味着 {} 中包含的所有内容根本不会被读入 vector 。
请您参考如下方法:
事实上,您正在尝试初始化类型为 std::vector<std::string>
的对象同时使用两个构造函数。
第一个构造函数如下
explicit vector(size_type n, const Allocator& = Allocator());
第二个构造函数是
vector(initializer_list<T>, const Allocator& = Allocator());
这没有意义。
您总是可以通过使用其成员函数size
来获取 vector 中元素的数量。 .你总是可以通过使用它的方法 resize
来调整 vector 的大小。 .
此外,您可以在不需要知道元素数量的情况下使用基于范围的 for 循环。
所以就这么写
vector<string>possiblePalindromes =
{ "A man a plan a canal Panama",
"The rain in Spain",
"No lemon, no melon",
"radar",
"CS1D",
"Was it a cat I saw?",
"Racecar",
"Saddleback",
"dad" };
这是一个演示程序
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> possiblePalindromes =
{
"A man a plan a canal Panama",
"The rain in Spain",
"No lemon, no melon",
"radar",
"CS1D",
"Was it a cat I saw?",
"Racecar",
"Saddleback",
"dad"
};
std::cout << "The vecor contains " << possiblePalindromes.size() << " elements\n";
std::cout << "They are:\n";
for ( const auto &s : possiblePalindromes )
{
std::cout << '\t' << s << '\n';
}
return 0;
}
它的输出是
The vecor contains 9 elements
They are:
A man a plan a canal Panama
The rain in Spain
No lemon, no melon
radar
CS1D
Was it a cat I saw?
Racecar
Saddleback
dad