我正在尝试在循环内创建一个空向量,并希望每次读入循环时向该向量添加一个元素。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<float> myVector();
float x;
while(cin >> x)
myVector.insert(x);
return 0;
}
但是这给我带来了错误信息。
你需要使用std::vector::push_back()
代替:
while(cin >> x)
myVector.push_back(x);
// ^^^^^^^^^
而不是std::vector::insert()
,如链接所示,需要迭代器指示要插入元素的位置。
此外,正如@Joel所评论的那样,你应该在定义向量变量时删除括号。
std::vector<float> myVector;
而不是
std::vector<float> myVector();
通过这样做,你会遇到C++的最令人困扰的解析问题。
std::vector<float> myVector;
而不是std::vector<float> myVector();
- YangmyVector.insert()
,请像这样使用myVector.insert(myVector.end(), x)
。这将在myVector的末尾添加x。
您可以通过myVector.insert(myVector.begin(), x)
在开头插入x。另一种选择是使用std::vector::emplace_back()
而不是std::vector::push_back()
。这样做一些优化,并且不需要一个类型为vector::value_type
的参数,它需要可变数量的参数,这些参数被转发到附加项的构造函数中,而push_back
可能会造成不必要的复制或移动。
在std::vector::emplace_back文档中有演示,这里是一个相关问题here。
用法示例:
std::vector<int> myVector;
while (cin >> x) {
myVector.emplace_back(x);
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vector_of_integers{};
vector_of_integers.push_back(1); // O(1)
vector_of_integers.push_back(3); // O(1)
vector_of_integers.push_back(5); // O(1)
vector_of_integers.push_back(7); // O(1)
for (int i = 8; i <= 10; i++)
vector_of_integers.push_back(i);
// Printing out all the elements of vector of integers - Method 1
copy(vector_of_integers.begin(), vector_of_integers.end(), ostream_iterator<int>(cout, " ")); // 1 3 5 7 8 9 10
cout << endl << endl;
// Inserting '2' at index 1
vector<int>::iterator it{ vector_of_integers.begin() };
advance(it, 1);
vector_of_integers.insert(it, 2); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 2
for (auto const& element : vector_of_integers)
std::cout << element << " "; // 1 2 3 5 7 8 9 10
cout << endl << endl;
// "it" no longer valid, get a new one
it = vector_of_integers.begin();
vector_of_integers.insert(it + 4, 6); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 3
for (it = vector_of_integers.begin(); it != vector_of_integers.end(); it++)
std::cout << *it << ' '; // 1 2 3 5 6 7 8 9 10
cout << endl << endl;
// insert '4' 7 times at index 3
vector<int> new_vector_to_be_inserted(7, 4);
vector_of_integers.insert(vector_of_integers.begin() + 3, new_vector_to_be_inserted.begin(), new_vector_to_be_inserted.end()); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 4
for (int i = 0; i < vector_of_integers.size(); i++)
cout << vector_of_integers.at(i) << ' '; // 1 2 3 4 4 4 4 4 4 4 5 6 7 8 9 10
cout << endl << endl;
return 0;
}
myVector
时去掉括号。 - Joel