我想知道,是否有人可以向我解释 vector.insert() 方法中的第二个参数:
迭代器插入(迭代器位置,const value_type& val);
例如,我有一个 wstring 类型的向量,我想在给定位置插入一个 wstring。我已经想出了如何使用迭代器设置位置:
wstring word = "test";
int insertion_pos = 3;
iterator it = words.begin();
words.insert( it + insertion_pos, word );
但是第二个论点呢?如何将 wstring 对象传递给 insert() 方法?非常感谢。
干杯,
马丁
完整示例:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <wchar.h>
#include <vector>
using namespace std;
int main(void) {
// Initialize the vecor with three words.
vector<wstring> words;
wstring word1 = "FirstWord"; // Error msg: no viable conversion from 'const char [10]' to 'wstring' (aka
// 'basic_string<wchar_t>')
wstring word2 = "SecondWord"; // same here
wstring word3 = "ThirdWord"; // same here
words.push_back(word1);
words.push_back(word2);
words.push_back(word3);
// Now try to insert a new word at position 2 (i.e. between "SecondWord "and "ThirdWord"
int position = 2;
wstring word4 = "InsertThis"; // same error as above
iterator it = words.begin(); // Error: use of class template iterator requires template
// arguments
words.insert( it + position, word4 );
// Invalid arguments ' Candidates are: __gnu_cxx::__normal_iterator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
// *,std::vector<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,std::allocator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>>>
// insert(__gnu_cxx::__normal_iterator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
// *,std::vector<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,std::allocator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>>>,
// const std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>> &) void
// insert(__gnu_cxx::__normal_iterator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
// *,std::vector<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,std::allocator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>>>,
// unsigned long int, const std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>> &) void
// insert(__gnu_cxx::__normal_iterator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>
// *,std::vector<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,std::allocator<std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>>>,
// #10000, #10000) '
return EXIT_SUCCESS;
}