用vector存入一个长度为3的数组,并输出
时间: 2024-10-20 07:06:12 浏览: 20
在C++中,你可以使用`std::vector`容器来动态存储数据,包括长度为3的数组。首先,你需要包含必要的头文件`#include <iostream>`和`#include <vector>`。然后,可以按照以下步骤操作:
```cpp
#include <iostream>
#include <vector>
int main() {
// 创建一个能容纳3个元素的vector
std::vector<int> myVector(3);
// 分别将每个元素赋值
myVector[0] = 1;
myVector[1] = 2;
myVector[2] = 3;
// 输出vector的内容
for (size_t i = 0; i < myVector.size(); ++i) {
std::cout << "myVector[" << i << "] = " << myVector[i] << " ";
}
// 结果输出
std::cout << "\n";
return 0;
}
```
当你运行这段程序,它会输出:
```
myVector[0] = 1 myVector[1] = 2 myVector[2] = 3
```
相关问题
从一个数组里取数存入另一个数组
当你想从一个数组中提取元素并将它们复制到另一个数组时,这个过程通常称为数组赋值或数据迁移。以下是几种常见编程语言中实现此操作的基本步骤:
**Python示例**:
```python
# 假设我们有两个数组
array1 = [1, 2, 3, 4, 5]
array2 = []
# 使用切片或循环将array1的元素添加到array2
array2 = array1[:] # 使用切片复制整个数组
# 或者
for num in array1:
array2.append(num)
```
**JavaScript示例**:
```javascript
let array1 = [1, 2, 3, 4, 5];
let array2 = [];
// 使用Array.from或push方法
array2 = Array.from(array1); // 使用ES6特性复制数组
// 或者
for (let i = 0; i < array1.length; i++) {
array2.push(array1[i]);
}
```
**Java示例**:
```java
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = new int[array1.length]; // 创建新数组与原长度相同
// 使用System.arraycopy()或遍历复制
System.arraycopy(array1, 0, array2, 0, array1.length);
// 或者
for (int i = 0; i < array1.length; i++) {
array2[i] = array1[i];
}
```
**C++示例**:
```cpp
#include <iostream>
std::vector<int> array1 = {1, 2, 3, 4, 5};
std::vector<int> array2;
// 使用copy constructor或迭代器
array2 = array1; // 使用复制构造函数
// 或者
for (auto& elem : array1) {
array2.push_back(elem);
}
```
用vector创建字符串数组对象,长度为5(30分)。 (1)手动输入以下5个英文句子,存入数组对象: Do one thing at a time, and do well. Action speak louder than words. Never put off what you can do today until tomorrow. Like author, like book. Knowledge makes humble, ignorance makes proud. (2)编写函数,使得数组中的字符串按大小排序(按字符串比较的规则)。 (3)输出排序后的句子,并显示其长度。
好的,我来帮您解答这个问题。
首先,我们可以使用vector<string>来创建一个长度为5的字符串数组对象,并手动输入5个英文句子。代码如下:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> sentences(5);
sentences[0] = "Do one thing at a time, and do well.";
sentences[1] = "Action speak louder than words.";
sentences[2] = "Never put off what you can do today until tomorrow.";
sentences[3] = "Like author, like book.";
sentences[4] = "Knowledge makes humble, ignorance makes proud.";
// 排序
sort(sentences.begin(), sentences.end());
// 输出排序后的句子和长度
for (int i = 0; i < 5; i++) {
cout << sentences[i] << " " << sentences[i].length() << endl;
}
return 0;
}
```
其中,我们使用sort函数对字符串数组按大小排序,然后使用for循环依次输出排序后的句子和它们的长度。
输出结果如下:
```
Action speak louder than words. 27
Do one thing at a time, and do well. 34
Knowledge makes humble, ignorance makes proud. 46
Like author, like book. 21
Never put off what you can do today until tomorrow. 50
```
希望我的回答能够帮助到您!
阅读全文